xref: /openbsd-src/gnu/llvm/clang/lib/CodeGen/CGCall.cpp (revision 7a9b00ce7716f522d49aa36666c74a71cd12203a)
1e5dd7070Spatrick //===--- CGCall.cpp - Encapsulate calling convention details --------------===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // These classes wrap the information about a call or function
10e5dd7070Spatrick // definition used to handle ABI compliancy.
11e5dd7070Spatrick //
12e5dd7070Spatrick //===----------------------------------------------------------------------===//
13e5dd7070Spatrick 
14e5dd7070Spatrick #include "CGCall.h"
15e5dd7070Spatrick #include "ABIInfo.h"
16e5dd7070Spatrick #include "CGBlocks.h"
17e5dd7070Spatrick #include "CGCXXABI.h"
18e5dd7070Spatrick #include "CGCleanup.h"
19ec727ea7Spatrick #include "CGRecordLayout.h"
20e5dd7070Spatrick #include "CodeGenFunction.h"
21e5dd7070Spatrick #include "CodeGenModule.h"
22e5dd7070Spatrick #include "TargetInfo.h"
23e5dd7070Spatrick #include "clang/AST/Attr.h"
24e5dd7070Spatrick #include "clang/AST/Decl.h"
25e5dd7070Spatrick #include "clang/AST/DeclCXX.h"
26e5dd7070Spatrick #include "clang/AST/DeclObjC.h"
27e5dd7070Spatrick #include "clang/Basic/CodeGenOptions.h"
28e5dd7070Spatrick #include "clang/Basic/TargetBuiltins.h"
29e5dd7070Spatrick #include "clang/Basic/TargetInfo.h"
30e5dd7070Spatrick #include "clang/CodeGen/CGFunctionInfo.h"
31e5dd7070Spatrick #include "clang/CodeGen/SwiftCallingConv.h"
32e5dd7070Spatrick #include "llvm/ADT/StringExtras.h"
33e5dd7070Spatrick #include "llvm/Analysis/ValueTracking.h"
34a0747c9fSpatrick #include "llvm/IR/Assumptions.h"
35e5dd7070Spatrick #include "llvm/IR/Attributes.h"
36e5dd7070Spatrick #include "llvm/IR/CallingConv.h"
37e5dd7070Spatrick #include "llvm/IR/DataLayout.h"
38e5dd7070Spatrick #include "llvm/IR/InlineAsm.h"
39e5dd7070Spatrick #include "llvm/IR/IntrinsicInst.h"
40e5dd7070Spatrick #include "llvm/IR/Intrinsics.h"
41*7a9b00ceSrobert #include "llvm/IR/Type.h"
42e5dd7070Spatrick #include "llvm/Transforms/Utils/Local.h"
43*7a9b00ceSrobert #include <optional>
44e5dd7070Spatrick using namespace clang;
45e5dd7070Spatrick using namespace CodeGen;
46e5dd7070Spatrick 
47e5dd7070Spatrick /***/
48e5dd7070Spatrick 
ClangCallConvToLLVMCallConv(CallingConv CC)49e5dd7070Spatrick unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC) {
50e5dd7070Spatrick   switch (CC) {
51e5dd7070Spatrick   default: return llvm::CallingConv::C;
52e5dd7070Spatrick   case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
53e5dd7070Spatrick   case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
54e5dd7070Spatrick   case CC_X86RegCall: return llvm::CallingConv::X86_RegCall;
55e5dd7070Spatrick   case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
56e5dd7070Spatrick   case CC_Win64: return llvm::CallingConv::Win64;
57e5dd7070Spatrick   case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
58e5dd7070Spatrick   case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
59e5dd7070Spatrick   case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
60e5dd7070Spatrick   case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
61e5dd7070Spatrick   // TODO: Add support for __pascal to LLVM.
62e5dd7070Spatrick   case CC_X86Pascal: return llvm::CallingConv::C;
63e5dd7070Spatrick   // TODO: Add support for __vectorcall to LLVM.
64e5dd7070Spatrick   case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
65e5dd7070Spatrick   case CC_AArch64VectorCall: return llvm::CallingConv::AArch64_VectorCall;
66*7a9b00ceSrobert   case CC_AArch64SVEPCS: return llvm::CallingConv::AArch64_SVE_VectorCall;
67*7a9b00ceSrobert   case CC_AMDGPUKernelCall: return llvm::CallingConv::AMDGPU_KERNEL;
68e5dd7070Spatrick   case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
69e5dd7070Spatrick   case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv();
70e5dd7070Spatrick   case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
71e5dd7070Spatrick   case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
72e5dd7070Spatrick   case CC_Swift: return llvm::CallingConv::Swift;
73a0747c9fSpatrick   case CC_SwiftAsync: return llvm::CallingConv::SwiftTail;
74e5dd7070Spatrick   }
75e5dd7070Spatrick }
76e5dd7070Spatrick 
77e5dd7070Spatrick /// Derives the 'this' type for codegen purposes, i.e. ignoring method CVR
78e5dd7070Spatrick /// qualification. Either or both of RD and MD may be null. A null RD indicates
79e5dd7070Spatrick /// that there is no meaningful 'this' type, and a null MD can occur when
80e5dd7070Spatrick /// calling a method pointer.
DeriveThisType(const CXXRecordDecl * RD,const CXXMethodDecl * MD)81e5dd7070Spatrick CanQualType CodeGenTypes::DeriveThisType(const CXXRecordDecl *RD,
82e5dd7070Spatrick                                          const CXXMethodDecl *MD) {
83e5dd7070Spatrick   QualType RecTy;
84e5dd7070Spatrick   if (RD)
85e5dd7070Spatrick     RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
86e5dd7070Spatrick   else
87e5dd7070Spatrick     RecTy = Context.VoidTy;
88e5dd7070Spatrick 
89e5dd7070Spatrick   if (MD)
90e5dd7070Spatrick     RecTy = Context.getAddrSpaceQualType(RecTy, MD->getMethodQualifiers().getAddressSpace());
91e5dd7070Spatrick   return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
92e5dd7070Spatrick }
93e5dd7070Spatrick 
94e5dd7070Spatrick /// Returns the canonical formal type of the given C++ method.
GetFormalType(const CXXMethodDecl * MD)95e5dd7070Spatrick static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
96e5dd7070Spatrick   return MD->getType()->getCanonicalTypeUnqualified()
97e5dd7070Spatrick            .getAs<FunctionProtoType>();
98e5dd7070Spatrick }
99e5dd7070Spatrick 
100e5dd7070Spatrick /// Returns the "extra-canonicalized" return type, which discards
101e5dd7070Spatrick /// qualifiers on the return type.  Codegen doesn't care about them,
102e5dd7070Spatrick /// and it makes ABI code a little easier to be able to assume that
103e5dd7070Spatrick /// all parameter and return types are top-level unqualified.
GetReturnType(QualType RetTy)104e5dd7070Spatrick static CanQualType GetReturnType(QualType RetTy) {
105e5dd7070Spatrick   return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
106e5dd7070Spatrick }
107e5dd7070Spatrick 
108e5dd7070Spatrick /// Arrange the argument and result information for a value of the given
109e5dd7070Spatrick /// unprototyped freestanding function type.
110e5dd7070Spatrick const CGFunctionInfo &
arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP)111e5dd7070Spatrick CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
112e5dd7070Spatrick   // When translating an unprototyped function type, always use a
113e5dd7070Spatrick   // variadic type.
114e5dd7070Spatrick   return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
115e5dd7070Spatrick                                  /*instanceMethod=*/false,
116*7a9b00ceSrobert                                  /*chainCall=*/false, std::nullopt,
117e5dd7070Spatrick                                  FTNP->getExtInfo(), {}, RequiredArgs(0));
118e5dd7070Spatrick }
119e5dd7070Spatrick 
addExtParameterInfosForCall(llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> & paramInfos,const FunctionProtoType * proto,unsigned prefixArgs,unsigned totalArgs)120e5dd7070Spatrick static void addExtParameterInfosForCall(
121e5dd7070Spatrick          llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
122e5dd7070Spatrick                                         const FunctionProtoType *proto,
123e5dd7070Spatrick                                         unsigned prefixArgs,
124e5dd7070Spatrick                                         unsigned totalArgs) {
125e5dd7070Spatrick   assert(proto->hasExtParameterInfos());
126e5dd7070Spatrick   assert(paramInfos.size() <= prefixArgs);
127e5dd7070Spatrick   assert(proto->getNumParams() + prefixArgs <= totalArgs);
128e5dd7070Spatrick 
129e5dd7070Spatrick   paramInfos.reserve(totalArgs);
130e5dd7070Spatrick 
131e5dd7070Spatrick   // Add default infos for any prefix args that don't already have infos.
132e5dd7070Spatrick   paramInfos.resize(prefixArgs);
133e5dd7070Spatrick 
134e5dd7070Spatrick   // Add infos for the prototype.
135e5dd7070Spatrick   for (const auto &ParamInfo : proto->getExtParameterInfos()) {
136e5dd7070Spatrick     paramInfos.push_back(ParamInfo);
137e5dd7070Spatrick     // pass_object_size params have no parameter info.
138e5dd7070Spatrick     if (ParamInfo.hasPassObjectSize())
139e5dd7070Spatrick       paramInfos.emplace_back();
140e5dd7070Spatrick   }
141e5dd7070Spatrick 
142e5dd7070Spatrick   assert(paramInfos.size() <= totalArgs &&
143e5dd7070Spatrick          "Did we forget to insert pass_object_size args?");
144e5dd7070Spatrick   // Add default infos for the variadic and/or suffix arguments.
145e5dd7070Spatrick   paramInfos.resize(totalArgs);
146e5dd7070Spatrick }
147e5dd7070Spatrick 
148e5dd7070Spatrick /// Adds the formal parameters in FPT to the given prefix. If any parameter in
149e5dd7070Spatrick /// FPT has pass_object_size attrs, then we'll add parameters for those, too.
appendParameterTypes(const CodeGenTypes & CGT,SmallVectorImpl<CanQualType> & prefix,SmallVectorImpl<FunctionProtoType::ExtParameterInfo> & paramInfos,CanQual<FunctionProtoType> FPT)150e5dd7070Spatrick static void appendParameterTypes(const CodeGenTypes &CGT,
151e5dd7070Spatrick                                  SmallVectorImpl<CanQualType> &prefix,
152e5dd7070Spatrick               SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
153e5dd7070Spatrick                                  CanQual<FunctionProtoType> FPT) {
154e5dd7070Spatrick   // Fast path: don't touch param info if we don't need to.
155e5dd7070Spatrick   if (!FPT->hasExtParameterInfos()) {
156e5dd7070Spatrick     assert(paramInfos.empty() &&
157e5dd7070Spatrick            "We have paramInfos, but the prototype doesn't?");
158e5dd7070Spatrick     prefix.append(FPT->param_type_begin(), FPT->param_type_end());
159e5dd7070Spatrick     return;
160e5dd7070Spatrick   }
161e5dd7070Spatrick 
162e5dd7070Spatrick   unsigned PrefixSize = prefix.size();
163e5dd7070Spatrick   // In the vast majority of cases, we'll have precisely FPT->getNumParams()
164e5dd7070Spatrick   // parameters; the only thing that can change this is the presence of
165e5dd7070Spatrick   // pass_object_size. So, we preallocate for the common case.
166e5dd7070Spatrick   prefix.reserve(prefix.size() + FPT->getNumParams());
167e5dd7070Spatrick 
168e5dd7070Spatrick   auto ExtInfos = FPT->getExtParameterInfos();
169e5dd7070Spatrick   assert(ExtInfos.size() == FPT->getNumParams());
170e5dd7070Spatrick   for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
171e5dd7070Spatrick     prefix.push_back(FPT->getParamType(I));
172e5dd7070Spatrick     if (ExtInfos[I].hasPassObjectSize())
173e5dd7070Spatrick       prefix.push_back(CGT.getContext().getSizeType());
174e5dd7070Spatrick   }
175e5dd7070Spatrick 
176e5dd7070Spatrick   addExtParameterInfosForCall(paramInfos, FPT.getTypePtr(), PrefixSize,
177e5dd7070Spatrick                               prefix.size());
178e5dd7070Spatrick }
179e5dd7070Spatrick 
180e5dd7070Spatrick /// Arrange the LLVM function layout for a value of the given function
181e5dd7070Spatrick /// type, on top of any implicit parameters already stored.
182e5dd7070Spatrick static const CGFunctionInfo &
arrangeLLVMFunctionInfo(CodeGenTypes & CGT,bool instanceMethod,SmallVectorImpl<CanQualType> & prefix,CanQual<FunctionProtoType> FTP)183e5dd7070Spatrick arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
184e5dd7070Spatrick                         SmallVectorImpl<CanQualType> &prefix,
185e5dd7070Spatrick                         CanQual<FunctionProtoType> FTP) {
186e5dd7070Spatrick   SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
187e5dd7070Spatrick   RequiredArgs Required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
188e5dd7070Spatrick   // FIXME: Kill copy.
189e5dd7070Spatrick   appendParameterTypes(CGT, prefix, paramInfos, FTP);
190e5dd7070Spatrick   CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
191e5dd7070Spatrick 
192e5dd7070Spatrick   return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
193e5dd7070Spatrick                                      /*chainCall=*/false, prefix,
194e5dd7070Spatrick                                      FTP->getExtInfo(), paramInfos,
195e5dd7070Spatrick                                      Required);
196e5dd7070Spatrick }
197e5dd7070Spatrick 
198e5dd7070Spatrick /// Arrange the argument and result information for a value of the
199e5dd7070Spatrick /// given freestanding function type.
200e5dd7070Spatrick const CGFunctionInfo &
arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP)201e5dd7070Spatrick CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
202e5dd7070Spatrick   SmallVector<CanQualType, 16> argTypes;
203e5dd7070Spatrick   return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
204e5dd7070Spatrick                                    FTP);
205e5dd7070Spatrick }
206e5dd7070Spatrick 
getCallingConventionForDecl(const ObjCMethodDecl * D,bool IsWindows)207a0747c9fSpatrick static CallingConv getCallingConventionForDecl(const ObjCMethodDecl *D,
208a0747c9fSpatrick                                                bool IsWindows) {
209e5dd7070Spatrick   // Set the appropriate calling convention for the Function.
210e5dd7070Spatrick   if (D->hasAttr<StdCallAttr>())
211e5dd7070Spatrick     return CC_X86StdCall;
212e5dd7070Spatrick 
213e5dd7070Spatrick   if (D->hasAttr<FastCallAttr>())
214e5dd7070Spatrick     return CC_X86FastCall;
215e5dd7070Spatrick 
216e5dd7070Spatrick   if (D->hasAttr<RegCallAttr>())
217e5dd7070Spatrick     return CC_X86RegCall;
218e5dd7070Spatrick 
219e5dd7070Spatrick   if (D->hasAttr<ThisCallAttr>())
220e5dd7070Spatrick     return CC_X86ThisCall;
221e5dd7070Spatrick 
222e5dd7070Spatrick   if (D->hasAttr<VectorCallAttr>())
223e5dd7070Spatrick     return CC_X86VectorCall;
224e5dd7070Spatrick 
225e5dd7070Spatrick   if (D->hasAttr<PascalAttr>())
226e5dd7070Spatrick     return CC_X86Pascal;
227e5dd7070Spatrick 
228e5dd7070Spatrick   if (PcsAttr *PCS = D->getAttr<PcsAttr>())
229e5dd7070Spatrick     return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
230e5dd7070Spatrick 
231e5dd7070Spatrick   if (D->hasAttr<AArch64VectorPcsAttr>())
232e5dd7070Spatrick     return CC_AArch64VectorCall;
233e5dd7070Spatrick 
234*7a9b00ceSrobert   if (D->hasAttr<AArch64SVEPcsAttr>())
235*7a9b00ceSrobert     return CC_AArch64SVEPCS;
236*7a9b00ceSrobert 
237*7a9b00ceSrobert   if (D->hasAttr<AMDGPUKernelCallAttr>())
238*7a9b00ceSrobert     return CC_AMDGPUKernelCall;
239*7a9b00ceSrobert 
240e5dd7070Spatrick   if (D->hasAttr<IntelOclBiccAttr>())
241e5dd7070Spatrick     return CC_IntelOclBicc;
242e5dd7070Spatrick 
243e5dd7070Spatrick   if (D->hasAttr<MSABIAttr>())
244e5dd7070Spatrick     return IsWindows ? CC_C : CC_Win64;
245e5dd7070Spatrick 
246e5dd7070Spatrick   if (D->hasAttr<SysVABIAttr>())
247e5dd7070Spatrick     return IsWindows ? CC_X86_64SysV : CC_C;
248e5dd7070Spatrick 
249e5dd7070Spatrick   if (D->hasAttr<PreserveMostAttr>())
250e5dd7070Spatrick     return CC_PreserveMost;
251e5dd7070Spatrick 
252e5dd7070Spatrick   if (D->hasAttr<PreserveAllAttr>())
253e5dd7070Spatrick     return CC_PreserveAll;
254e5dd7070Spatrick 
255e5dd7070Spatrick   return CC_C;
256e5dd7070Spatrick }
257e5dd7070Spatrick 
258e5dd7070Spatrick /// Arrange the argument and result information for a call to an
259e5dd7070Spatrick /// unknown C++ non-static member function of the given abstract type.
260e5dd7070Spatrick /// (A null RD means we don't have any meaningful "this" argument type,
261e5dd7070Spatrick ///  so fall back to a generic pointer type).
262e5dd7070Spatrick /// The member function must be an ordinary function, i.e. not a
263e5dd7070Spatrick /// constructor or destructor.
264e5dd7070Spatrick const CGFunctionInfo &
arrangeCXXMethodType(const CXXRecordDecl * RD,const FunctionProtoType * FTP,const CXXMethodDecl * MD)265e5dd7070Spatrick CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
266e5dd7070Spatrick                                    const FunctionProtoType *FTP,
267e5dd7070Spatrick                                    const CXXMethodDecl *MD) {
268e5dd7070Spatrick   SmallVector<CanQualType, 16> argTypes;
269e5dd7070Spatrick 
270e5dd7070Spatrick   // Add the 'this' pointer.
271e5dd7070Spatrick   argTypes.push_back(DeriveThisType(RD, MD));
272e5dd7070Spatrick 
273e5dd7070Spatrick   return ::arrangeLLVMFunctionInfo(
274e5dd7070Spatrick       *this, true, argTypes,
275e5dd7070Spatrick       FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
276e5dd7070Spatrick }
277e5dd7070Spatrick 
278e5dd7070Spatrick /// Set calling convention for CUDA/HIP kernel.
setCUDAKernelCallingConvention(CanQualType & FTy,CodeGenModule & CGM,const FunctionDecl * FD)279e5dd7070Spatrick static void setCUDAKernelCallingConvention(CanQualType &FTy, CodeGenModule &CGM,
280e5dd7070Spatrick                                            const FunctionDecl *FD) {
281e5dd7070Spatrick   if (FD->hasAttr<CUDAGlobalAttr>()) {
282e5dd7070Spatrick     const FunctionType *FT = FTy->getAs<FunctionType>();
283e5dd7070Spatrick     CGM.getTargetCodeGenInfo().setCUDAKernelCallingConvention(FT);
284e5dd7070Spatrick     FTy = FT->getCanonicalTypeUnqualified();
285e5dd7070Spatrick   }
286e5dd7070Spatrick }
287e5dd7070Spatrick 
288e5dd7070Spatrick /// Arrange the argument and result information for a declaration or
289e5dd7070Spatrick /// definition of the given C++ non-static member function.  The
290e5dd7070Spatrick /// member function must be an ordinary function, i.e. not a
291e5dd7070Spatrick /// constructor or destructor.
292e5dd7070Spatrick const CGFunctionInfo &
arrangeCXXMethodDeclaration(const CXXMethodDecl * MD)293e5dd7070Spatrick CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
294e5dd7070Spatrick   assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
295e5dd7070Spatrick   assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
296e5dd7070Spatrick 
297e5dd7070Spatrick   CanQualType FT = GetFormalType(MD).getAs<Type>();
298e5dd7070Spatrick   setCUDAKernelCallingConvention(FT, CGM, MD);
299e5dd7070Spatrick   auto prototype = FT.getAs<FunctionProtoType>();
300e5dd7070Spatrick 
301e5dd7070Spatrick   if (MD->isInstance()) {
302e5dd7070Spatrick     // The abstract case is perfectly fine.
303e5dd7070Spatrick     const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
304e5dd7070Spatrick     return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
305e5dd7070Spatrick   }
306e5dd7070Spatrick 
307e5dd7070Spatrick   return arrangeFreeFunctionType(prototype);
308e5dd7070Spatrick }
309e5dd7070Spatrick 
inheritingCtorHasParams(const InheritedConstructor & Inherited,CXXCtorType Type)310e5dd7070Spatrick bool CodeGenTypes::inheritingCtorHasParams(
311e5dd7070Spatrick     const InheritedConstructor &Inherited, CXXCtorType Type) {
312e5dd7070Spatrick   // Parameters are unnecessary if we're constructing a base class subobject
313e5dd7070Spatrick   // and the inherited constructor lives in a virtual base.
314e5dd7070Spatrick   return Type == Ctor_Complete ||
315e5dd7070Spatrick          !Inherited.getShadowDecl()->constructsVirtualBase() ||
316e5dd7070Spatrick          !Target.getCXXABI().hasConstructorVariants();
317e5dd7070Spatrick }
318e5dd7070Spatrick 
319e5dd7070Spatrick const CGFunctionInfo &
arrangeCXXStructorDeclaration(GlobalDecl GD)320e5dd7070Spatrick CodeGenTypes::arrangeCXXStructorDeclaration(GlobalDecl GD) {
321e5dd7070Spatrick   auto *MD = cast<CXXMethodDecl>(GD.getDecl());
322e5dd7070Spatrick 
323e5dd7070Spatrick   SmallVector<CanQualType, 16> argTypes;
324e5dd7070Spatrick   SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
325*7a9b00ceSrobert 
326*7a9b00ceSrobert   const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(GD);
327*7a9b00ceSrobert   argTypes.push_back(DeriveThisType(ThisType, MD));
328e5dd7070Spatrick 
329e5dd7070Spatrick   bool PassParams = true;
330e5dd7070Spatrick 
331e5dd7070Spatrick   if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
332e5dd7070Spatrick     // A base class inheriting constructor doesn't get forwarded arguments
333e5dd7070Spatrick     // needed to construct a virtual base (or base class thereof).
334e5dd7070Spatrick     if (auto Inherited = CD->getInheritedConstructor())
335e5dd7070Spatrick       PassParams = inheritingCtorHasParams(Inherited, GD.getCtorType());
336e5dd7070Spatrick   }
337e5dd7070Spatrick 
338e5dd7070Spatrick   CanQual<FunctionProtoType> FTP = GetFormalType(MD);
339e5dd7070Spatrick 
340e5dd7070Spatrick   // Add the formal parameters.
341e5dd7070Spatrick   if (PassParams)
342e5dd7070Spatrick     appendParameterTypes(*this, argTypes, paramInfos, FTP);
343e5dd7070Spatrick 
344ec727ea7Spatrick   CGCXXABI::AddedStructorArgCounts AddedArgs =
345e5dd7070Spatrick       TheCXXABI.buildStructorSignature(GD, argTypes);
346e5dd7070Spatrick   if (!paramInfos.empty()) {
347e5dd7070Spatrick     // Note: prefix implies after the first param.
348e5dd7070Spatrick     if (AddedArgs.Prefix)
349e5dd7070Spatrick       paramInfos.insert(paramInfos.begin() + 1, AddedArgs.Prefix,
350e5dd7070Spatrick                         FunctionProtoType::ExtParameterInfo{});
351e5dd7070Spatrick     if (AddedArgs.Suffix)
352e5dd7070Spatrick       paramInfos.append(AddedArgs.Suffix,
353e5dd7070Spatrick                         FunctionProtoType::ExtParameterInfo{});
354e5dd7070Spatrick   }
355e5dd7070Spatrick 
356e5dd7070Spatrick   RequiredArgs required =
357e5dd7070Spatrick       (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
358e5dd7070Spatrick                                       : RequiredArgs::All);
359e5dd7070Spatrick 
360e5dd7070Spatrick   FunctionType::ExtInfo extInfo = FTP->getExtInfo();
361e5dd7070Spatrick   CanQualType resultType = TheCXXABI.HasThisReturn(GD)
362e5dd7070Spatrick                                ? argTypes.front()
363e5dd7070Spatrick                                : TheCXXABI.hasMostDerivedReturn(GD)
364e5dd7070Spatrick                                      ? CGM.getContext().VoidPtrTy
365e5dd7070Spatrick                                      : Context.VoidTy;
366e5dd7070Spatrick   return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
367e5dd7070Spatrick                                  /*chainCall=*/false, argTypes, extInfo,
368e5dd7070Spatrick                                  paramInfos, required);
369e5dd7070Spatrick }
370e5dd7070Spatrick 
371e5dd7070Spatrick static SmallVector<CanQualType, 16>
getArgTypesForCall(ASTContext & ctx,const CallArgList & args)372e5dd7070Spatrick getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
373e5dd7070Spatrick   SmallVector<CanQualType, 16> argTypes;
374e5dd7070Spatrick   for (auto &arg : args)
375e5dd7070Spatrick     argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
376e5dd7070Spatrick   return argTypes;
377e5dd7070Spatrick }
378e5dd7070Spatrick 
379e5dd7070Spatrick static SmallVector<CanQualType, 16>
getArgTypesForDeclaration(ASTContext & ctx,const FunctionArgList & args)380e5dd7070Spatrick getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
381e5dd7070Spatrick   SmallVector<CanQualType, 16> argTypes;
382e5dd7070Spatrick   for (auto &arg : args)
383e5dd7070Spatrick     argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
384e5dd7070Spatrick   return argTypes;
385e5dd7070Spatrick }
386e5dd7070Spatrick 
387e5dd7070Spatrick static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
getExtParameterInfosForCall(const FunctionProtoType * proto,unsigned prefixArgs,unsigned totalArgs)388e5dd7070Spatrick getExtParameterInfosForCall(const FunctionProtoType *proto,
389e5dd7070Spatrick                             unsigned prefixArgs, unsigned totalArgs) {
390e5dd7070Spatrick   llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
391e5dd7070Spatrick   if (proto->hasExtParameterInfos()) {
392e5dd7070Spatrick     addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
393e5dd7070Spatrick   }
394e5dd7070Spatrick   return result;
395e5dd7070Spatrick }
396e5dd7070Spatrick 
397e5dd7070Spatrick /// Arrange a call to a C++ method, passing the given arguments.
398e5dd7070Spatrick ///
399e5dd7070Spatrick /// ExtraPrefixArgs is the number of ABI-specific args passed after the `this`
400e5dd7070Spatrick /// parameter.
401e5dd7070Spatrick /// ExtraSuffixArgs is the number of ABI-specific args passed at the end of
402e5dd7070Spatrick /// args.
403e5dd7070Spatrick /// PassProtoArgs indicates whether `args` has args for the parameters in the
404e5dd7070Spatrick /// given CXXConstructorDecl.
405e5dd7070Spatrick const CGFunctionInfo &
arrangeCXXConstructorCall(const CallArgList & args,const CXXConstructorDecl * D,CXXCtorType CtorKind,unsigned ExtraPrefixArgs,unsigned ExtraSuffixArgs,bool PassProtoArgs)406e5dd7070Spatrick CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
407e5dd7070Spatrick                                         const CXXConstructorDecl *D,
408e5dd7070Spatrick                                         CXXCtorType CtorKind,
409e5dd7070Spatrick                                         unsigned ExtraPrefixArgs,
410e5dd7070Spatrick                                         unsigned ExtraSuffixArgs,
411e5dd7070Spatrick                                         bool PassProtoArgs) {
412e5dd7070Spatrick   // FIXME: Kill copy.
413e5dd7070Spatrick   SmallVector<CanQualType, 16> ArgTypes;
414e5dd7070Spatrick   for (const auto &Arg : args)
415e5dd7070Spatrick     ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
416e5dd7070Spatrick 
417e5dd7070Spatrick   // +1 for implicit this, which should always be args[0].
418e5dd7070Spatrick   unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs;
419e5dd7070Spatrick 
420e5dd7070Spatrick   CanQual<FunctionProtoType> FPT = GetFormalType(D);
421e5dd7070Spatrick   RequiredArgs Required = PassProtoArgs
422e5dd7070Spatrick                               ? RequiredArgs::forPrototypePlus(
423e5dd7070Spatrick                                     FPT, TotalPrefixArgs + ExtraSuffixArgs)
424e5dd7070Spatrick                               : RequiredArgs::All;
425e5dd7070Spatrick 
426e5dd7070Spatrick   GlobalDecl GD(D, CtorKind);
427e5dd7070Spatrick   CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
428e5dd7070Spatrick                                ? ArgTypes.front()
429e5dd7070Spatrick                                : TheCXXABI.hasMostDerivedReturn(GD)
430e5dd7070Spatrick                                      ? CGM.getContext().VoidPtrTy
431e5dd7070Spatrick                                      : Context.VoidTy;
432e5dd7070Spatrick 
433e5dd7070Spatrick   FunctionType::ExtInfo Info = FPT->getExtInfo();
434e5dd7070Spatrick   llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> ParamInfos;
435e5dd7070Spatrick   // If the prototype args are elided, we should only have ABI-specific args,
436e5dd7070Spatrick   // which never have param info.
437e5dd7070Spatrick   if (PassProtoArgs && FPT->hasExtParameterInfos()) {
438e5dd7070Spatrick     // ABI-specific suffix arguments are treated the same as variadic arguments.
439e5dd7070Spatrick     addExtParameterInfosForCall(ParamInfos, FPT.getTypePtr(), TotalPrefixArgs,
440e5dd7070Spatrick                                 ArgTypes.size());
441e5dd7070Spatrick   }
442e5dd7070Spatrick   return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
443e5dd7070Spatrick                                  /*chainCall=*/false, ArgTypes, Info,
444e5dd7070Spatrick                                  ParamInfos, Required);
445e5dd7070Spatrick }
446e5dd7070Spatrick 
447e5dd7070Spatrick /// Arrange the argument and result information for the declaration or
448e5dd7070Spatrick /// definition of the given function.
449e5dd7070Spatrick const CGFunctionInfo &
arrangeFunctionDeclaration(const FunctionDecl * FD)450e5dd7070Spatrick CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
451e5dd7070Spatrick   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
452e5dd7070Spatrick     if (MD->isInstance())
453e5dd7070Spatrick       return arrangeCXXMethodDeclaration(MD);
454e5dd7070Spatrick 
455e5dd7070Spatrick   CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
456e5dd7070Spatrick 
457e5dd7070Spatrick   assert(isa<FunctionType>(FTy));
458e5dd7070Spatrick   setCUDAKernelCallingConvention(FTy, CGM, FD);
459e5dd7070Spatrick 
460e5dd7070Spatrick   // When declaring a function without a prototype, always use a
461e5dd7070Spatrick   // non-variadic type.
462e5dd7070Spatrick   if (CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>()) {
463e5dd7070Spatrick     return arrangeLLVMFunctionInfo(
464e5dd7070Spatrick         noProto->getReturnType(), /*instanceMethod=*/false,
465*7a9b00ceSrobert         /*chainCall=*/false, std::nullopt, noProto->getExtInfo(), {},
466*7a9b00ceSrobert         RequiredArgs::All);
467e5dd7070Spatrick   }
468e5dd7070Spatrick 
469e5dd7070Spatrick   return arrangeFreeFunctionType(FTy.castAs<FunctionProtoType>());
470e5dd7070Spatrick }
471e5dd7070Spatrick 
472e5dd7070Spatrick /// Arrange the argument and result information for the declaration or
473e5dd7070Spatrick /// definition of an Objective-C method.
474e5dd7070Spatrick const CGFunctionInfo &
arrangeObjCMethodDeclaration(const ObjCMethodDecl * MD)475e5dd7070Spatrick CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
476e5dd7070Spatrick   // It happens that this is the same as a call with no optional
477e5dd7070Spatrick   // arguments, except also using the formal 'self' type.
478e5dd7070Spatrick   return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
479e5dd7070Spatrick }
480e5dd7070Spatrick 
481e5dd7070Spatrick /// Arrange the argument and result information for the function type
482e5dd7070Spatrick /// through which to perform a send to the given Objective-C method,
483e5dd7070Spatrick /// using the given receiver type.  The receiver type is not always
484e5dd7070Spatrick /// the 'self' type of the method or even an Objective-C pointer type.
485e5dd7070Spatrick /// This is *not* the right method for actually performing such a
486e5dd7070Spatrick /// message send, due to the possibility of optional arguments.
487e5dd7070Spatrick const CGFunctionInfo &
arrangeObjCMessageSendSignature(const ObjCMethodDecl * MD,QualType receiverType)488e5dd7070Spatrick CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
489e5dd7070Spatrick                                               QualType receiverType) {
490e5dd7070Spatrick   SmallVector<CanQualType, 16> argTys;
491*7a9b00ceSrobert   SmallVector<FunctionProtoType::ExtParameterInfo, 4> extParamInfos(
492*7a9b00ceSrobert       MD->isDirectMethod() ? 1 : 2);
493e5dd7070Spatrick   argTys.push_back(Context.getCanonicalParamType(receiverType));
494*7a9b00ceSrobert   if (!MD->isDirectMethod())
495e5dd7070Spatrick     argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
496e5dd7070Spatrick   // FIXME: Kill copy?
497e5dd7070Spatrick   for (const auto *I : MD->parameters()) {
498e5dd7070Spatrick     argTys.push_back(Context.getCanonicalParamType(I->getType()));
499e5dd7070Spatrick     auto extParamInfo = FunctionProtoType::ExtParameterInfo().withIsNoEscape(
500e5dd7070Spatrick         I->hasAttr<NoEscapeAttr>());
501e5dd7070Spatrick     extParamInfos.push_back(extParamInfo);
502e5dd7070Spatrick   }
503e5dd7070Spatrick 
504e5dd7070Spatrick   FunctionType::ExtInfo einfo;
505e5dd7070Spatrick   bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
506e5dd7070Spatrick   einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
507e5dd7070Spatrick 
508e5dd7070Spatrick   if (getContext().getLangOpts().ObjCAutoRefCount &&
509e5dd7070Spatrick       MD->hasAttr<NSReturnsRetainedAttr>())
510e5dd7070Spatrick     einfo = einfo.withProducesResult(true);
511e5dd7070Spatrick 
512e5dd7070Spatrick   RequiredArgs required =
513e5dd7070Spatrick     (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
514e5dd7070Spatrick 
515e5dd7070Spatrick   return arrangeLLVMFunctionInfo(
516e5dd7070Spatrick       GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
517e5dd7070Spatrick       /*chainCall=*/false, argTys, einfo, extParamInfos, required);
518e5dd7070Spatrick }
519e5dd7070Spatrick 
520e5dd7070Spatrick const CGFunctionInfo &
arrangeUnprototypedObjCMessageSend(QualType returnType,const CallArgList & args)521e5dd7070Spatrick CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
522e5dd7070Spatrick                                                  const CallArgList &args) {
523e5dd7070Spatrick   auto argTypes = getArgTypesForCall(Context, args);
524e5dd7070Spatrick   FunctionType::ExtInfo einfo;
525e5dd7070Spatrick 
526e5dd7070Spatrick   return arrangeLLVMFunctionInfo(
527e5dd7070Spatrick       GetReturnType(returnType), /*instanceMethod=*/false,
528e5dd7070Spatrick       /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
529e5dd7070Spatrick }
530e5dd7070Spatrick 
531e5dd7070Spatrick const CGFunctionInfo &
arrangeGlobalDeclaration(GlobalDecl GD)532e5dd7070Spatrick CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
533e5dd7070Spatrick   // FIXME: Do we need to handle ObjCMethodDecl?
534e5dd7070Spatrick   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
535e5dd7070Spatrick 
536e5dd7070Spatrick   if (isa<CXXConstructorDecl>(GD.getDecl()) ||
537e5dd7070Spatrick       isa<CXXDestructorDecl>(GD.getDecl()))
538e5dd7070Spatrick     return arrangeCXXStructorDeclaration(GD);
539e5dd7070Spatrick 
540e5dd7070Spatrick   return arrangeFunctionDeclaration(FD);
541e5dd7070Spatrick }
542e5dd7070Spatrick 
543e5dd7070Spatrick /// Arrange a thunk that takes 'this' as the first parameter followed by
544e5dd7070Spatrick /// varargs.  Return a void pointer, regardless of the actual return type.
545e5dd7070Spatrick /// The body of the thunk will end in a musttail call to a function of the
546e5dd7070Spatrick /// correct type, and the caller will bitcast the function to the correct
547e5dd7070Spatrick /// prototype.
548e5dd7070Spatrick const CGFunctionInfo &
arrangeUnprototypedMustTailThunk(const CXXMethodDecl * MD)549e5dd7070Spatrick CodeGenTypes::arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD) {
550e5dd7070Spatrick   assert(MD->isVirtual() && "only methods have thunks");
551e5dd7070Spatrick   CanQual<FunctionProtoType> FTP = GetFormalType(MD);
552e5dd7070Spatrick   CanQualType ArgTys[] = {DeriveThisType(MD->getParent(), MD)};
553e5dd7070Spatrick   return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
554e5dd7070Spatrick                                  /*chainCall=*/false, ArgTys,
555e5dd7070Spatrick                                  FTP->getExtInfo(), {}, RequiredArgs(1));
556e5dd7070Spatrick }
557e5dd7070Spatrick 
558e5dd7070Spatrick const CGFunctionInfo &
arrangeMSCtorClosure(const CXXConstructorDecl * CD,CXXCtorType CT)559e5dd7070Spatrick CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
560e5dd7070Spatrick                                    CXXCtorType CT) {
561e5dd7070Spatrick   assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
562e5dd7070Spatrick 
563e5dd7070Spatrick   CanQual<FunctionProtoType> FTP = GetFormalType(CD);
564e5dd7070Spatrick   SmallVector<CanQualType, 2> ArgTys;
565e5dd7070Spatrick   const CXXRecordDecl *RD = CD->getParent();
566e5dd7070Spatrick   ArgTys.push_back(DeriveThisType(RD, CD));
567e5dd7070Spatrick   if (CT == Ctor_CopyingClosure)
568e5dd7070Spatrick     ArgTys.push_back(*FTP->param_type_begin());
569e5dd7070Spatrick   if (RD->getNumVBases() > 0)
570e5dd7070Spatrick     ArgTys.push_back(Context.IntTy);
571e5dd7070Spatrick   CallingConv CC = Context.getDefaultCallingConvention(
572e5dd7070Spatrick       /*IsVariadic=*/false, /*IsCXXMethod=*/true);
573e5dd7070Spatrick   return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
574e5dd7070Spatrick                                  /*chainCall=*/false, ArgTys,
575e5dd7070Spatrick                                  FunctionType::ExtInfo(CC), {},
576e5dd7070Spatrick                                  RequiredArgs::All);
577e5dd7070Spatrick }
578e5dd7070Spatrick 
579e5dd7070Spatrick /// Arrange a call as unto a free function, except possibly with an
580e5dd7070Spatrick /// additional number of formal parameters considered required.
581e5dd7070Spatrick static const CGFunctionInfo &
arrangeFreeFunctionLikeCall(CodeGenTypes & CGT,CodeGenModule & CGM,const CallArgList & args,const FunctionType * fnType,unsigned numExtraRequiredArgs,bool chainCall)582e5dd7070Spatrick arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
583e5dd7070Spatrick                             CodeGenModule &CGM,
584e5dd7070Spatrick                             const CallArgList &args,
585e5dd7070Spatrick                             const FunctionType *fnType,
586e5dd7070Spatrick                             unsigned numExtraRequiredArgs,
587e5dd7070Spatrick                             bool chainCall) {
588e5dd7070Spatrick   assert(args.size() >= numExtraRequiredArgs);
589e5dd7070Spatrick 
590e5dd7070Spatrick   llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
591e5dd7070Spatrick 
592e5dd7070Spatrick   // In most cases, there are no optional arguments.
593e5dd7070Spatrick   RequiredArgs required = RequiredArgs::All;
594e5dd7070Spatrick 
595e5dd7070Spatrick   // If we have a variadic prototype, the required arguments are the
596e5dd7070Spatrick   // extra prefix plus the arguments in the prototype.
597e5dd7070Spatrick   if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
598e5dd7070Spatrick     if (proto->isVariadic())
599e5dd7070Spatrick       required = RequiredArgs::forPrototypePlus(proto, numExtraRequiredArgs);
600e5dd7070Spatrick 
601e5dd7070Spatrick     if (proto->hasExtParameterInfos())
602e5dd7070Spatrick       addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
603e5dd7070Spatrick                                   args.size());
604e5dd7070Spatrick 
605e5dd7070Spatrick   // If we don't have a prototype at all, but we're supposed to
606e5dd7070Spatrick   // explicitly use the variadic convention for unprototyped calls,
607e5dd7070Spatrick   // treat all of the arguments as required but preserve the nominal
608e5dd7070Spatrick   // possibility of variadics.
609e5dd7070Spatrick   } else if (CGM.getTargetCodeGenInfo()
610e5dd7070Spatrick                 .isNoProtoCallVariadic(args,
611e5dd7070Spatrick                                        cast<FunctionNoProtoType>(fnType))) {
612e5dd7070Spatrick     required = RequiredArgs(args.size());
613e5dd7070Spatrick   }
614e5dd7070Spatrick 
615e5dd7070Spatrick   // FIXME: Kill copy.
616e5dd7070Spatrick   SmallVector<CanQualType, 16> argTypes;
617e5dd7070Spatrick   for (const auto &arg : args)
618e5dd7070Spatrick     argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
619e5dd7070Spatrick   return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
620e5dd7070Spatrick                                      /*instanceMethod=*/false, chainCall,
621e5dd7070Spatrick                                      argTypes, fnType->getExtInfo(), paramInfos,
622e5dd7070Spatrick                                      required);
623e5dd7070Spatrick }
624e5dd7070Spatrick 
625e5dd7070Spatrick /// Figure out the rules for calling a function with the given formal
626e5dd7070Spatrick /// type using the given arguments.  The arguments are necessary
627e5dd7070Spatrick /// because the function might be unprototyped, in which case it's
628e5dd7070Spatrick /// target-dependent in crazy ways.
629e5dd7070Spatrick const CGFunctionInfo &
arrangeFreeFunctionCall(const CallArgList & args,const FunctionType * fnType,bool chainCall)630e5dd7070Spatrick CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
631e5dd7070Spatrick                                       const FunctionType *fnType,
632e5dd7070Spatrick                                       bool chainCall) {
633e5dd7070Spatrick   return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
634e5dd7070Spatrick                                      chainCall ? 1 : 0, chainCall);
635e5dd7070Spatrick }
636e5dd7070Spatrick 
637e5dd7070Spatrick /// A block function is essentially a free function with an
638e5dd7070Spatrick /// extra implicit argument.
639e5dd7070Spatrick const CGFunctionInfo &
arrangeBlockFunctionCall(const CallArgList & args,const FunctionType * fnType)640e5dd7070Spatrick CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
641e5dd7070Spatrick                                        const FunctionType *fnType) {
642e5dd7070Spatrick   return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
643e5dd7070Spatrick                                      /*chainCall=*/false);
644e5dd7070Spatrick }
645e5dd7070Spatrick 
646e5dd7070Spatrick const CGFunctionInfo &
arrangeBlockFunctionDeclaration(const FunctionProtoType * proto,const FunctionArgList & params)647e5dd7070Spatrick CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
648e5dd7070Spatrick                                               const FunctionArgList &params) {
649e5dd7070Spatrick   auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
650e5dd7070Spatrick   auto argTypes = getArgTypesForDeclaration(Context, params);
651e5dd7070Spatrick 
652e5dd7070Spatrick   return arrangeLLVMFunctionInfo(GetReturnType(proto->getReturnType()),
653e5dd7070Spatrick                                  /*instanceMethod*/ false, /*chainCall*/ false,
654e5dd7070Spatrick                                  argTypes, proto->getExtInfo(), paramInfos,
655e5dd7070Spatrick                                  RequiredArgs::forPrototypePlus(proto, 1));
656e5dd7070Spatrick }
657e5dd7070Spatrick 
658e5dd7070Spatrick const CGFunctionInfo &
arrangeBuiltinFunctionCall(QualType resultType,const CallArgList & args)659e5dd7070Spatrick CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
660e5dd7070Spatrick                                          const CallArgList &args) {
661e5dd7070Spatrick   // FIXME: Kill copy.
662e5dd7070Spatrick   SmallVector<CanQualType, 16> argTypes;
663e5dd7070Spatrick   for (const auto &Arg : args)
664e5dd7070Spatrick     argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
665e5dd7070Spatrick   return arrangeLLVMFunctionInfo(
666e5dd7070Spatrick       GetReturnType(resultType), /*instanceMethod=*/false,
667e5dd7070Spatrick       /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
668e5dd7070Spatrick       /*paramInfos=*/ {}, RequiredArgs::All);
669e5dd7070Spatrick }
670e5dd7070Spatrick 
671e5dd7070Spatrick const CGFunctionInfo &
arrangeBuiltinFunctionDeclaration(QualType resultType,const FunctionArgList & args)672e5dd7070Spatrick CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
673e5dd7070Spatrick                                                 const FunctionArgList &args) {
674e5dd7070Spatrick   auto argTypes = getArgTypesForDeclaration(Context, args);
675e5dd7070Spatrick 
676e5dd7070Spatrick   return arrangeLLVMFunctionInfo(
677e5dd7070Spatrick       GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
678e5dd7070Spatrick       argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
679e5dd7070Spatrick }
680e5dd7070Spatrick 
681e5dd7070Spatrick const CGFunctionInfo &
arrangeBuiltinFunctionDeclaration(CanQualType resultType,ArrayRef<CanQualType> argTypes)682e5dd7070Spatrick CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
683e5dd7070Spatrick                                               ArrayRef<CanQualType> argTypes) {
684e5dd7070Spatrick   return arrangeLLVMFunctionInfo(
685e5dd7070Spatrick       resultType, /*instanceMethod=*/false, /*chainCall=*/false,
686e5dd7070Spatrick       argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
687e5dd7070Spatrick }
688e5dd7070Spatrick 
689e5dd7070Spatrick /// Arrange a call to a C++ method, passing the given arguments.
690e5dd7070Spatrick ///
691e5dd7070Spatrick /// numPrefixArgs is the number of ABI-specific prefix arguments we have. It
692e5dd7070Spatrick /// does not count `this`.
693e5dd7070Spatrick const CGFunctionInfo &
arrangeCXXMethodCall(const CallArgList & args,const FunctionProtoType * proto,RequiredArgs required,unsigned numPrefixArgs)694e5dd7070Spatrick CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
695e5dd7070Spatrick                                    const FunctionProtoType *proto,
696e5dd7070Spatrick                                    RequiredArgs required,
697e5dd7070Spatrick                                    unsigned numPrefixArgs) {
698e5dd7070Spatrick   assert(numPrefixArgs + 1 <= args.size() &&
699e5dd7070Spatrick          "Emitting a call with less args than the required prefix?");
700e5dd7070Spatrick   // Add one to account for `this`. It's a bit awkward here, but we don't count
701e5dd7070Spatrick   // `this` in similar places elsewhere.
702e5dd7070Spatrick   auto paramInfos =
703e5dd7070Spatrick     getExtParameterInfosForCall(proto, numPrefixArgs + 1, args.size());
704e5dd7070Spatrick 
705e5dd7070Spatrick   // FIXME: Kill copy.
706e5dd7070Spatrick   auto argTypes = getArgTypesForCall(Context, args);
707e5dd7070Spatrick 
708e5dd7070Spatrick   FunctionType::ExtInfo info = proto->getExtInfo();
709e5dd7070Spatrick   return arrangeLLVMFunctionInfo(
710e5dd7070Spatrick       GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
711e5dd7070Spatrick       /*chainCall=*/false, argTypes, info, paramInfos, required);
712e5dd7070Spatrick }
713e5dd7070Spatrick 
arrangeNullaryFunction()714e5dd7070Spatrick const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
715e5dd7070Spatrick   return arrangeLLVMFunctionInfo(
716e5dd7070Spatrick       getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
717*7a9b00ceSrobert       std::nullopt, FunctionType::ExtInfo(), {}, RequiredArgs::All);
718e5dd7070Spatrick }
719e5dd7070Spatrick 
720e5dd7070Spatrick const CGFunctionInfo &
arrangeCall(const CGFunctionInfo & signature,const CallArgList & args)721e5dd7070Spatrick CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
722e5dd7070Spatrick                           const CallArgList &args) {
723e5dd7070Spatrick   assert(signature.arg_size() <= args.size());
724e5dd7070Spatrick   if (signature.arg_size() == args.size())
725e5dd7070Spatrick     return signature;
726e5dd7070Spatrick 
727e5dd7070Spatrick   SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
728e5dd7070Spatrick   auto sigParamInfos = signature.getExtParameterInfos();
729e5dd7070Spatrick   if (!sigParamInfos.empty()) {
730e5dd7070Spatrick     paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
731e5dd7070Spatrick     paramInfos.resize(args.size());
732e5dd7070Spatrick   }
733e5dd7070Spatrick 
734e5dd7070Spatrick   auto argTypes = getArgTypesForCall(Context, args);
735e5dd7070Spatrick 
736e5dd7070Spatrick   assert(signature.getRequiredArgs().allowsOptionalArgs());
737e5dd7070Spatrick   return arrangeLLVMFunctionInfo(signature.getReturnType(),
738e5dd7070Spatrick                                  signature.isInstanceMethod(),
739e5dd7070Spatrick                                  signature.isChainCall(),
740e5dd7070Spatrick                                  argTypes,
741e5dd7070Spatrick                                  signature.getExtInfo(),
742e5dd7070Spatrick                                  paramInfos,
743e5dd7070Spatrick                                  signature.getRequiredArgs());
744e5dd7070Spatrick }
745e5dd7070Spatrick 
746e5dd7070Spatrick namespace clang {
747e5dd7070Spatrick namespace CodeGen {
748e5dd7070Spatrick void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI);
749e5dd7070Spatrick }
750e5dd7070Spatrick }
751e5dd7070Spatrick 
752e5dd7070Spatrick /// Arrange the argument and result information for an abstract value
753e5dd7070Spatrick /// of a given function type.  This is the method which all of the
754e5dd7070Spatrick /// above functions ultimately defer to.
755e5dd7070Spatrick const CGFunctionInfo &
arrangeLLVMFunctionInfo(CanQualType resultType,bool instanceMethod,bool chainCall,ArrayRef<CanQualType> argTypes,FunctionType::ExtInfo info,ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,RequiredArgs required)756e5dd7070Spatrick CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
757e5dd7070Spatrick                                       bool instanceMethod,
758e5dd7070Spatrick                                       bool chainCall,
759e5dd7070Spatrick                                       ArrayRef<CanQualType> argTypes,
760e5dd7070Spatrick                                       FunctionType::ExtInfo info,
761e5dd7070Spatrick                      ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
762e5dd7070Spatrick                                       RequiredArgs required) {
763e5dd7070Spatrick   assert(llvm::all_of(argTypes,
764e5dd7070Spatrick                       [](CanQualType T) { return T.isCanonicalAsParam(); }));
765e5dd7070Spatrick 
766e5dd7070Spatrick   // Lookup or create unique function info.
767e5dd7070Spatrick   llvm::FoldingSetNodeID ID;
768e5dd7070Spatrick   CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
769e5dd7070Spatrick                           required, resultType, argTypes);
770e5dd7070Spatrick 
771e5dd7070Spatrick   void *insertPos = nullptr;
772e5dd7070Spatrick   CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
773e5dd7070Spatrick   if (FI)
774e5dd7070Spatrick     return *FI;
775e5dd7070Spatrick 
776e5dd7070Spatrick   unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
777e5dd7070Spatrick 
778e5dd7070Spatrick   // Construct the function info.  We co-allocate the ArgInfos.
779e5dd7070Spatrick   FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
780e5dd7070Spatrick                               paramInfos, resultType, argTypes, required);
781e5dd7070Spatrick   FunctionInfos.InsertNode(FI, insertPos);
782e5dd7070Spatrick 
783e5dd7070Spatrick   bool inserted = FunctionsBeingProcessed.insert(FI).second;
784e5dd7070Spatrick   (void)inserted;
785e5dd7070Spatrick   assert(inserted && "Recursively being processed?");
786e5dd7070Spatrick 
787e5dd7070Spatrick   // Compute ABI information.
788e5dd7070Spatrick   if (CC == llvm::CallingConv::SPIR_KERNEL) {
789e5dd7070Spatrick     // Force target independent argument handling for the host visible
790e5dd7070Spatrick     // kernel functions.
791e5dd7070Spatrick     computeSPIRKernelABIInfo(CGM, *FI);
792a0747c9fSpatrick   } else if (info.getCC() == CC_Swift || info.getCC() == CC_SwiftAsync) {
793e5dd7070Spatrick     swiftcall::computeABIInfo(CGM, *FI);
794e5dd7070Spatrick   } else {
795e5dd7070Spatrick     getABIInfo().computeInfo(*FI);
796e5dd7070Spatrick   }
797e5dd7070Spatrick 
798e5dd7070Spatrick   // Loop over all of the computed argument and return value info.  If any of
799e5dd7070Spatrick   // them are direct or extend without a specified coerce type, specify the
800e5dd7070Spatrick   // default now.
801e5dd7070Spatrick   ABIArgInfo &retInfo = FI->getReturnInfo();
802e5dd7070Spatrick   if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
803e5dd7070Spatrick     retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
804e5dd7070Spatrick 
805e5dd7070Spatrick   for (auto &I : FI->arguments())
806e5dd7070Spatrick     if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
807e5dd7070Spatrick       I.info.setCoerceToType(ConvertType(I.type));
808e5dd7070Spatrick 
809e5dd7070Spatrick   bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
810e5dd7070Spatrick   assert(erased && "Not in set?");
811e5dd7070Spatrick 
812e5dd7070Spatrick   return *FI;
813e5dd7070Spatrick }
814e5dd7070Spatrick 
create(unsigned llvmCC,bool instanceMethod,bool chainCall,const FunctionType::ExtInfo & info,ArrayRef<ExtParameterInfo> paramInfos,CanQualType resultType,ArrayRef<CanQualType> argTypes,RequiredArgs required)815e5dd7070Spatrick CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
816e5dd7070Spatrick                                        bool instanceMethod,
817e5dd7070Spatrick                                        bool chainCall,
818e5dd7070Spatrick                                        const FunctionType::ExtInfo &info,
819e5dd7070Spatrick                                        ArrayRef<ExtParameterInfo> paramInfos,
820e5dd7070Spatrick                                        CanQualType resultType,
821e5dd7070Spatrick                                        ArrayRef<CanQualType> argTypes,
822e5dd7070Spatrick                                        RequiredArgs required) {
823e5dd7070Spatrick   assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
824e5dd7070Spatrick   assert(!required.allowsOptionalArgs() ||
825e5dd7070Spatrick          required.getNumRequiredArgs() <= argTypes.size());
826e5dd7070Spatrick 
827e5dd7070Spatrick   void *buffer =
828e5dd7070Spatrick     operator new(totalSizeToAlloc<ArgInfo,             ExtParameterInfo>(
829e5dd7070Spatrick                                   argTypes.size() + 1, paramInfos.size()));
830e5dd7070Spatrick 
831e5dd7070Spatrick   CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
832e5dd7070Spatrick   FI->CallingConvention = llvmCC;
833e5dd7070Spatrick   FI->EffectiveCallingConvention = llvmCC;
834e5dd7070Spatrick   FI->ASTCallingConvention = info.getCC();
835e5dd7070Spatrick   FI->InstanceMethod = instanceMethod;
836e5dd7070Spatrick   FI->ChainCall = chainCall;
837ec727ea7Spatrick   FI->CmseNSCall = info.getCmseNSCall();
838e5dd7070Spatrick   FI->NoReturn = info.getNoReturn();
839e5dd7070Spatrick   FI->ReturnsRetained = info.getProducesResult();
840e5dd7070Spatrick   FI->NoCallerSavedRegs = info.getNoCallerSavedRegs();
841e5dd7070Spatrick   FI->NoCfCheck = info.getNoCfCheck();
842e5dd7070Spatrick   FI->Required = required;
843e5dd7070Spatrick   FI->HasRegParm = info.getHasRegParm();
844e5dd7070Spatrick   FI->RegParm = info.getRegParm();
845e5dd7070Spatrick   FI->ArgStruct = nullptr;
846e5dd7070Spatrick   FI->ArgStructAlign = 0;
847e5dd7070Spatrick   FI->NumArgs = argTypes.size();
848e5dd7070Spatrick   FI->HasExtParameterInfos = !paramInfos.empty();
849e5dd7070Spatrick   FI->getArgsBuffer()[0].type = resultType;
850*7a9b00ceSrobert   FI->MaxVectorWidth = 0;
851e5dd7070Spatrick   for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
852e5dd7070Spatrick     FI->getArgsBuffer()[i + 1].type = argTypes[i];
853e5dd7070Spatrick   for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
854e5dd7070Spatrick     FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
855e5dd7070Spatrick   return FI;
856e5dd7070Spatrick }
857e5dd7070Spatrick 
858e5dd7070Spatrick /***/
859e5dd7070Spatrick 
860e5dd7070Spatrick namespace {
861e5dd7070Spatrick // ABIArgInfo::Expand implementation.
862e5dd7070Spatrick 
863e5dd7070Spatrick // Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
864e5dd7070Spatrick struct TypeExpansion {
865e5dd7070Spatrick   enum TypeExpansionKind {
866e5dd7070Spatrick     // Elements of constant arrays are expanded recursively.
867e5dd7070Spatrick     TEK_ConstantArray,
868e5dd7070Spatrick     // Record fields are expanded recursively (but if record is a union, only
869e5dd7070Spatrick     // the field with the largest size is expanded).
870e5dd7070Spatrick     TEK_Record,
871e5dd7070Spatrick     // For complex types, real and imaginary parts are expanded recursively.
872e5dd7070Spatrick     TEK_Complex,
873e5dd7070Spatrick     // All other types are not expandable.
874e5dd7070Spatrick     TEK_None
875e5dd7070Spatrick   };
876e5dd7070Spatrick 
877e5dd7070Spatrick   const TypeExpansionKind Kind;
878e5dd7070Spatrick 
TypeExpansion__anon5c86009b0211::TypeExpansion879e5dd7070Spatrick   TypeExpansion(TypeExpansionKind K) : Kind(K) {}
~TypeExpansion__anon5c86009b0211::TypeExpansion880e5dd7070Spatrick   virtual ~TypeExpansion() {}
881e5dd7070Spatrick };
882e5dd7070Spatrick 
883e5dd7070Spatrick struct ConstantArrayExpansion : TypeExpansion {
884e5dd7070Spatrick   QualType EltTy;
885e5dd7070Spatrick   uint64_t NumElts;
886e5dd7070Spatrick 
ConstantArrayExpansion__anon5c86009b0211::ConstantArrayExpansion887e5dd7070Spatrick   ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
888e5dd7070Spatrick       : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
classof__anon5c86009b0211::ConstantArrayExpansion889e5dd7070Spatrick   static bool classof(const TypeExpansion *TE) {
890e5dd7070Spatrick     return TE->Kind == TEK_ConstantArray;
891e5dd7070Spatrick   }
892e5dd7070Spatrick };
893e5dd7070Spatrick 
894e5dd7070Spatrick struct RecordExpansion : TypeExpansion {
895e5dd7070Spatrick   SmallVector<const CXXBaseSpecifier *, 1> Bases;
896e5dd7070Spatrick 
897e5dd7070Spatrick   SmallVector<const FieldDecl *, 1> Fields;
898e5dd7070Spatrick 
RecordExpansion__anon5c86009b0211::RecordExpansion899e5dd7070Spatrick   RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
900e5dd7070Spatrick                   SmallVector<const FieldDecl *, 1> &&Fields)
901e5dd7070Spatrick       : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
902e5dd7070Spatrick         Fields(std::move(Fields)) {}
classof__anon5c86009b0211::RecordExpansion903e5dd7070Spatrick   static bool classof(const TypeExpansion *TE) {
904e5dd7070Spatrick     return TE->Kind == TEK_Record;
905e5dd7070Spatrick   }
906e5dd7070Spatrick };
907e5dd7070Spatrick 
908e5dd7070Spatrick struct ComplexExpansion : TypeExpansion {
909e5dd7070Spatrick   QualType EltTy;
910e5dd7070Spatrick 
ComplexExpansion__anon5c86009b0211::ComplexExpansion911e5dd7070Spatrick   ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
classof__anon5c86009b0211::ComplexExpansion912e5dd7070Spatrick   static bool classof(const TypeExpansion *TE) {
913e5dd7070Spatrick     return TE->Kind == TEK_Complex;
914e5dd7070Spatrick   }
915e5dd7070Spatrick };
916e5dd7070Spatrick 
917e5dd7070Spatrick struct NoExpansion : TypeExpansion {
NoExpansion__anon5c86009b0211::NoExpansion918e5dd7070Spatrick   NoExpansion() : TypeExpansion(TEK_None) {}
classof__anon5c86009b0211::NoExpansion919e5dd7070Spatrick   static bool classof(const TypeExpansion *TE) {
920e5dd7070Spatrick     return TE->Kind == TEK_None;
921e5dd7070Spatrick   }
922e5dd7070Spatrick };
923e5dd7070Spatrick }  // namespace
924e5dd7070Spatrick 
925e5dd7070Spatrick static std::unique_ptr<TypeExpansion>
getTypeExpansion(QualType Ty,const ASTContext & Context)926e5dd7070Spatrick getTypeExpansion(QualType Ty, const ASTContext &Context) {
927e5dd7070Spatrick   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
928e5dd7070Spatrick     return std::make_unique<ConstantArrayExpansion>(
929e5dd7070Spatrick         AT->getElementType(), AT->getSize().getZExtValue());
930e5dd7070Spatrick   }
931e5dd7070Spatrick   if (const RecordType *RT = Ty->getAs<RecordType>()) {
932e5dd7070Spatrick     SmallVector<const CXXBaseSpecifier *, 1> Bases;
933e5dd7070Spatrick     SmallVector<const FieldDecl *, 1> Fields;
934e5dd7070Spatrick     const RecordDecl *RD = RT->getDecl();
935e5dd7070Spatrick     assert(!RD->hasFlexibleArrayMember() &&
936e5dd7070Spatrick            "Cannot expand structure with flexible array.");
937e5dd7070Spatrick     if (RD->isUnion()) {
938e5dd7070Spatrick       // Unions can be here only in degenerative cases - all the fields are same
939e5dd7070Spatrick       // after flattening. Thus we have to use the "largest" field.
940e5dd7070Spatrick       const FieldDecl *LargestFD = nullptr;
941e5dd7070Spatrick       CharUnits UnionSize = CharUnits::Zero();
942e5dd7070Spatrick 
943e5dd7070Spatrick       for (const auto *FD : RD->fields()) {
944e5dd7070Spatrick         if (FD->isZeroLengthBitField(Context))
945e5dd7070Spatrick           continue;
946e5dd7070Spatrick         assert(!FD->isBitField() &&
947e5dd7070Spatrick                "Cannot expand structure with bit-field members.");
948e5dd7070Spatrick         CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
949e5dd7070Spatrick         if (UnionSize < FieldSize) {
950e5dd7070Spatrick           UnionSize = FieldSize;
951e5dd7070Spatrick           LargestFD = FD;
952e5dd7070Spatrick         }
953e5dd7070Spatrick       }
954e5dd7070Spatrick       if (LargestFD)
955e5dd7070Spatrick         Fields.push_back(LargestFD);
956e5dd7070Spatrick     } else {
957e5dd7070Spatrick       if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
958e5dd7070Spatrick         assert(!CXXRD->isDynamicClass() &&
959e5dd7070Spatrick                "cannot expand vtable pointers in dynamic classes");
960*7a9b00ceSrobert         llvm::append_range(Bases, llvm::make_pointer_range(CXXRD->bases()));
961e5dd7070Spatrick       }
962e5dd7070Spatrick 
963e5dd7070Spatrick       for (const auto *FD : RD->fields()) {
964e5dd7070Spatrick         if (FD->isZeroLengthBitField(Context))
965e5dd7070Spatrick           continue;
966e5dd7070Spatrick         assert(!FD->isBitField() &&
967e5dd7070Spatrick                "Cannot expand structure with bit-field members.");
968e5dd7070Spatrick         Fields.push_back(FD);
969e5dd7070Spatrick       }
970e5dd7070Spatrick     }
971e5dd7070Spatrick     return std::make_unique<RecordExpansion>(std::move(Bases),
972e5dd7070Spatrick                                               std::move(Fields));
973e5dd7070Spatrick   }
974e5dd7070Spatrick   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
975e5dd7070Spatrick     return std::make_unique<ComplexExpansion>(CT->getElementType());
976e5dd7070Spatrick   }
977e5dd7070Spatrick   return std::make_unique<NoExpansion>();
978e5dd7070Spatrick }
979e5dd7070Spatrick 
getExpansionSize(QualType Ty,const ASTContext & Context)980e5dd7070Spatrick static int getExpansionSize(QualType Ty, const ASTContext &Context) {
981e5dd7070Spatrick   auto Exp = getTypeExpansion(Ty, Context);
982e5dd7070Spatrick   if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
983e5dd7070Spatrick     return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
984e5dd7070Spatrick   }
985e5dd7070Spatrick   if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
986e5dd7070Spatrick     int Res = 0;
987e5dd7070Spatrick     for (auto BS : RExp->Bases)
988e5dd7070Spatrick       Res += getExpansionSize(BS->getType(), Context);
989e5dd7070Spatrick     for (auto FD : RExp->Fields)
990e5dd7070Spatrick       Res += getExpansionSize(FD->getType(), Context);
991e5dd7070Spatrick     return Res;
992e5dd7070Spatrick   }
993e5dd7070Spatrick   if (isa<ComplexExpansion>(Exp.get()))
994e5dd7070Spatrick     return 2;
995e5dd7070Spatrick   assert(isa<NoExpansion>(Exp.get()));
996e5dd7070Spatrick   return 1;
997e5dd7070Spatrick }
998e5dd7070Spatrick 
999e5dd7070Spatrick void
getExpandedTypes(QualType Ty,SmallVectorImpl<llvm::Type * >::iterator & TI)1000e5dd7070Spatrick CodeGenTypes::getExpandedTypes(QualType Ty,
1001e5dd7070Spatrick                                SmallVectorImpl<llvm::Type *>::iterator &TI) {
1002e5dd7070Spatrick   auto Exp = getTypeExpansion(Ty, Context);
1003e5dd7070Spatrick   if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1004e5dd7070Spatrick     for (int i = 0, n = CAExp->NumElts; i < n; i++) {
1005e5dd7070Spatrick       getExpandedTypes(CAExp->EltTy, TI);
1006e5dd7070Spatrick     }
1007e5dd7070Spatrick   } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1008e5dd7070Spatrick     for (auto BS : RExp->Bases)
1009e5dd7070Spatrick       getExpandedTypes(BS->getType(), TI);
1010e5dd7070Spatrick     for (auto FD : RExp->Fields)
1011e5dd7070Spatrick       getExpandedTypes(FD->getType(), TI);
1012e5dd7070Spatrick   } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
1013e5dd7070Spatrick     llvm::Type *EltTy = ConvertType(CExp->EltTy);
1014e5dd7070Spatrick     *TI++ = EltTy;
1015e5dd7070Spatrick     *TI++ = EltTy;
1016e5dd7070Spatrick   } else {
1017e5dd7070Spatrick     assert(isa<NoExpansion>(Exp.get()));
1018e5dd7070Spatrick     *TI++ = ConvertType(Ty);
1019e5dd7070Spatrick   }
1020e5dd7070Spatrick }
1021e5dd7070Spatrick 
forConstantArrayExpansion(CodeGenFunction & CGF,ConstantArrayExpansion * CAE,Address BaseAddr,llvm::function_ref<void (Address)> Fn)1022e5dd7070Spatrick static void forConstantArrayExpansion(CodeGenFunction &CGF,
1023e5dd7070Spatrick                                       ConstantArrayExpansion *CAE,
1024e5dd7070Spatrick                                       Address BaseAddr,
1025e5dd7070Spatrick                                       llvm::function_ref<void(Address)> Fn) {
1026e5dd7070Spatrick   CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
1027e5dd7070Spatrick   CharUnits EltAlign =
1028e5dd7070Spatrick     BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
1029*7a9b00ceSrobert   llvm::Type *EltTy = CGF.ConvertTypeForMem(CAE->EltTy);
1030e5dd7070Spatrick 
1031e5dd7070Spatrick   for (int i = 0, n = CAE->NumElts; i < n; i++) {
1032a0747c9fSpatrick     llvm::Value *EltAddr = CGF.Builder.CreateConstGEP2_32(
1033a0747c9fSpatrick         BaseAddr.getElementType(), BaseAddr.getPointer(), 0, i);
1034*7a9b00ceSrobert     Fn(Address(EltAddr, EltTy, EltAlign));
1035e5dd7070Spatrick   }
1036e5dd7070Spatrick }
1037e5dd7070Spatrick 
ExpandTypeFromArgs(QualType Ty,LValue LV,llvm::Function::arg_iterator & AI)1038ec727ea7Spatrick void CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
1039ec727ea7Spatrick                                          llvm::Function::arg_iterator &AI) {
1040e5dd7070Spatrick   assert(LV.isSimple() &&
1041e5dd7070Spatrick          "Unexpected non-simple lvalue during struct expansion.");
1042e5dd7070Spatrick 
1043e5dd7070Spatrick   auto Exp = getTypeExpansion(Ty, getContext());
1044e5dd7070Spatrick   if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1045e5dd7070Spatrick     forConstantArrayExpansion(
1046e5dd7070Spatrick         *this, CAExp, LV.getAddress(*this), [&](Address EltAddr) {
1047e5dd7070Spatrick           LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
1048e5dd7070Spatrick           ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
1049e5dd7070Spatrick         });
1050e5dd7070Spatrick   } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1051e5dd7070Spatrick     Address This = LV.getAddress(*this);
1052e5dd7070Spatrick     for (const CXXBaseSpecifier *BS : RExp->Bases) {
1053e5dd7070Spatrick       // Perform a single step derived-to-base conversion.
1054e5dd7070Spatrick       Address Base =
1055e5dd7070Spatrick           GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1056e5dd7070Spatrick                                 /*NullCheckValue=*/false, SourceLocation());
1057e5dd7070Spatrick       LValue SubLV = MakeAddrLValue(Base, BS->getType());
1058e5dd7070Spatrick 
1059e5dd7070Spatrick       // Recurse onto bases.
1060e5dd7070Spatrick       ExpandTypeFromArgs(BS->getType(), SubLV, AI);
1061e5dd7070Spatrick     }
1062e5dd7070Spatrick     for (auto FD : RExp->Fields) {
1063e5dd7070Spatrick       // FIXME: What are the right qualifiers here?
1064e5dd7070Spatrick       LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
1065e5dd7070Spatrick       ExpandTypeFromArgs(FD->getType(), SubLV, AI);
1066e5dd7070Spatrick     }
1067e5dd7070Spatrick   } else if (isa<ComplexExpansion>(Exp.get())) {
1068ec727ea7Spatrick     auto realValue = &*AI++;
1069ec727ea7Spatrick     auto imagValue = &*AI++;
1070e5dd7070Spatrick     EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
1071e5dd7070Spatrick   } else {
1072e5dd7070Spatrick     // Call EmitStoreOfScalar except when the lvalue is a bitfield to emit a
1073e5dd7070Spatrick     // primitive store.
1074e5dd7070Spatrick     assert(isa<NoExpansion>(Exp.get()));
1075*7a9b00ceSrobert     llvm::Value *Arg = &*AI++;
1076*7a9b00ceSrobert     if (LV.isBitField()) {
1077*7a9b00ceSrobert       EmitStoreThroughLValue(RValue::get(Arg), LV);
1078*7a9b00ceSrobert     } else {
1079*7a9b00ceSrobert       // TODO: currently there are some places are inconsistent in what LLVM
1080*7a9b00ceSrobert       // pointer type they use (see D118744). Once clang uses opaque pointers
1081*7a9b00ceSrobert       // all LLVM pointer types will be the same and we can remove this check.
1082*7a9b00ceSrobert       if (Arg->getType()->isPointerTy()) {
1083*7a9b00ceSrobert         Address Addr = LV.getAddress(*this);
1084*7a9b00ceSrobert         Arg = Builder.CreateBitCast(Arg, Addr.getElementType());
1085*7a9b00ceSrobert       }
1086*7a9b00ceSrobert       EmitStoreOfScalar(Arg, LV);
1087*7a9b00ceSrobert     }
1088e5dd7070Spatrick   }
1089e5dd7070Spatrick }
1090e5dd7070Spatrick 
ExpandTypeToArgs(QualType Ty,CallArg Arg,llvm::FunctionType * IRFuncTy,SmallVectorImpl<llvm::Value * > & IRCallArgs,unsigned & IRCallArgPos)1091e5dd7070Spatrick void CodeGenFunction::ExpandTypeToArgs(
1092e5dd7070Spatrick     QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
1093e5dd7070Spatrick     SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
1094e5dd7070Spatrick   auto Exp = getTypeExpansion(Ty, getContext());
1095e5dd7070Spatrick   if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1096e5dd7070Spatrick     Address Addr = Arg.hasLValue() ? Arg.getKnownLValue().getAddress(*this)
1097e5dd7070Spatrick                                    : Arg.getKnownRValue().getAggregateAddress();
1098e5dd7070Spatrick     forConstantArrayExpansion(
1099e5dd7070Spatrick         *this, CAExp, Addr, [&](Address EltAddr) {
1100e5dd7070Spatrick           CallArg EltArg = CallArg(
1101e5dd7070Spatrick               convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation()),
1102e5dd7070Spatrick               CAExp->EltTy);
1103e5dd7070Spatrick           ExpandTypeToArgs(CAExp->EltTy, EltArg, IRFuncTy, IRCallArgs,
1104e5dd7070Spatrick                            IRCallArgPos);
1105e5dd7070Spatrick         });
1106e5dd7070Spatrick   } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1107e5dd7070Spatrick     Address This = Arg.hasLValue() ? Arg.getKnownLValue().getAddress(*this)
1108e5dd7070Spatrick                                    : Arg.getKnownRValue().getAggregateAddress();
1109e5dd7070Spatrick     for (const CXXBaseSpecifier *BS : RExp->Bases) {
1110e5dd7070Spatrick       // Perform a single step derived-to-base conversion.
1111e5dd7070Spatrick       Address Base =
1112e5dd7070Spatrick           GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1113e5dd7070Spatrick                                 /*NullCheckValue=*/false, SourceLocation());
1114e5dd7070Spatrick       CallArg BaseArg = CallArg(RValue::getAggregate(Base), BS->getType());
1115e5dd7070Spatrick 
1116e5dd7070Spatrick       // Recurse onto bases.
1117e5dd7070Spatrick       ExpandTypeToArgs(BS->getType(), BaseArg, IRFuncTy, IRCallArgs,
1118e5dd7070Spatrick                        IRCallArgPos);
1119e5dd7070Spatrick     }
1120e5dd7070Spatrick 
1121e5dd7070Spatrick     LValue LV = MakeAddrLValue(This, Ty);
1122e5dd7070Spatrick     for (auto FD : RExp->Fields) {
1123e5dd7070Spatrick       CallArg FldArg =
1124e5dd7070Spatrick           CallArg(EmitRValueForField(LV, FD, SourceLocation()), FD->getType());
1125e5dd7070Spatrick       ExpandTypeToArgs(FD->getType(), FldArg, IRFuncTy, IRCallArgs,
1126e5dd7070Spatrick                        IRCallArgPos);
1127e5dd7070Spatrick     }
1128e5dd7070Spatrick   } else if (isa<ComplexExpansion>(Exp.get())) {
1129e5dd7070Spatrick     ComplexPairTy CV = Arg.getKnownRValue().getComplexVal();
1130e5dd7070Spatrick     IRCallArgs[IRCallArgPos++] = CV.first;
1131e5dd7070Spatrick     IRCallArgs[IRCallArgPos++] = CV.second;
1132e5dd7070Spatrick   } else {
1133e5dd7070Spatrick     assert(isa<NoExpansion>(Exp.get()));
1134e5dd7070Spatrick     auto RV = Arg.getKnownRValue();
1135e5dd7070Spatrick     assert(RV.isScalar() &&
1136e5dd7070Spatrick            "Unexpected non-scalar rvalue during struct expansion.");
1137e5dd7070Spatrick 
1138e5dd7070Spatrick     // Insert a bitcast as needed.
1139e5dd7070Spatrick     llvm::Value *V = RV.getScalarVal();
1140e5dd7070Spatrick     if (IRCallArgPos < IRFuncTy->getNumParams() &&
1141e5dd7070Spatrick         V->getType() != IRFuncTy->getParamType(IRCallArgPos))
1142e5dd7070Spatrick       V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
1143e5dd7070Spatrick 
1144e5dd7070Spatrick     IRCallArgs[IRCallArgPos++] = V;
1145e5dd7070Spatrick   }
1146e5dd7070Spatrick }
1147e5dd7070Spatrick 
1148e5dd7070Spatrick /// Create a temporary allocation for the purposes of coercion.
CreateTempAllocaForCoercion(CodeGenFunction & CGF,llvm::Type * Ty,CharUnits MinAlign,const Twine & Name="tmp")1149e5dd7070Spatrick static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
1150a0747c9fSpatrick                                            CharUnits MinAlign,
1151a0747c9fSpatrick                                            const Twine &Name = "tmp") {
1152e5dd7070Spatrick   // Don't use an alignment that's worse than what LLVM would prefer.
1153*7a9b00ceSrobert   auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(Ty);
1154e5dd7070Spatrick   CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
1155e5dd7070Spatrick 
1156a0747c9fSpatrick   return CGF.CreateTempAlloca(Ty, Align, Name + ".coerce");
1157e5dd7070Spatrick }
1158e5dd7070Spatrick 
1159e5dd7070Spatrick /// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
1160e5dd7070Spatrick /// accessing some number of bytes out of it, try to gep into the struct to get
1161e5dd7070Spatrick /// at its inner goodness.  Dive as deep as possible without entering an element
1162e5dd7070Spatrick /// with an in-memory size smaller than DstSize.
1163e5dd7070Spatrick static Address
EnterStructPointerForCoercedAccess(Address SrcPtr,llvm::StructType * SrcSTy,uint64_t DstSize,CodeGenFunction & CGF)1164e5dd7070Spatrick EnterStructPointerForCoercedAccess(Address SrcPtr,
1165e5dd7070Spatrick                                    llvm::StructType *SrcSTy,
1166e5dd7070Spatrick                                    uint64_t DstSize, CodeGenFunction &CGF) {
1167e5dd7070Spatrick   // We can't dive into a zero-element struct.
1168e5dd7070Spatrick   if (SrcSTy->getNumElements() == 0) return SrcPtr;
1169e5dd7070Spatrick 
1170e5dd7070Spatrick   llvm::Type *FirstElt = SrcSTy->getElementType(0);
1171e5dd7070Spatrick 
1172e5dd7070Spatrick   // If the first elt is at least as large as what we're looking for, or if the
1173e5dd7070Spatrick   // first element is the same size as the whole struct, we can enter it. The
1174e5dd7070Spatrick   // comparison must be made on the store size and not the alloca size. Using
1175e5dd7070Spatrick   // the alloca size may overstate the size of the load.
1176e5dd7070Spatrick   uint64_t FirstEltSize =
1177e5dd7070Spatrick     CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
1178e5dd7070Spatrick   if (FirstEltSize < DstSize &&
1179e5dd7070Spatrick       FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
1180e5dd7070Spatrick     return SrcPtr;
1181e5dd7070Spatrick 
1182e5dd7070Spatrick   // GEP into the first element.
1183e5dd7070Spatrick   SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, "coerce.dive");
1184e5dd7070Spatrick 
1185e5dd7070Spatrick   // If the first element is a struct, recurse.
1186e5dd7070Spatrick   llvm::Type *SrcTy = SrcPtr.getElementType();
1187e5dd7070Spatrick   if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
1188e5dd7070Spatrick     return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
1189e5dd7070Spatrick 
1190e5dd7070Spatrick   return SrcPtr;
1191e5dd7070Spatrick }
1192e5dd7070Spatrick 
1193e5dd7070Spatrick /// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1194e5dd7070Spatrick /// are either integers or pointers.  This does a truncation of the value if it
1195e5dd7070Spatrick /// is too large or a zero extension if it is too small.
1196e5dd7070Spatrick ///
1197e5dd7070Spatrick /// This behaves as if the value were coerced through memory, so on big-endian
1198e5dd7070Spatrick /// targets the high bits are preserved in a truncation, while little-endian
1199e5dd7070Spatrick /// targets preserve the low bits.
CoerceIntOrPtrToIntOrPtr(llvm::Value * Val,llvm::Type * Ty,CodeGenFunction & CGF)1200e5dd7070Spatrick static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
1201e5dd7070Spatrick                                              llvm::Type *Ty,
1202e5dd7070Spatrick                                              CodeGenFunction &CGF) {
1203e5dd7070Spatrick   if (Val->getType() == Ty)
1204e5dd7070Spatrick     return Val;
1205e5dd7070Spatrick 
1206e5dd7070Spatrick   if (isa<llvm::PointerType>(Val->getType())) {
1207e5dd7070Spatrick     // If this is Pointer->Pointer avoid conversion to and from int.
1208e5dd7070Spatrick     if (isa<llvm::PointerType>(Ty))
1209e5dd7070Spatrick       return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
1210e5dd7070Spatrick 
1211e5dd7070Spatrick     // Convert the pointer to an integer so we can play with its width.
1212e5dd7070Spatrick     Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
1213e5dd7070Spatrick   }
1214e5dd7070Spatrick 
1215e5dd7070Spatrick   llvm::Type *DestIntTy = Ty;
1216e5dd7070Spatrick   if (isa<llvm::PointerType>(DestIntTy))
1217e5dd7070Spatrick     DestIntTy = CGF.IntPtrTy;
1218e5dd7070Spatrick 
1219e5dd7070Spatrick   if (Val->getType() != DestIntTy) {
1220e5dd7070Spatrick     const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
1221e5dd7070Spatrick     if (DL.isBigEndian()) {
1222e5dd7070Spatrick       // Preserve the high bits on big-endian targets.
1223e5dd7070Spatrick       // That is what memory coercion does.
1224e5dd7070Spatrick       uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1225e5dd7070Spatrick       uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1226e5dd7070Spatrick 
1227e5dd7070Spatrick       if (SrcSize > DstSize) {
1228e5dd7070Spatrick         Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
1229e5dd7070Spatrick         Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
1230e5dd7070Spatrick       } else {
1231e5dd7070Spatrick         Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
1232e5dd7070Spatrick         Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
1233e5dd7070Spatrick       }
1234e5dd7070Spatrick     } else {
1235e5dd7070Spatrick       // Little-endian targets preserve the low bits. No shifts required.
1236e5dd7070Spatrick       Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
1237e5dd7070Spatrick     }
1238e5dd7070Spatrick   }
1239e5dd7070Spatrick 
1240e5dd7070Spatrick   if (isa<llvm::PointerType>(Ty))
1241e5dd7070Spatrick     Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
1242e5dd7070Spatrick   return Val;
1243e5dd7070Spatrick }
1244e5dd7070Spatrick 
1245e5dd7070Spatrick 
1246e5dd7070Spatrick 
1247e5dd7070Spatrick /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
1248e5dd7070Spatrick /// a pointer to an object of type \arg Ty, known to be aligned to
1249e5dd7070Spatrick /// \arg SrcAlign bytes.
1250e5dd7070Spatrick ///
1251e5dd7070Spatrick /// This safely handles the case when the src type is smaller than the
1252e5dd7070Spatrick /// destination type; in this situation the values of bits which not
1253e5dd7070Spatrick /// present in the src are undefined.
CreateCoercedLoad(Address Src,llvm::Type * Ty,CodeGenFunction & CGF)1254e5dd7070Spatrick static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
1255e5dd7070Spatrick                                       CodeGenFunction &CGF) {
1256e5dd7070Spatrick   llvm::Type *SrcTy = Src.getElementType();
1257e5dd7070Spatrick 
1258e5dd7070Spatrick   // If SrcTy and Ty are the same, just do a load.
1259e5dd7070Spatrick   if (SrcTy == Ty)
1260e5dd7070Spatrick     return CGF.Builder.CreateLoad(Src);
1261e5dd7070Spatrick 
1262a0747c9fSpatrick   llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
1263e5dd7070Spatrick 
1264e5dd7070Spatrick   if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
1265a0747c9fSpatrick     Src = EnterStructPointerForCoercedAccess(Src, SrcSTy,
1266*7a9b00ceSrobert                                              DstSize.getFixedValue(), CGF);
1267ec727ea7Spatrick     SrcTy = Src.getElementType();
1268e5dd7070Spatrick   }
1269e5dd7070Spatrick 
1270a0747c9fSpatrick   llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
1271e5dd7070Spatrick 
1272e5dd7070Spatrick   // If the source and destination are integer or pointer types, just do an
1273e5dd7070Spatrick   // extension or truncation to the desired type.
1274e5dd7070Spatrick   if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
1275e5dd7070Spatrick       (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
1276e5dd7070Spatrick     llvm::Value *Load = CGF.Builder.CreateLoad(Src);
1277e5dd7070Spatrick     return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
1278e5dd7070Spatrick   }
1279e5dd7070Spatrick 
1280e5dd7070Spatrick   // If load is legal, just bitcast the src pointer.
1281a0747c9fSpatrick   if (!SrcSize.isScalable() && !DstSize.isScalable() &&
1282*7a9b00ceSrobert       SrcSize.getFixedValue() >= DstSize.getFixedValue()) {
1283e5dd7070Spatrick     // Generally SrcSize is never greater than DstSize, since this means we are
1284e5dd7070Spatrick     // losing bits. However, this can happen in cases where the structure has
1285e5dd7070Spatrick     // additional padding, for example due to a user specified alignment.
1286e5dd7070Spatrick     //
1287e5dd7070Spatrick     // FIXME: Assert that we aren't truncating non-padding bits when have access
1288e5dd7070Spatrick     // to that information.
1289*7a9b00ceSrobert     Src = CGF.Builder.CreateElementBitCast(Src, Ty);
1290e5dd7070Spatrick     return CGF.Builder.CreateLoad(Src);
1291e5dd7070Spatrick   }
1292e5dd7070Spatrick 
1293a0747c9fSpatrick   // If coercing a fixed vector to a scalable vector for ABI compatibility, and
1294*7a9b00ceSrobert   // the types match, use the llvm.vector.insert intrinsic to perform the
1295*7a9b00ceSrobert   // conversion.
1296a0747c9fSpatrick   if (auto *ScalableDst = dyn_cast<llvm::ScalableVectorType>(Ty)) {
1297a0747c9fSpatrick     if (auto *FixedSrc = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
1298*7a9b00ceSrobert       // If we are casting a fixed i8 vector to a scalable 16 x i1 predicate
1299*7a9b00ceSrobert       // vector, use a vector insert and bitcast the result.
1300*7a9b00ceSrobert       bool NeedsBitcast = false;
1301*7a9b00ceSrobert       auto PredType =
1302*7a9b00ceSrobert           llvm::ScalableVectorType::get(CGF.Builder.getInt1Ty(), 16);
1303*7a9b00ceSrobert       llvm::Type *OrigType = Ty;
1304*7a9b00ceSrobert       if (ScalableDst == PredType &&
1305*7a9b00ceSrobert           FixedSrc->getElementType() == CGF.Builder.getInt8Ty()) {
1306*7a9b00ceSrobert         ScalableDst = llvm::ScalableVectorType::get(CGF.Builder.getInt8Ty(), 2);
1307*7a9b00ceSrobert         NeedsBitcast = true;
1308*7a9b00ceSrobert       }
1309a0747c9fSpatrick       if (ScalableDst->getElementType() == FixedSrc->getElementType()) {
1310a0747c9fSpatrick         auto *Load = CGF.Builder.CreateLoad(Src);
1311a0747c9fSpatrick         auto *UndefVec = llvm::UndefValue::get(ScalableDst);
1312a0747c9fSpatrick         auto *Zero = llvm::Constant::getNullValue(CGF.CGM.Int64Ty);
1313*7a9b00ceSrobert         llvm::Value *Result = CGF.Builder.CreateInsertVector(
1314*7a9b00ceSrobert             ScalableDst, UndefVec, Load, Zero, "castScalableSve");
1315*7a9b00ceSrobert         if (NeedsBitcast)
1316*7a9b00ceSrobert           Result = CGF.Builder.CreateBitCast(Result, OrigType);
1317*7a9b00ceSrobert         return Result;
1318a0747c9fSpatrick       }
1319a0747c9fSpatrick     }
1320a0747c9fSpatrick   }
1321a0747c9fSpatrick 
1322e5dd7070Spatrick   // Otherwise do coercion through memory. This is stupid, but simple.
1323a0747c9fSpatrick   Address Tmp =
1324a0747c9fSpatrick       CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment(), Src.getName());
1325a0747c9fSpatrick   CGF.Builder.CreateMemCpy(
1326a0747c9fSpatrick       Tmp.getPointer(), Tmp.getAlignment().getAsAlign(), Src.getPointer(),
1327a0747c9fSpatrick       Src.getAlignment().getAsAlign(),
1328*7a9b00ceSrobert       llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize.getKnownMinValue()));
1329e5dd7070Spatrick   return CGF.Builder.CreateLoad(Tmp);
1330e5dd7070Spatrick }
1331e5dd7070Spatrick 
1332e5dd7070Spatrick // Function to store a first-class aggregate into memory.  We prefer to
1333e5dd7070Spatrick // store the elements rather than the aggregate to be more friendly to
1334e5dd7070Spatrick // fast-isel.
1335e5dd7070Spatrick // FIXME: Do we need to recurse here?
EmitAggregateStore(llvm::Value * Val,Address Dest,bool DestIsVolatile)1336ec727ea7Spatrick void CodeGenFunction::EmitAggregateStore(llvm::Value *Val, Address Dest,
1337ec727ea7Spatrick                                          bool DestIsVolatile) {
1338e5dd7070Spatrick   // Prefer scalar stores to first-class aggregate stores.
1339ec727ea7Spatrick   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(Val->getType())) {
1340e5dd7070Spatrick     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1341ec727ea7Spatrick       Address EltPtr = Builder.CreateStructGEP(Dest, i);
1342ec727ea7Spatrick       llvm::Value *Elt = Builder.CreateExtractValue(Val, i);
1343ec727ea7Spatrick       Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
1344e5dd7070Spatrick     }
1345e5dd7070Spatrick   } else {
1346ec727ea7Spatrick     Builder.CreateStore(Val, Dest, DestIsVolatile);
1347e5dd7070Spatrick   }
1348e5dd7070Spatrick }
1349e5dd7070Spatrick 
1350e5dd7070Spatrick /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
1351e5dd7070Spatrick /// where the source and destination may have different types.  The
1352e5dd7070Spatrick /// destination is known to be aligned to \arg DstAlign bytes.
1353e5dd7070Spatrick ///
1354e5dd7070Spatrick /// This safely handles the case when the src type is larger than the
1355e5dd7070Spatrick /// destination type; the upper bits of the src will be lost.
CreateCoercedStore(llvm::Value * Src,Address Dst,bool DstIsVolatile,CodeGenFunction & CGF)1356e5dd7070Spatrick static void CreateCoercedStore(llvm::Value *Src,
1357e5dd7070Spatrick                                Address Dst,
1358e5dd7070Spatrick                                bool DstIsVolatile,
1359e5dd7070Spatrick                                CodeGenFunction &CGF) {
1360e5dd7070Spatrick   llvm::Type *SrcTy = Src->getType();
1361ec727ea7Spatrick   llvm::Type *DstTy = Dst.getElementType();
1362e5dd7070Spatrick   if (SrcTy == DstTy) {
1363e5dd7070Spatrick     CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1364e5dd7070Spatrick     return;
1365e5dd7070Spatrick   }
1366e5dd7070Spatrick 
1367a0747c9fSpatrick   llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
1368e5dd7070Spatrick 
1369e5dd7070Spatrick   if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
1370a0747c9fSpatrick     Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy,
1371*7a9b00ceSrobert                                              SrcSize.getFixedValue(), CGF);
1372ec727ea7Spatrick     DstTy = Dst.getElementType();
1373e5dd7070Spatrick   }
1374e5dd7070Spatrick 
1375e5dd7070Spatrick   llvm::PointerType *SrcPtrTy = llvm::dyn_cast<llvm::PointerType>(SrcTy);
1376e5dd7070Spatrick   llvm::PointerType *DstPtrTy = llvm::dyn_cast<llvm::PointerType>(DstTy);
1377e5dd7070Spatrick   if (SrcPtrTy && DstPtrTy &&
1378e5dd7070Spatrick       SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace()) {
1379e5dd7070Spatrick     Src = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy);
1380e5dd7070Spatrick     CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1381e5dd7070Spatrick     return;
1382e5dd7070Spatrick   }
1383e5dd7070Spatrick 
1384e5dd7070Spatrick   // If the source and destination are integer or pointer types, just do an
1385e5dd7070Spatrick   // extension or truncation to the desired type.
1386e5dd7070Spatrick   if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1387e5dd7070Spatrick       (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1388e5dd7070Spatrick     Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
1389e5dd7070Spatrick     CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1390e5dd7070Spatrick     return;
1391e5dd7070Spatrick   }
1392e5dd7070Spatrick 
1393a0747c9fSpatrick   llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
1394e5dd7070Spatrick 
1395e5dd7070Spatrick   // If store is legal, just bitcast the src pointer.
1396a0747c9fSpatrick   if (isa<llvm::ScalableVectorType>(SrcTy) ||
1397a0747c9fSpatrick       isa<llvm::ScalableVectorType>(DstTy) ||
1398*7a9b00ceSrobert       SrcSize.getFixedValue() <= DstSize.getFixedValue()) {
1399e5dd7070Spatrick     Dst = CGF.Builder.CreateElementBitCast(Dst, SrcTy);
1400ec727ea7Spatrick     CGF.EmitAggregateStore(Src, Dst, DstIsVolatile);
1401e5dd7070Spatrick   } else {
1402e5dd7070Spatrick     // Otherwise do coercion through memory. This is stupid, but
1403e5dd7070Spatrick     // simple.
1404e5dd7070Spatrick 
1405e5dd7070Spatrick     // Generally SrcSize is never greater than DstSize, since this means we are
1406e5dd7070Spatrick     // losing bits. However, this can happen in cases where the structure has
1407e5dd7070Spatrick     // additional padding, for example due to a user specified alignment.
1408e5dd7070Spatrick     //
1409e5dd7070Spatrick     // FIXME: Assert that we aren't truncating non-padding bits when have access
1410e5dd7070Spatrick     // to that information.
1411e5dd7070Spatrick     Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1412e5dd7070Spatrick     CGF.Builder.CreateStore(Src, Tmp);
1413a0747c9fSpatrick     CGF.Builder.CreateMemCpy(
1414a0747c9fSpatrick         Dst.getPointer(), Dst.getAlignment().getAsAlign(), Tmp.getPointer(),
1415a0747c9fSpatrick         Tmp.getAlignment().getAsAlign(),
1416*7a9b00ceSrobert         llvm::ConstantInt::get(CGF.IntPtrTy, DstSize.getFixedValue()));
1417e5dd7070Spatrick   }
1418e5dd7070Spatrick }
1419e5dd7070Spatrick 
emitAddressAtOffset(CodeGenFunction & CGF,Address addr,const ABIArgInfo & info)1420e5dd7070Spatrick static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
1421e5dd7070Spatrick                                    const ABIArgInfo &info) {
1422e5dd7070Spatrick   if (unsigned offset = info.getDirectOffset()) {
1423e5dd7070Spatrick     addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
1424e5dd7070Spatrick     addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1425e5dd7070Spatrick                                              CharUnits::fromQuantity(offset));
1426e5dd7070Spatrick     addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
1427e5dd7070Spatrick   }
1428e5dd7070Spatrick   return addr;
1429e5dd7070Spatrick }
1430e5dd7070Spatrick 
1431e5dd7070Spatrick namespace {
1432e5dd7070Spatrick 
1433e5dd7070Spatrick /// Encapsulates information about the way function arguments from
1434e5dd7070Spatrick /// CGFunctionInfo should be passed to actual LLVM IR function.
1435e5dd7070Spatrick class ClangToLLVMArgMapping {
1436e5dd7070Spatrick   static const unsigned InvalidIndex = ~0U;
1437e5dd7070Spatrick   unsigned InallocaArgNo;
1438e5dd7070Spatrick   unsigned SRetArgNo;
1439e5dd7070Spatrick   unsigned TotalIRArgs;
1440e5dd7070Spatrick 
1441e5dd7070Spatrick   /// Arguments of LLVM IR function corresponding to single Clang argument.
1442e5dd7070Spatrick   struct IRArgs {
1443e5dd7070Spatrick     unsigned PaddingArgIndex;
1444e5dd7070Spatrick     // Argument is expanded to IR arguments at positions
1445e5dd7070Spatrick     // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1446e5dd7070Spatrick     unsigned FirstArgIndex;
1447e5dd7070Spatrick     unsigned NumberOfArgs;
1448e5dd7070Spatrick 
IRArgs__anon5c86009b0511::ClangToLLVMArgMapping::IRArgs1449e5dd7070Spatrick     IRArgs()
1450e5dd7070Spatrick         : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1451e5dd7070Spatrick           NumberOfArgs(0) {}
1452e5dd7070Spatrick   };
1453e5dd7070Spatrick 
1454e5dd7070Spatrick   SmallVector<IRArgs, 8> ArgInfo;
1455e5dd7070Spatrick 
1456e5dd7070Spatrick public:
ClangToLLVMArgMapping(const ASTContext & Context,const CGFunctionInfo & FI,bool OnlyRequiredArgs=false)1457e5dd7070Spatrick   ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1458e5dd7070Spatrick                         bool OnlyRequiredArgs = false)
1459e5dd7070Spatrick       : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1460e5dd7070Spatrick         ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1461e5dd7070Spatrick     construct(Context, FI, OnlyRequiredArgs);
1462e5dd7070Spatrick   }
1463e5dd7070Spatrick 
hasInallocaArg() const1464e5dd7070Spatrick   bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
getInallocaArgNo() const1465e5dd7070Spatrick   unsigned getInallocaArgNo() const {
1466e5dd7070Spatrick     assert(hasInallocaArg());
1467e5dd7070Spatrick     return InallocaArgNo;
1468e5dd7070Spatrick   }
1469e5dd7070Spatrick 
hasSRetArg() const1470e5dd7070Spatrick   bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
getSRetArgNo() const1471e5dd7070Spatrick   unsigned getSRetArgNo() const {
1472e5dd7070Spatrick     assert(hasSRetArg());
1473e5dd7070Spatrick     return SRetArgNo;
1474e5dd7070Spatrick   }
1475e5dd7070Spatrick 
totalIRArgs() const1476e5dd7070Spatrick   unsigned totalIRArgs() const { return TotalIRArgs; }
1477e5dd7070Spatrick 
hasPaddingArg(unsigned ArgNo) const1478e5dd7070Spatrick   bool hasPaddingArg(unsigned ArgNo) const {
1479e5dd7070Spatrick     assert(ArgNo < ArgInfo.size());
1480e5dd7070Spatrick     return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1481e5dd7070Spatrick   }
getPaddingArgNo(unsigned ArgNo) const1482e5dd7070Spatrick   unsigned getPaddingArgNo(unsigned ArgNo) const {
1483e5dd7070Spatrick     assert(hasPaddingArg(ArgNo));
1484e5dd7070Spatrick     return ArgInfo[ArgNo].PaddingArgIndex;
1485e5dd7070Spatrick   }
1486e5dd7070Spatrick 
1487e5dd7070Spatrick   /// Returns index of first IR argument corresponding to ArgNo, and their
1488e5dd7070Spatrick   /// quantity.
getIRArgs(unsigned ArgNo) const1489e5dd7070Spatrick   std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1490e5dd7070Spatrick     assert(ArgNo < ArgInfo.size());
1491e5dd7070Spatrick     return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1492e5dd7070Spatrick                           ArgInfo[ArgNo].NumberOfArgs);
1493e5dd7070Spatrick   }
1494e5dd7070Spatrick 
1495e5dd7070Spatrick private:
1496e5dd7070Spatrick   void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1497e5dd7070Spatrick                  bool OnlyRequiredArgs);
1498e5dd7070Spatrick };
1499e5dd7070Spatrick 
construct(const ASTContext & Context,const CGFunctionInfo & FI,bool OnlyRequiredArgs)1500e5dd7070Spatrick void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1501e5dd7070Spatrick                                       const CGFunctionInfo &FI,
1502e5dd7070Spatrick                                       bool OnlyRequiredArgs) {
1503e5dd7070Spatrick   unsigned IRArgNo = 0;
1504e5dd7070Spatrick   bool SwapThisWithSRet = false;
1505e5dd7070Spatrick   const ABIArgInfo &RetAI = FI.getReturnInfo();
1506e5dd7070Spatrick 
1507e5dd7070Spatrick   if (RetAI.getKind() == ABIArgInfo::Indirect) {
1508e5dd7070Spatrick     SwapThisWithSRet = RetAI.isSRetAfterThis();
1509e5dd7070Spatrick     SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1510e5dd7070Spatrick   }
1511e5dd7070Spatrick 
1512e5dd7070Spatrick   unsigned ArgNo = 0;
1513e5dd7070Spatrick   unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1514e5dd7070Spatrick   for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1515e5dd7070Spatrick        ++I, ++ArgNo) {
1516e5dd7070Spatrick     assert(I != FI.arg_end());
1517e5dd7070Spatrick     QualType ArgType = I->type;
1518e5dd7070Spatrick     const ABIArgInfo &AI = I->info;
1519e5dd7070Spatrick     // Collect data about IR arguments corresponding to Clang argument ArgNo.
1520e5dd7070Spatrick     auto &IRArgs = ArgInfo[ArgNo];
1521e5dd7070Spatrick 
1522e5dd7070Spatrick     if (AI.getPaddingType())
1523e5dd7070Spatrick       IRArgs.PaddingArgIndex = IRArgNo++;
1524e5dd7070Spatrick 
1525e5dd7070Spatrick     switch (AI.getKind()) {
1526e5dd7070Spatrick     case ABIArgInfo::Extend:
1527e5dd7070Spatrick     case ABIArgInfo::Direct: {
1528e5dd7070Spatrick       // FIXME: handle sseregparm someday...
1529e5dd7070Spatrick       llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1530e5dd7070Spatrick       if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1531e5dd7070Spatrick         IRArgs.NumberOfArgs = STy->getNumElements();
1532e5dd7070Spatrick       } else {
1533e5dd7070Spatrick         IRArgs.NumberOfArgs = 1;
1534e5dd7070Spatrick       }
1535e5dd7070Spatrick       break;
1536e5dd7070Spatrick     }
1537e5dd7070Spatrick     case ABIArgInfo::Indirect:
1538a0747c9fSpatrick     case ABIArgInfo::IndirectAliased:
1539e5dd7070Spatrick       IRArgs.NumberOfArgs = 1;
1540e5dd7070Spatrick       break;
1541e5dd7070Spatrick     case ABIArgInfo::Ignore:
1542e5dd7070Spatrick     case ABIArgInfo::InAlloca:
1543e5dd7070Spatrick       // ignore and inalloca doesn't have matching LLVM parameters.
1544e5dd7070Spatrick       IRArgs.NumberOfArgs = 0;
1545e5dd7070Spatrick       break;
1546e5dd7070Spatrick     case ABIArgInfo::CoerceAndExpand:
1547e5dd7070Spatrick       IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1548e5dd7070Spatrick       break;
1549e5dd7070Spatrick     case ABIArgInfo::Expand:
1550e5dd7070Spatrick       IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1551e5dd7070Spatrick       break;
1552e5dd7070Spatrick     }
1553e5dd7070Spatrick 
1554e5dd7070Spatrick     if (IRArgs.NumberOfArgs > 0) {
1555e5dd7070Spatrick       IRArgs.FirstArgIndex = IRArgNo;
1556e5dd7070Spatrick       IRArgNo += IRArgs.NumberOfArgs;
1557e5dd7070Spatrick     }
1558e5dd7070Spatrick 
1559e5dd7070Spatrick     // Skip over the sret parameter when it comes second.  We already handled it
1560e5dd7070Spatrick     // above.
1561e5dd7070Spatrick     if (IRArgNo == 1 && SwapThisWithSRet)
1562e5dd7070Spatrick       IRArgNo++;
1563e5dd7070Spatrick   }
1564e5dd7070Spatrick   assert(ArgNo == ArgInfo.size());
1565e5dd7070Spatrick 
1566e5dd7070Spatrick   if (FI.usesInAlloca())
1567e5dd7070Spatrick     InallocaArgNo = IRArgNo++;
1568e5dd7070Spatrick 
1569e5dd7070Spatrick   TotalIRArgs = IRArgNo;
1570e5dd7070Spatrick }
1571e5dd7070Spatrick }  // namespace
1572e5dd7070Spatrick 
1573e5dd7070Spatrick /***/
1574e5dd7070Spatrick 
ReturnTypeUsesSRet(const CGFunctionInfo & FI)1575e5dd7070Spatrick bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
1576e5dd7070Spatrick   const auto &RI = FI.getReturnInfo();
1577e5dd7070Spatrick   return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet());
1578e5dd7070Spatrick }
1579e5dd7070Spatrick 
ReturnSlotInterferesWithArgs(const CGFunctionInfo & FI)1580e5dd7070Spatrick bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1581e5dd7070Spatrick   return ReturnTypeUsesSRet(FI) &&
1582e5dd7070Spatrick          getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1583e5dd7070Spatrick }
1584e5dd7070Spatrick 
ReturnTypeUsesFPRet(QualType ResultType)1585e5dd7070Spatrick bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1586e5dd7070Spatrick   if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1587e5dd7070Spatrick     switch (BT->getKind()) {
1588e5dd7070Spatrick     default:
1589e5dd7070Spatrick       return false;
1590e5dd7070Spatrick     case BuiltinType::Float:
1591*7a9b00ceSrobert       return getTarget().useObjCFPRetForRealType(FloatModeKind::Float);
1592e5dd7070Spatrick     case BuiltinType::Double:
1593*7a9b00ceSrobert       return getTarget().useObjCFPRetForRealType(FloatModeKind::Double);
1594e5dd7070Spatrick     case BuiltinType::LongDouble:
1595*7a9b00ceSrobert       return getTarget().useObjCFPRetForRealType(FloatModeKind::LongDouble);
1596e5dd7070Spatrick     }
1597e5dd7070Spatrick   }
1598e5dd7070Spatrick 
1599e5dd7070Spatrick   return false;
1600e5dd7070Spatrick }
1601e5dd7070Spatrick 
ReturnTypeUsesFP2Ret(QualType ResultType)1602e5dd7070Spatrick bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1603e5dd7070Spatrick   if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1604e5dd7070Spatrick     if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1605e5dd7070Spatrick       if (BT->getKind() == BuiltinType::LongDouble)
1606e5dd7070Spatrick         return getTarget().useObjCFP2RetForComplexLongDouble();
1607e5dd7070Spatrick     }
1608e5dd7070Spatrick   }
1609e5dd7070Spatrick 
1610e5dd7070Spatrick   return false;
1611e5dd7070Spatrick }
1612e5dd7070Spatrick 
GetFunctionType(GlobalDecl GD)1613e5dd7070Spatrick llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
1614e5dd7070Spatrick   const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1615e5dd7070Spatrick   return GetFunctionType(FI);
1616e5dd7070Spatrick }
1617e5dd7070Spatrick 
1618e5dd7070Spatrick llvm::FunctionType *
GetFunctionType(const CGFunctionInfo & FI)1619e5dd7070Spatrick CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
1620e5dd7070Spatrick 
1621e5dd7070Spatrick   bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1622e5dd7070Spatrick   (void)Inserted;
1623e5dd7070Spatrick   assert(Inserted && "Recursively being processed?");
1624e5dd7070Spatrick 
1625e5dd7070Spatrick   llvm::Type *resultType = nullptr;
1626e5dd7070Spatrick   const ABIArgInfo &retAI = FI.getReturnInfo();
1627e5dd7070Spatrick   switch (retAI.getKind()) {
1628e5dd7070Spatrick   case ABIArgInfo::Expand:
1629a0747c9fSpatrick   case ABIArgInfo::IndirectAliased:
1630e5dd7070Spatrick     llvm_unreachable("Invalid ABI kind for return argument");
1631e5dd7070Spatrick 
1632e5dd7070Spatrick   case ABIArgInfo::Extend:
1633e5dd7070Spatrick   case ABIArgInfo::Direct:
1634e5dd7070Spatrick     resultType = retAI.getCoerceToType();
1635e5dd7070Spatrick     break;
1636e5dd7070Spatrick 
1637e5dd7070Spatrick   case ABIArgInfo::InAlloca:
1638e5dd7070Spatrick     if (retAI.getInAllocaSRet()) {
1639e5dd7070Spatrick       // sret things on win32 aren't void, they return the sret pointer.
1640e5dd7070Spatrick       QualType ret = FI.getReturnType();
1641e5dd7070Spatrick       llvm::Type *ty = ConvertType(ret);
1642*7a9b00ceSrobert       unsigned addressSpace = CGM.getTypes().getTargetAddressSpace(ret);
1643e5dd7070Spatrick       resultType = llvm::PointerType::get(ty, addressSpace);
1644e5dd7070Spatrick     } else {
1645e5dd7070Spatrick       resultType = llvm::Type::getVoidTy(getLLVMContext());
1646e5dd7070Spatrick     }
1647e5dd7070Spatrick     break;
1648e5dd7070Spatrick 
1649e5dd7070Spatrick   case ABIArgInfo::Indirect:
1650e5dd7070Spatrick   case ABIArgInfo::Ignore:
1651e5dd7070Spatrick     resultType = llvm::Type::getVoidTy(getLLVMContext());
1652e5dd7070Spatrick     break;
1653e5dd7070Spatrick 
1654e5dd7070Spatrick   case ABIArgInfo::CoerceAndExpand:
1655e5dd7070Spatrick     resultType = retAI.getUnpaddedCoerceAndExpandType();
1656e5dd7070Spatrick     break;
1657e5dd7070Spatrick   }
1658e5dd7070Spatrick 
1659e5dd7070Spatrick   ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1660e5dd7070Spatrick   SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1661e5dd7070Spatrick 
1662e5dd7070Spatrick   // Add type for sret argument.
1663e5dd7070Spatrick   if (IRFunctionArgs.hasSRetArg()) {
1664e5dd7070Spatrick     QualType Ret = FI.getReturnType();
1665e5dd7070Spatrick     llvm::Type *Ty = ConvertType(Ret);
1666*7a9b00ceSrobert     unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(Ret);
1667e5dd7070Spatrick     ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1668e5dd7070Spatrick         llvm::PointerType::get(Ty, AddressSpace);
1669e5dd7070Spatrick   }
1670e5dd7070Spatrick 
1671e5dd7070Spatrick   // Add type for inalloca argument.
1672e5dd7070Spatrick   if (IRFunctionArgs.hasInallocaArg()) {
1673e5dd7070Spatrick     auto ArgStruct = FI.getArgStruct();
1674e5dd7070Spatrick     assert(ArgStruct);
1675e5dd7070Spatrick     ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1676e5dd7070Spatrick   }
1677e5dd7070Spatrick 
1678e5dd7070Spatrick   // Add in all of the required arguments.
1679e5dd7070Spatrick   unsigned ArgNo = 0;
1680e5dd7070Spatrick   CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1681e5dd7070Spatrick                                      ie = it + FI.getNumRequiredArgs();
1682e5dd7070Spatrick   for (; it != ie; ++it, ++ArgNo) {
1683e5dd7070Spatrick     const ABIArgInfo &ArgInfo = it->info;
1684e5dd7070Spatrick 
1685e5dd7070Spatrick     // Insert a padding type to ensure proper alignment.
1686e5dd7070Spatrick     if (IRFunctionArgs.hasPaddingArg(ArgNo))
1687e5dd7070Spatrick       ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1688e5dd7070Spatrick           ArgInfo.getPaddingType();
1689e5dd7070Spatrick 
1690e5dd7070Spatrick     unsigned FirstIRArg, NumIRArgs;
1691e5dd7070Spatrick     std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1692e5dd7070Spatrick 
1693e5dd7070Spatrick     switch (ArgInfo.getKind()) {
1694e5dd7070Spatrick     case ABIArgInfo::Ignore:
1695e5dd7070Spatrick     case ABIArgInfo::InAlloca:
1696e5dd7070Spatrick       assert(NumIRArgs == 0);
1697e5dd7070Spatrick       break;
1698e5dd7070Spatrick 
1699e5dd7070Spatrick     case ABIArgInfo::Indirect: {
1700e5dd7070Spatrick       assert(NumIRArgs == 1);
1701e5dd7070Spatrick       // indirect arguments are always on the stack, which is alloca addr space.
1702e5dd7070Spatrick       llvm::Type *LTy = ConvertTypeForMem(it->type);
1703e5dd7070Spatrick       ArgTypes[FirstIRArg] = LTy->getPointerTo(
1704e5dd7070Spatrick           CGM.getDataLayout().getAllocaAddrSpace());
1705e5dd7070Spatrick       break;
1706e5dd7070Spatrick     }
1707a0747c9fSpatrick     case ABIArgInfo::IndirectAliased: {
1708a0747c9fSpatrick       assert(NumIRArgs == 1);
1709a0747c9fSpatrick       llvm::Type *LTy = ConvertTypeForMem(it->type);
1710a0747c9fSpatrick       ArgTypes[FirstIRArg] = LTy->getPointerTo(ArgInfo.getIndirectAddrSpace());
1711a0747c9fSpatrick       break;
1712a0747c9fSpatrick     }
1713e5dd7070Spatrick     case ABIArgInfo::Extend:
1714e5dd7070Spatrick     case ABIArgInfo::Direct: {
1715e5dd7070Spatrick       // Fast-isel and the optimizer generally like scalar values better than
1716e5dd7070Spatrick       // FCAs, so we flatten them if this is safe to do for this argument.
1717e5dd7070Spatrick       llvm::Type *argType = ArgInfo.getCoerceToType();
1718e5dd7070Spatrick       llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
1719e5dd7070Spatrick       if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1720e5dd7070Spatrick         assert(NumIRArgs == st->getNumElements());
1721e5dd7070Spatrick         for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
1722e5dd7070Spatrick           ArgTypes[FirstIRArg + i] = st->getElementType(i);
1723e5dd7070Spatrick       } else {
1724e5dd7070Spatrick         assert(NumIRArgs == 1);
1725e5dd7070Spatrick         ArgTypes[FirstIRArg] = argType;
1726e5dd7070Spatrick       }
1727e5dd7070Spatrick       break;
1728e5dd7070Spatrick     }
1729e5dd7070Spatrick 
1730e5dd7070Spatrick     case ABIArgInfo::CoerceAndExpand: {
1731e5dd7070Spatrick       auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1732*7a9b00ceSrobert       for (auto *EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1733e5dd7070Spatrick         *ArgTypesIter++ = EltTy;
1734e5dd7070Spatrick       }
1735e5dd7070Spatrick       assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1736e5dd7070Spatrick       break;
1737e5dd7070Spatrick     }
1738e5dd7070Spatrick 
1739e5dd7070Spatrick     case ABIArgInfo::Expand:
1740e5dd7070Spatrick       auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1741e5dd7070Spatrick       getExpandedTypes(it->type, ArgTypesIter);
1742e5dd7070Spatrick       assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1743e5dd7070Spatrick       break;
1744e5dd7070Spatrick     }
1745e5dd7070Spatrick   }
1746e5dd7070Spatrick 
1747e5dd7070Spatrick   bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1748e5dd7070Spatrick   assert(Erased && "Not in set?");
1749e5dd7070Spatrick 
1750e5dd7070Spatrick   return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
1751e5dd7070Spatrick }
1752e5dd7070Spatrick 
GetFunctionTypeForVTable(GlobalDecl GD)1753e5dd7070Spatrick llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
1754e5dd7070Spatrick   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1755e5dd7070Spatrick   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
1756e5dd7070Spatrick 
1757e5dd7070Spatrick   if (!isFuncTypeConvertible(FPT))
1758e5dd7070Spatrick     return llvm::StructType::get(getLLVMContext());
1759e5dd7070Spatrick 
1760e5dd7070Spatrick   return GetFunctionType(GD);
1761e5dd7070Spatrick }
1762e5dd7070Spatrick 
AddAttributesFromFunctionProtoType(ASTContext & Ctx,llvm::AttrBuilder & FuncAttrs,const FunctionProtoType * FPT)1763e5dd7070Spatrick static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
1764e5dd7070Spatrick                                                llvm::AttrBuilder &FuncAttrs,
1765e5dd7070Spatrick                                                const FunctionProtoType *FPT) {
1766e5dd7070Spatrick   if (!FPT)
1767e5dd7070Spatrick     return;
1768e5dd7070Spatrick 
1769e5dd7070Spatrick   if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
1770e5dd7070Spatrick       FPT->isNothrow())
1771e5dd7070Spatrick     FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1772e5dd7070Spatrick }
1773e5dd7070Spatrick 
AddAttributesFromAssumes(llvm::AttrBuilder & FuncAttrs,const Decl * Callee)1774*7a9b00ceSrobert static void AddAttributesFromAssumes(llvm::AttrBuilder &FuncAttrs,
1775*7a9b00ceSrobert                                      const Decl *Callee) {
1776*7a9b00ceSrobert   if (!Callee)
1777*7a9b00ceSrobert     return;
1778*7a9b00ceSrobert 
1779*7a9b00ceSrobert   SmallVector<StringRef, 4> Attrs;
1780*7a9b00ceSrobert 
1781*7a9b00ceSrobert   for (const AssumptionAttr *AA : Callee->specific_attrs<AssumptionAttr>())
1782*7a9b00ceSrobert     AA->getAssumption().split(Attrs, ",");
1783*7a9b00ceSrobert 
1784*7a9b00ceSrobert   if (!Attrs.empty())
1785*7a9b00ceSrobert     FuncAttrs.addAttribute(llvm::AssumptionAttrKey,
1786*7a9b00ceSrobert                            llvm::join(Attrs.begin(), Attrs.end(), ","));
1787*7a9b00ceSrobert }
1788*7a9b00ceSrobert 
MayDropFunctionReturn(const ASTContext & Context,QualType ReturnType) const1789a0747c9fSpatrick bool CodeGenModule::MayDropFunctionReturn(const ASTContext &Context,
1790*7a9b00ceSrobert                                           QualType ReturnType) const {
1791a0747c9fSpatrick   // We can't just discard the return value for a record type with a
1792a0747c9fSpatrick   // complex destructor or a non-trivially copyable type.
1793a0747c9fSpatrick   if (const RecordType *RT =
1794a0747c9fSpatrick           ReturnType.getCanonicalType()->getAs<RecordType>()) {
1795a0747c9fSpatrick     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1796a0747c9fSpatrick       return ClassDecl->hasTrivialDestructor();
1797a0747c9fSpatrick   }
1798a0747c9fSpatrick   return ReturnType.isTriviallyCopyableType(Context);
1799a0747c9fSpatrick }
1800a0747c9fSpatrick 
HasStrictReturn(const CodeGenModule & Module,QualType RetTy,const Decl * TargetDecl)1801*7a9b00ceSrobert static bool HasStrictReturn(const CodeGenModule &Module, QualType RetTy,
1802*7a9b00ceSrobert                             const Decl *TargetDecl) {
1803*7a9b00ceSrobert   // As-is msan can not tolerate noundef mismatch between caller and
1804*7a9b00ceSrobert   // implementation. Mismatch is possible for e.g. indirect calls from C-caller
1805*7a9b00ceSrobert   // into C++. Such mismatches lead to confusing false reports. To avoid
1806*7a9b00ceSrobert   // expensive workaround on msan we enforce initialization event in uncommon
1807*7a9b00ceSrobert   // cases where it's allowed.
1808*7a9b00ceSrobert   if (Module.getLangOpts().Sanitize.has(SanitizerKind::Memory))
1809*7a9b00ceSrobert     return true;
1810*7a9b00ceSrobert   // C++ explicitly makes returning undefined values UB. C's rule only applies
1811*7a9b00ceSrobert   // to used values, so we never mark them noundef for now.
1812*7a9b00ceSrobert   if (!Module.getLangOpts().CPlusPlus)
1813*7a9b00ceSrobert     return false;
1814*7a9b00ceSrobert   if (TargetDecl) {
1815*7a9b00ceSrobert     if (const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(TargetDecl)) {
1816*7a9b00ceSrobert       if (FDecl->isExternC())
1817*7a9b00ceSrobert         return false;
1818*7a9b00ceSrobert     } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(TargetDecl)) {
1819*7a9b00ceSrobert       // Function pointer.
1820*7a9b00ceSrobert       if (VDecl->isExternC())
1821*7a9b00ceSrobert         return false;
1822*7a9b00ceSrobert     }
1823*7a9b00ceSrobert   }
1824*7a9b00ceSrobert 
1825*7a9b00ceSrobert   // We don't want to be too aggressive with the return checking, unless
1826*7a9b00ceSrobert   // it's explicit in the code opts or we're using an appropriate sanitizer.
1827*7a9b00ceSrobert   // Try to respect what the programmer intended.
1828*7a9b00ceSrobert   return Module.getCodeGenOpts().StrictReturn ||
1829*7a9b00ceSrobert          !Module.MayDropFunctionReturn(Module.getContext(), RetTy) ||
1830*7a9b00ceSrobert          Module.getLangOpts().Sanitize.has(SanitizerKind::Return);
1831*7a9b00ceSrobert }
1832*7a9b00ceSrobert 
getDefaultFunctionAttributes(StringRef Name,bool HasOptnone,bool AttrOnCallSite,llvm::AttrBuilder & FuncAttrs)1833ec727ea7Spatrick void CodeGenModule::getDefaultFunctionAttributes(StringRef Name,
1834ec727ea7Spatrick                                                  bool HasOptnone,
1835e5dd7070Spatrick                                                  bool AttrOnCallSite,
1836e5dd7070Spatrick                                                llvm::AttrBuilder &FuncAttrs) {
1837e5dd7070Spatrick   // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1838e5dd7070Spatrick   if (!HasOptnone) {
1839e5dd7070Spatrick     if (CodeGenOpts.OptimizeSize)
1840e5dd7070Spatrick       FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1841e5dd7070Spatrick     if (CodeGenOpts.OptimizeSize == 2)
1842e5dd7070Spatrick       FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1843e5dd7070Spatrick   }
1844e5dd7070Spatrick 
1845e5dd7070Spatrick   if (CodeGenOpts.DisableRedZone)
1846e5dd7070Spatrick     FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
1847e5dd7070Spatrick   if (CodeGenOpts.IndirectTlsSegRefs)
1848e5dd7070Spatrick     FuncAttrs.addAttribute("indirect-tls-seg-refs");
1849e5dd7070Spatrick   if (CodeGenOpts.NoImplicitFloat)
1850e5dd7070Spatrick     FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
1851e5dd7070Spatrick 
1852e5dd7070Spatrick   if (AttrOnCallSite) {
1853e5dd7070Spatrick     // Attributes that should go on the call site only.
1854*7a9b00ceSrobert     // FIXME: Look for 'BuiltinAttr' on the function rather than re-checking
1855*7a9b00ceSrobert     // the -fno-builtin-foo list.
1856a0747c9fSpatrick     if (!CodeGenOpts.SimplifyLibCalls || LangOpts.isNoBuiltinFunc(Name))
1857e5dd7070Spatrick       FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
1858e5dd7070Spatrick     if (!CodeGenOpts.TrapFuncName.empty())
1859e5dd7070Spatrick       FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
1860e5dd7070Spatrick   } else {
1861e5dd7070Spatrick     switch (CodeGenOpts.getFramePointer()) {
1862e5dd7070Spatrick     case CodeGenOptions::FramePointerKind::None:
1863*7a9b00ceSrobert       // This is the default behavior.
1864e5dd7070Spatrick       break;
1865e5dd7070Spatrick     case CodeGenOptions::FramePointerKind::NonLeaf:
1866e5dd7070Spatrick     case CodeGenOptions::FramePointerKind::All:
1867*7a9b00ceSrobert       FuncAttrs.addAttribute("frame-pointer",
1868*7a9b00ceSrobert                              CodeGenOptions::getFramePointerKindName(
1869*7a9b00ceSrobert                                  CodeGenOpts.getFramePointer()));
1870e5dd7070Spatrick     }
1871e5dd7070Spatrick 
1872a0747c9fSpatrick     if (CodeGenOpts.LessPreciseFPMAD)
1873a0747c9fSpatrick       FuncAttrs.addAttribute("less-precise-fpmad", "true");
1874e5dd7070Spatrick 
1875e5dd7070Spatrick     if (CodeGenOpts.NullPointerIsValid)
1876ec727ea7Spatrick       FuncAttrs.addAttribute(llvm::Attribute::NullPointerIsValid);
1877ec727ea7Spatrick 
1878ec727ea7Spatrick     if (CodeGenOpts.FPDenormalMode != llvm::DenormalMode::getIEEE())
1879e5dd7070Spatrick       FuncAttrs.addAttribute("denormal-fp-math",
1880ec727ea7Spatrick                              CodeGenOpts.FPDenormalMode.str());
1881ec727ea7Spatrick     if (CodeGenOpts.FP32DenormalMode != CodeGenOpts.FPDenormalMode) {
1882ec727ea7Spatrick       FuncAttrs.addAttribute(
1883ec727ea7Spatrick           "denormal-fp-math-f32",
1884ec727ea7Spatrick           CodeGenOpts.FP32DenormalMode.str());
1885ec727ea7Spatrick     }
1886e5dd7070Spatrick 
1887*7a9b00ceSrobert     if (LangOpts.getDefaultExceptionMode() == LangOptions::FPE_Ignore)
1888a0747c9fSpatrick       FuncAttrs.addAttribute("no-trapping-math", "true");
1889e5dd7070Spatrick 
1890e5dd7070Spatrick     // TODO: Are these all needed?
1891e5dd7070Spatrick     // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
1892a0747c9fSpatrick     if (LangOpts.NoHonorInfs)
1893a0747c9fSpatrick       FuncAttrs.addAttribute("no-infs-fp-math", "true");
1894a0747c9fSpatrick     if (LangOpts.NoHonorNaNs)
1895a0747c9fSpatrick       FuncAttrs.addAttribute("no-nans-fp-math", "true");
1896*7a9b00ceSrobert     if (LangOpts.ApproxFunc)
1897*7a9b00ceSrobert       FuncAttrs.addAttribute("approx-func-fp-math", "true");
1898*7a9b00ceSrobert     if (LangOpts.AllowFPReassoc && LangOpts.AllowRecip &&
1899*7a9b00ceSrobert         LangOpts.NoSignedZero && LangOpts.ApproxFunc &&
1900*7a9b00ceSrobert         (LangOpts.getDefaultFPContractMode() ==
1901*7a9b00ceSrobert              LangOptions::FPModeKind::FPM_Fast ||
1902*7a9b00ceSrobert          LangOpts.getDefaultFPContractMode() ==
1903*7a9b00ceSrobert              LangOptions::FPModeKind::FPM_FastHonorPragmas))
1904a0747c9fSpatrick       FuncAttrs.addAttribute("unsafe-fp-math", "true");
1905a0747c9fSpatrick     if (CodeGenOpts.SoftFloat)
1906a0747c9fSpatrick       FuncAttrs.addAttribute("use-soft-float", "true");
1907e5dd7070Spatrick     FuncAttrs.addAttribute("stack-protector-buffer-size",
1908e5dd7070Spatrick                            llvm::utostr(CodeGenOpts.SSPBufferSize));
1909a0747c9fSpatrick     if (LangOpts.NoSignedZero)
1910a0747c9fSpatrick       FuncAttrs.addAttribute("no-signed-zeros-fp-math", "true");
1911e5dd7070Spatrick 
1912e5dd7070Spatrick     // TODO: Reciprocal estimate codegen options should apply to instructions?
1913e5dd7070Spatrick     const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals;
1914e5dd7070Spatrick     if (!Recips.empty())
1915e5dd7070Spatrick       FuncAttrs.addAttribute("reciprocal-estimates",
1916e5dd7070Spatrick                              llvm::join(Recips, ","));
1917e5dd7070Spatrick 
1918e5dd7070Spatrick     if (!CodeGenOpts.PreferVectorWidth.empty() &&
1919e5dd7070Spatrick         CodeGenOpts.PreferVectorWidth != "none")
1920e5dd7070Spatrick       FuncAttrs.addAttribute("prefer-vector-width",
1921e5dd7070Spatrick                              CodeGenOpts.PreferVectorWidth);
1922e5dd7070Spatrick 
1923e5dd7070Spatrick     if (CodeGenOpts.StackRealignment)
1924e5dd7070Spatrick       FuncAttrs.addAttribute("stackrealign");
1925e5dd7070Spatrick     if (CodeGenOpts.Backchain)
1926e5dd7070Spatrick       FuncAttrs.addAttribute("backchain");
1927ec727ea7Spatrick     if (CodeGenOpts.EnableSegmentedStacks)
1928ec727ea7Spatrick       FuncAttrs.addAttribute("split-stack");
1929e5dd7070Spatrick 
1930e5dd7070Spatrick     if (CodeGenOpts.SpeculativeLoadHardening)
1931e5dd7070Spatrick       FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
1932*7a9b00ceSrobert 
1933*7a9b00ceSrobert     // Add zero-call-used-regs attribute.
1934*7a9b00ceSrobert     switch (CodeGenOpts.getZeroCallUsedRegs()) {
1935*7a9b00ceSrobert     case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Skip:
1936*7a9b00ceSrobert       FuncAttrs.removeAttribute("zero-call-used-regs");
1937*7a9b00ceSrobert       break;
1938*7a9b00ceSrobert     case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPRArg:
1939*7a9b00ceSrobert       FuncAttrs.addAttribute("zero-call-used-regs", "used-gpr-arg");
1940*7a9b00ceSrobert       break;
1941*7a9b00ceSrobert     case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPR:
1942*7a9b00ceSrobert       FuncAttrs.addAttribute("zero-call-used-regs", "used-gpr");
1943*7a9b00ceSrobert       break;
1944*7a9b00ceSrobert     case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedArg:
1945*7a9b00ceSrobert       FuncAttrs.addAttribute("zero-call-used-regs", "used-arg");
1946*7a9b00ceSrobert       break;
1947*7a9b00ceSrobert     case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Used:
1948*7a9b00ceSrobert       FuncAttrs.addAttribute("zero-call-used-regs", "used");
1949*7a9b00ceSrobert       break;
1950*7a9b00ceSrobert     case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPRArg:
1951*7a9b00ceSrobert       FuncAttrs.addAttribute("zero-call-used-regs", "all-gpr-arg");
1952*7a9b00ceSrobert       break;
1953*7a9b00ceSrobert     case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPR:
1954*7a9b00ceSrobert       FuncAttrs.addAttribute("zero-call-used-regs", "all-gpr");
1955*7a9b00ceSrobert       break;
1956*7a9b00ceSrobert     case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllArg:
1957*7a9b00ceSrobert       FuncAttrs.addAttribute("zero-call-used-regs", "all-arg");
1958*7a9b00ceSrobert       break;
1959*7a9b00ceSrobert     case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::All:
1960*7a9b00ceSrobert       FuncAttrs.addAttribute("zero-call-used-regs", "all");
1961*7a9b00ceSrobert       break;
1962*7a9b00ceSrobert     }
1963e5dd7070Spatrick   }
1964e5dd7070Spatrick 
1965e5dd7070Spatrick   if (getLangOpts().assumeFunctionsAreConvergent()) {
1966e5dd7070Spatrick     // Conservatively, mark all functions and calls in CUDA and OpenCL as
1967e5dd7070Spatrick     // convergent (meaning, they may call an intrinsically convergent op, such
1968e5dd7070Spatrick     // as __syncthreads() / barrier(), and so can't have certain optimizations
1969e5dd7070Spatrick     // applied around them).  LLVM will remove this attribute where it safely
1970e5dd7070Spatrick     // can.
1971e5dd7070Spatrick     FuncAttrs.addAttribute(llvm::Attribute::Convergent);
1972e5dd7070Spatrick   }
1973e5dd7070Spatrick 
1974*7a9b00ceSrobert   // TODO: NoUnwind attribute should be added for other GPU modes HIP,
1975*7a9b00ceSrobert   // SYCL, OpenMP offload. AFAIK, none of them support exceptions in device
1976*7a9b00ceSrobert   // code.
1977*7a9b00ceSrobert   if ((getLangOpts().CUDA && getLangOpts().CUDAIsDevice) ||
1978*7a9b00ceSrobert       getLangOpts().OpenCL) {
1979e5dd7070Spatrick     FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1980e5dd7070Spatrick   }
1981e5dd7070Spatrick 
1982e5dd7070Spatrick   for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) {
1983e5dd7070Spatrick     StringRef Var, Value;
1984e5dd7070Spatrick     std::tie(Var, Value) = Attr.split('=');
1985e5dd7070Spatrick     FuncAttrs.addAttribute(Var, Value);
1986e5dd7070Spatrick   }
1987e5dd7070Spatrick }
1988e5dd7070Spatrick 
addDefaultFunctionDefinitionAttributes(llvm::Function & F)1989ec727ea7Spatrick void CodeGenModule::addDefaultFunctionDefinitionAttributes(llvm::Function &F) {
1990*7a9b00ceSrobert   llvm::AttrBuilder FuncAttrs(F.getContext());
1991ec727ea7Spatrick   getDefaultFunctionAttributes(F.getName(), F.hasOptNone(),
1992e5dd7070Spatrick                                /* AttrOnCallSite = */ false, FuncAttrs);
1993ec727ea7Spatrick   // TODO: call GetCPUAndFeaturesAttributes?
1994*7a9b00ceSrobert   F.addFnAttrs(FuncAttrs);
1995e5dd7070Spatrick }
1996e5dd7070Spatrick 
addDefaultFunctionDefinitionAttributes(llvm::AttrBuilder & attrs)1997ec727ea7Spatrick void CodeGenModule::addDefaultFunctionDefinitionAttributes(
1998ec727ea7Spatrick                                                    llvm::AttrBuilder &attrs) {
1999ec727ea7Spatrick   getDefaultFunctionAttributes(/*function name*/ "", /*optnone*/ false,
2000ec727ea7Spatrick                                /*for call*/ false, attrs);
2001ec727ea7Spatrick   GetCPUAndFeaturesAttributes(GlobalDecl(), attrs);
2002ec727ea7Spatrick }
2003ec727ea7Spatrick 
addNoBuiltinAttributes(llvm::AttrBuilder & FuncAttrs,const LangOptions & LangOpts,const NoBuiltinAttr * NBA=nullptr)2004ec727ea7Spatrick static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs,
2005ec727ea7Spatrick                                    const LangOptions &LangOpts,
2006ec727ea7Spatrick                                    const NoBuiltinAttr *NBA = nullptr) {
2007ec727ea7Spatrick   auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) {
2008ec727ea7Spatrick     SmallString<32> AttributeName;
2009ec727ea7Spatrick     AttributeName += "no-builtin-";
2010ec727ea7Spatrick     AttributeName += BuiltinName;
2011ec727ea7Spatrick     FuncAttrs.addAttribute(AttributeName);
2012ec727ea7Spatrick   };
2013ec727ea7Spatrick 
2014ec727ea7Spatrick   // First, handle the language options passed through -fno-builtin.
2015ec727ea7Spatrick   if (LangOpts.NoBuiltin) {
2016ec727ea7Spatrick     // -fno-builtin disables them all.
2017ec727ea7Spatrick     FuncAttrs.addAttribute("no-builtins");
2018ec727ea7Spatrick     return;
2019ec727ea7Spatrick   }
2020ec727ea7Spatrick 
2021ec727ea7Spatrick   // Then, add attributes for builtins specified through -fno-builtin-<name>.
2022ec727ea7Spatrick   llvm::for_each(LangOpts.NoBuiltinFuncs, AddNoBuiltinAttr);
2023ec727ea7Spatrick 
2024ec727ea7Spatrick   // Now, let's check the __attribute__((no_builtin("...")) attribute added to
2025ec727ea7Spatrick   // the source.
2026ec727ea7Spatrick   if (!NBA)
2027ec727ea7Spatrick     return;
2028ec727ea7Spatrick 
2029ec727ea7Spatrick   // If there is a wildcard in the builtin names specified through the
2030ec727ea7Spatrick   // attribute, disable them all.
2031ec727ea7Spatrick   if (llvm::is_contained(NBA->builtinNames(), "*")) {
2032ec727ea7Spatrick     FuncAttrs.addAttribute("no-builtins");
2033ec727ea7Spatrick     return;
2034ec727ea7Spatrick   }
2035ec727ea7Spatrick 
2036ec727ea7Spatrick   // And last, add the rest of the builtin names.
2037ec727ea7Spatrick   llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr);
2038ec727ea7Spatrick }
2039ec727ea7Spatrick 
DetermineNoUndef(QualType QTy,CodeGenTypes & Types,const llvm::DataLayout & DL,const ABIArgInfo & AI,bool CheckCoerce=true)2040a0747c9fSpatrick static bool DetermineNoUndef(QualType QTy, CodeGenTypes &Types,
2041a0747c9fSpatrick                              const llvm::DataLayout &DL, const ABIArgInfo &AI,
2042a0747c9fSpatrick                              bool CheckCoerce = true) {
2043a0747c9fSpatrick   llvm::Type *Ty = Types.ConvertTypeForMem(QTy);
2044a0747c9fSpatrick   if (AI.getKind() == ABIArgInfo::Indirect)
2045a0747c9fSpatrick     return true;
2046a0747c9fSpatrick   if (AI.getKind() == ABIArgInfo::Extend)
2047a0747c9fSpatrick     return true;
2048a0747c9fSpatrick   if (!DL.typeSizeEqualsStoreSize(Ty))
2049a0747c9fSpatrick     // TODO: This will result in a modest amount of values not marked noundef
2050a0747c9fSpatrick     // when they could be. We care about values that *invisibly* contain undef
2051a0747c9fSpatrick     // bits from the perspective of LLVM IR.
2052a0747c9fSpatrick     return false;
2053a0747c9fSpatrick   if (CheckCoerce && AI.canHaveCoerceToType()) {
2054a0747c9fSpatrick     llvm::Type *CoerceTy = AI.getCoerceToType();
2055a0747c9fSpatrick     if (llvm::TypeSize::isKnownGT(DL.getTypeSizeInBits(CoerceTy),
2056a0747c9fSpatrick                                   DL.getTypeSizeInBits(Ty)))
2057a0747c9fSpatrick       // If we're coercing to a type with a greater size than the canonical one,
2058a0747c9fSpatrick       // we're introducing new undef bits.
2059a0747c9fSpatrick       // Coercing to a type of smaller or equal size is ok, as we know that
2060a0747c9fSpatrick       // there's no internal padding (typeSizeEqualsStoreSize).
2061a0747c9fSpatrick       return false;
2062a0747c9fSpatrick   }
2063*7a9b00ceSrobert   if (QTy->isBitIntType())
2064a0747c9fSpatrick     return true;
2065a0747c9fSpatrick   if (QTy->isReferenceType())
2066a0747c9fSpatrick     return true;
2067a0747c9fSpatrick   if (QTy->isNullPtrType())
2068a0747c9fSpatrick     return false;
2069a0747c9fSpatrick   if (QTy->isMemberPointerType())
2070a0747c9fSpatrick     // TODO: Some member pointers are `noundef`, but it depends on the ABI. For
2071a0747c9fSpatrick     // now, never mark them.
2072a0747c9fSpatrick     return false;
2073a0747c9fSpatrick   if (QTy->isScalarType()) {
2074a0747c9fSpatrick     if (const ComplexType *Complex = dyn_cast<ComplexType>(QTy))
2075a0747c9fSpatrick       return DetermineNoUndef(Complex->getElementType(), Types, DL, AI, false);
2076a0747c9fSpatrick     return true;
2077a0747c9fSpatrick   }
2078a0747c9fSpatrick   if (const VectorType *Vector = dyn_cast<VectorType>(QTy))
2079a0747c9fSpatrick     return DetermineNoUndef(Vector->getElementType(), Types, DL, AI, false);
2080a0747c9fSpatrick   if (const MatrixType *Matrix = dyn_cast<MatrixType>(QTy))
2081a0747c9fSpatrick     return DetermineNoUndef(Matrix->getElementType(), Types, DL, AI, false);
2082a0747c9fSpatrick   if (const ArrayType *Array = dyn_cast<ArrayType>(QTy))
2083a0747c9fSpatrick     return DetermineNoUndef(Array->getElementType(), Types, DL, AI, false);
2084a0747c9fSpatrick 
2085a0747c9fSpatrick   // TODO: Some structs may be `noundef`, in specific situations.
2086a0747c9fSpatrick   return false;
2087a0747c9fSpatrick }
2088a0747c9fSpatrick 
2089*7a9b00ceSrobert /// Check if the argument of a function has maybe_undef attribute.
IsArgumentMaybeUndef(const Decl * TargetDecl,unsigned NumRequiredArgs,unsigned ArgNo)2090*7a9b00ceSrobert static bool IsArgumentMaybeUndef(const Decl *TargetDecl,
2091*7a9b00ceSrobert                                  unsigned NumRequiredArgs, unsigned ArgNo) {
2092*7a9b00ceSrobert   const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
2093*7a9b00ceSrobert   if (!FD)
2094*7a9b00ceSrobert     return false;
2095*7a9b00ceSrobert 
2096*7a9b00ceSrobert   // Assume variadic arguments do not have maybe_undef attribute.
2097*7a9b00ceSrobert   if (ArgNo >= NumRequiredArgs)
2098*7a9b00ceSrobert     return false;
2099*7a9b00ceSrobert 
2100*7a9b00ceSrobert   // Check if argument has maybe_undef attribute.
2101*7a9b00ceSrobert   if (ArgNo < FD->getNumParams()) {
2102*7a9b00ceSrobert     const ParmVarDecl *Param = FD->getParamDecl(ArgNo);
2103*7a9b00ceSrobert     if (Param && Param->hasAttr<MaybeUndefAttr>())
2104*7a9b00ceSrobert       return true;
2105*7a9b00ceSrobert   }
2106*7a9b00ceSrobert 
2107*7a9b00ceSrobert   return false;
2108*7a9b00ceSrobert }
2109*7a9b00ceSrobert 
2110ec727ea7Spatrick /// Construct the IR attribute list of a function or call.
2111ec727ea7Spatrick ///
2112ec727ea7Spatrick /// When adding an attribute, please consider where it should be handled:
2113ec727ea7Spatrick ///
2114ec727ea7Spatrick ///   - getDefaultFunctionAttributes is for attributes that are essentially
2115ec727ea7Spatrick ///     part of the global target configuration (but perhaps can be
2116ec727ea7Spatrick ///     overridden on a per-function basis).  Adding attributes there
2117ec727ea7Spatrick ///     will cause them to also be set in frontends that build on Clang's
2118ec727ea7Spatrick ///     target-configuration logic, as well as for code defined in library
2119ec727ea7Spatrick ///     modules such as CUDA's libdevice.
2120ec727ea7Spatrick ///
2121ec727ea7Spatrick ///   - ConstructAttributeList builds on top of getDefaultFunctionAttributes
2122ec727ea7Spatrick ///     and adds declaration-specific, convention-specific, and
2123ec727ea7Spatrick ///     frontend-specific logic.  The last is of particular importance:
2124ec727ea7Spatrick ///     attributes that restrict how the frontend generates code must be
2125ec727ea7Spatrick ///     added here rather than getDefaultFunctionAttributes.
2126ec727ea7Spatrick ///
ConstructAttributeList(StringRef Name,const CGFunctionInfo & FI,CGCalleeInfo CalleeInfo,llvm::AttributeList & AttrList,unsigned & CallingConv,bool AttrOnCallSite,bool IsThunk)2127a0747c9fSpatrick void CodeGenModule::ConstructAttributeList(StringRef Name,
2128a0747c9fSpatrick                                            const CGFunctionInfo &FI,
2129a0747c9fSpatrick                                            CGCalleeInfo CalleeInfo,
2130a0747c9fSpatrick                                            llvm::AttributeList &AttrList,
2131a0747c9fSpatrick                                            unsigned &CallingConv,
2132a0747c9fSpatrick                                            bool AttrOnCallSite, bool IsThunk) {
2133*7a9b00ceSrobert   llvm::AttrBuilder FuncAttrs(getLLVMContext());
2134*7a9b00ceSrobert   llvm::AttrBuilder RetAttrs(getLLVMContext());
2135e5dd7070Spatrick 
2136ec727ea7Spatrick   // Collect function IR attributes from the CC lowering.
2137ec727ea7Spatrick   // We'll collect the paramete and result attributes later.
2138e5dd7070Spatrick   CallingConv = FI.getEffectiveCallingConvention();
2139e5dd7070Spatrick   if (FI.isNoReturn())
2140e5dd7070Spatrick     FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2141ec727ea7Spatrick   if (FI.isCmseNSCall())
2142ec727ea7Spatrick     FuncAttrs.addAttribute("cmse_nonsecure_call");
2143e5dd7070Spatrick 
2144ec727ea7Spatrick   // Collect function IR attributes from the callee prototype if we have one.
2145e5dd7070Spatrick   AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
2146e5dd7070Spatrick                                      CalleeInfo.getCalleeFunctionProtoType());
2147e5dd7070Spatrick 
2148e5dd7070Spatrick   const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl();
2149e5dd7070Spatrick 
2150*7a9b00ceSrobert   // Attach assumption attributes to the declaration. If this is a call
2151*7a9b00ceSrobert   // site, attach assumptions from the caller to the call as well.
2152*7a9b00ceSrobert   AddAttributesFromAssumes(FuncAttrs, TargetDecl);
2153*7a9b00ceSrobert 
2154e5dd7070Spatrick   bool HasOptnone = false;
2155ec727ea7Spatrick   // The NoBuiltinAttr attached to the target FunctionDecl.
2156ec727ea7Spatrick   const NoBuiltinAttr *NBA = nullptr;
2157ec727ea7Spatrick 
2158*7a9b00ceSrobert   // Some ABIs may result in additional accesses to arguments that may
2159*7a9b00ceSrobert   // otherwise not be present.
2160*7a9b00ceSrobert   auto AddPotentialArgAccess = [&]() {
2161*7a9b00ceSrobert     llvm::Attribute A = FuncAttrs.getAttribute(llvm::Attribute::Memory);
2162*7a9b00ceSrobert     if (A.isValid())
2163*7a9b00ceSrobert       FuncAttrs.addMemoryAttr(A.getMemoryEffects() |
2164*7a9b00ceSrobert                               llvm::MemoryEffects::argMemOnly());
2165*7a9b00ceSrobert   };
2166*7a9b00ceSrobert 
2167ec727ea7Spatrick   // Collect function IR attributes based on declaration-specific
2168ec727ea7Spatrick   // information.
2169e5dd7070Spatrick   // FIXME: handle sseregparm someday...
2170e5dd7070Spatrick   if (TargetDecl) {
2171e5dd7070Spatrick     if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
2172e5dd7070Spatrick       FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
2173e5dd7070Spatrick     if (TargetDecl->hasAttr<NoThrowAttr>())
2174e5dd7070Spatrick       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2175e5dd7070Spatrick     if (TargetDecl->hasAttr<NoReturnAttr>())
2176e5dd7070Spatrick       FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2177e5dd7070Spatrick     if (TargetDecl->hasAttr<ColdAttr>())
2178e5dd7070Spatrick       FuncAttrs.addAttribute(llvm::Attribute::Cold);
2179a0747c9fSpatrick     if (TargetDecl->hasAttr<HotAttr>())
2180a0747c9fSpatrick       FuncAttrs.addAttribute(llvm::Attribute::Hot);
2181e5dd7070Spatrick     if (TargetDecl->hasAttr<NoDuplicateAttr>())
2182e5dd7070Spatrick       FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
2183e5dd7070Spatrick     if (TargetDecl->hasAttr<ConvergentAttr>())
2184e5dd7070Spatrick       FuncAttrs.addAttribute(llvm::Attribute::Convergent);
2185e5dd7070Spatrick 
2186e5dd7070Spatrick     if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2187e5dd7070Spatrick       AddAttributesFromFunctionProtoType(
2188e5dd7070Spatrick           getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
2189ec727ea7Spatrick       if (AttrOnCallSite && Fn->isReplaceableGlobalAllocationFunction()) {
2190ec727ea7Spatrick         // A sane operator new returns a non-aliasing pointer.
2191ec727ea7Spatrick         auto Kind = Fn->getDeclName().getCXXOverloadedOperator();
2192ec727ea7Spatrick         if (getCodeGenOpts().AssumeSaneOperatorNew &&
2193ec727ea7Spatrick             (Kind == OO_New || Kind == OO_Array_New))
2194ec727ea7Spatrick           RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2195ec727ea7Spatrick       }
2196e5dd7070Spatrick       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
2197e5dd7070Spatrick       const bool IsVirtualCall = MD && MD->isVirtual();
2198e5dd7070Spatrick       // Don't use [[noreturn]], _Noreturn or [[no_builtin]] for a call to a
2199e5dd7070Spatrick       // virtual function. These attributes are not inherited by overloads.
2200e5dd7070Spatrick       if (!(AttrOnCallSite && IsVirtualCall)) {
2201e5dd7070Spatrick         if (Fn->isNoReturn())
2202e5dd7070Spatrick           FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2203ec727ea7Spatrick         NBA = Fn->getAttr<NoBuiltinAttr>();
2204e5dd7070Spatrick       }
2205a0747c9fSpatrick       // Only place nomerge attribute on call sites, never functions. This
2206a0747c9fSpatrick       // allows it to work on indirect virtual function calls.
2207a0747c9fSpatrick       if (AttrOnCallSite && TargetDecl->hasAttr<NoMergeAttr>())
2208a0747c9fSpatrick         FuncAttrs.addAttribute(llvm::Attribute::NoMerge);
2209e5dd7070Spatrick     }
2210e5dd7070Spatrick 
2211e5dd7070Spatrick     // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
2212e5dd7070Spatrick     if (TargetDecl->hasAttr<ConstAttr>()) {
2213*7a9b00ceSrobert       FuncAttrs.addMemoryAttr(llvm::MemoryEffects::none());
2214e5dd7070Spatrick       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2215a0747c9fSpatrick       // gcc specifies that 'const' functions have greater restrictions than
2216a0747c9fSpatrick       // 'pure' functions, so they also cannot have infinite loops.
2217a0747c9fSpatrick       FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
2218e5dd7070Spatrick     } else if (TargetDecl->hasAttr<PureAttr>()) {
2219*7a9b00ceSrobert       FuncAttrs.addMemoryAttr(llvm::MemoryEffects::readOnly());
2220e5dd7070Spatrick       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2221a0747c9fSpatrick       // gcc specifies that 'pure' functions cannot have infinite loops.
2222a0747c9fSpatrick       FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
2223e5dd7070Spatrick     } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
2224*7a9b00ceSrobert       FuncAttrs.addMemoryAttr(llvm::MemoryEffects::argMemOnly());
2225e5dd7070Spatrick       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2226e5dd7070Spatrick     }
2227e5dd7070Spatrick     if (TargetDecl->hasAttr<RestrictAttr>())
2228e5dd7070Spatrick       RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2229e5dd7070Spatrick     if (TargetDecl->hasAttr<ReturnsNonNullAttr>() &&
2230e5dd7070Spatrick         !CodeGenOpts.NullPointerIsValid)
2231e5dd7070Spatrick       RetAttrs.addAttribute(llvm::Attribute::NonNull);
2232e5dd7070Spatrick     if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
2233e5dd7070Spatrick       FuncAttrs.addAttribute("no_caller_saved_registers");
2234e5dd7070Spatrick     if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>())
2235e5dd7070Spatrick       FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck);
2236a0747c9fSpatrick     if (TargetDecl->hasAttr<LeafAttr>())
2237a0747c9fSpatrick       FuncAttrs.addAttribute(llvm::Attribute::NoCallback);
2238e5dd7070Spatrick 
2239e5dd7070Spatrick     HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
2240e5dd7070Spatrick     if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
2241*7a9b00ceSrobert       std::optional<unsigned> NumElemsParam;
2242e5dd7070Spatrick       if (AllocSize->getNumElemsParam().isValid())
2243e5dd7070Spatrick         NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
2244e5dd7070Spatrick       FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(),
2245e5dd7070Spatrick                                  NumElemsParam);
2246e5dd7070Spatrick     }
2247e5dd7070Spatrick 
2248ec727ea7Spatrick     if (TargetDecl->hasAttr<OpenCLKernelAttr>()) {
2249e5dd7070Spatrick       if (getLangOpts().OpenCLVersion <= 120) {
2250e5dd7070Spatrick         // OpenCL v1.2 Work groups are always uniform
2251e5dd7070Spatrick         FuncAttrs.addAttribute("uniform-work-group-size", "true");
2252e5dd7070Spatrick       } else {
2253e5dd7070Spatrick         // OpenCL v2.0 Work groups may be whether uniform or not.
2254e5dd7070Spatrick         // '-cl-uniform-work-group-size' compile option gets a hint
2255e5dd7070Spatrick         // to the compiler that the global work-size be a multiple of
2256e5dd7070Spatrick         // the work-group size specified to clEnqueueNDRangeKernel
2257e5dd7070Spatrick         // (i.e. work groups are uniform).
2258e5dd7070Spatrick         FuncAttrs.addAttribute("uniform-work-group-size",
2259e5dd7070Spatrick                                llvm::toStringRef(CodeGenOpts.UniformWGSize));
2260e5dd7070Spatrick       }
2261e5dd7070Spatrick     }
2262ec727ea7Spatrick   }
2263e5dd7070Spatrick 
2264ec727ea7Spatrick   // Attach "no-builtins" attributes to:
2265ec727ea7Spatrick   // * call sites: both `nobuiltin` and "no-builtins" or "no-builtin-<name>".
2266ec727ea7Spatrick   // * definitions: "no-builtins" or "no-builtin-<name>" only.
2267ec727ea7Spatrick   // The attributes can come from:
2268ec727ea7Spatrick   // * LangOpts: -ffreestanding, -fno-builtin, -fno-builtin-<name>
2269ec727ea7Spatrick   // * FunctionDecl attributes: __attribute__((no_builtin(...)))
2270ec727ea7Spatrick   addNoBuiltinAttributes(FuncAttrs, getLangOpts(), NBA);
2271ec727ea7Spatrick 
2272ec727ea7Spatrick   // Collect function IR attributes based on global settiings.
2273ec727ea7Spatrick   getDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
2274ec727ea7Spatrick 
2275ec727ea7Spatrick   // Override some default IR attributes based on declaration-specific
2276ec727ea7Spatrick   // information.
2277ec727ea7Spatrick   if (TargetDecl) {
2278ec727ea7Spatrick     if (TargetDecl->hasAttr<NoSpeculativeLoadHardeningAttr>())
2279ec727ea7Spatrick       FuncAttrs.removeAttribute(llvm::Attribute::SpeculativeLoadHardening);
2280ec727ea7Spatrick     if (TargetDecl->hasAttr<SpeculativeLoadHardeningAttr>())
2281ec727ea7Spatrick       FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
2282ec727ea7Spatrick     if (TargetDecl->hasAttr<NoSplitStackAttr>())
2283ec727ea7Spatrick       FuncAttrs.removeAttribute("split-stack");
2284*7a9b00ceSrobert     if (TargetDecl->hasAttr<ZeroCallUsedRegsAttr>()) {
2285*7a9b00ceSrobert       // A function "__attribute__((...))" overrides the command-line flag.
2286*7a9b00ceSrobert       auto Kind =
2287*7a9b00ceSrobert           TargetDecl->getAttr<ZeroCallUsedRegsAttr>()->getZeroCallUsedRegs();
2288*7a9b00ceSrobert       FuncAttrs.removeAttribute("zero-call-used-regs");
2289*7a9b00ceSrobert       FuncAttrs.addAttribute(
2290*7a9b00ceSrobert           "zero-call-used-regs",
2291*7a9b00ceSrobert           ZeroCallUsedRegsAttr::ConvertZeroCallUsedRegsKindToStr(Kind));
2292*7a9b00ceSrobert     }
2293ec727ea7Spatrick 
2294ec727ea7Spatrick     // Add NonLazyBind attribute to function declarations when -fno-plt
2295ec727ea7Spatrick     // is used.
2296ec727ea7Spatrick     // FIXME: what if we just haven't processed the function definition
2297ec727ea7Spatrick     // yet, or if it's an external definition like C99 inline?
2298ec727ea7Spatrick     if (CodeGenOpts.NoPLT) {
2299ec727ea7Spatrick       if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2300ec727ea7Spatrick         if (!Fn->isDefined() && !AttrOnCallSite) {
2301ec727ea7Spatrick           FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind);
2302ec727ea7Spatrick         }
2303ec727ea7Spatrick       }
2304ec727ea7Spatrick     }
2305ec727ea7Spatrick   }
2306ec727ea7Spatrick 
2307a0747c9fSpatrick   // Add "sample-profile-suffix-elision-policy" attribute for internal linkage
2308a0747c9fSpatrick   // functions with -funique-internal-linkage-names.
2309a0747c9fSpatrick   if (TargetDecl && CodeGenOpts.UniqueInternalLinkageNames) {
2310*7a9b00ceSrobert     if (const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
2311*7a9b00ceSrobert       if (!FD->isExternallyVisible())
2312a0747c9fSpatrick         FuncAttrs.addAttribute("sample-profile-suffix-elision-policy",
2313a0747c9fSpatrick                                "selected");
2314a0747c9fSpatrick     }
2315a0747c9fSpatrick   }
2316a0747c9fSpatrick 
2317ec727ea7Spatrick   // Collect non-call-site function IR attributes from declaration-specific
2318ec727ea7Spatrick   // information.
2319e5dd7070Spatrick   if (!AttrOnCallSite) {
2320ec727ea7Spatrick     if (TargetDecl && TargetDecl->hasAttr<CmseNSEntryAttr>())
2321ec727ea7Spatrick       FuncAttrs.addAttribute("cmse_nonsecure_entry");
2322e5dd7070Spatrick 
2323ec727ea7Spatrick     // Whether tail calls are enabled.
2324ec727ea7Spatrick     auto shouldDisableTailCalls = [&] {
2325ec727ea7Spatrick       // Should this be honored in getDefaultFunctionAttributes?
2326e5dd7070Spatrick       if (CodeGenOpts.DisableTailCalls)
2327ec727ea7Spatrick         return true;
2328ec727ea7Spatrick 
2329ec727ea7Spatrick       if (!TargetDecl)
2330ec727ea7Spatrick         return false;
2331ec727ea7Spatrick 
2332e5dd7070Spatrick       if (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
2333e5dd7070Spatrick           TargetDecl->hasAttr<AnyX86InterruptAttr>())
2334ec727ea7Spatrick         return true;
2335ec727ea7Spatrick 
2336ec727ea7Spatrick       if (CodeGenOpts.NoEscapingBlockTailCalls) {
2337e5dd7070Spatrick         if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl))
2338e5dd7070Spatrick           if (!BD->doesNotEscape())
2339ec727ea7Spatrick             return true;
2340e5dd7070Spatrick       }
2341e5dd7070Spatrick 
2342ec727ea7Spatrick       return false;
2343ec727ea7Spatrick     };
2344a0747c9fSpatrick     if (shouldDisableTailCalls())
2345a0747c9fSpatrick       FuncAttrs.addAttribute("disable-tail-calls", "true");
2346e5dd7070Spatrick 
2347ec727ea7Spatrick     // CPU/feature overrides.  addDefaultFunctionDefinitionAttributes
2348ec727ea7Spatrick     // handles these separately to set them based on the global defaults.
2349ec727ea7Spatrick     GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs);
2350adae0cfdSpatrick 
2351adae0cfdSpatrick     if (CodeGenOpts.ReturnProtector)
2352adae0cfdSpatrick       FuncAttrs.addAttribute("ret-protector");
2353e5dd7070Spatrick   }
2354e5dd7070Spatrick 
2355ec727ea7Spatrick   // Collect attributes from arguments and return values.
2356e5dd7070Spatrick   ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
2357e5dd7070Spatrick 
2358e5dd7070Spatrick   QualType RetTy = FI.getReturnType();
2359e5dd7070Spatrick   const ABIArgInfo &RetAI = FI.getReturnInfo();
2360a0747c9fSpatrick   const llvm::DataLayout &DL = getDataLayout();
2361a0747c9fSpatrick 
2362a0747c9fSpatrick   // Determine if the return type could be partially undef
2363*7a9b00ceSrobert   if (CodeGenOpts.EnableNoundefAttrs &&
2364*7a9b00ceSrobert       HasStrictReturn(*this, RetTy, TargetDecl)) {
2365a0747c9fSpatrick     if (!RetTy->isVoidType() && RetAI.getKind() != ABIArgInfo::Indirect &&
2366a0747c9fSpatrick         DetermineNoUndef(RetTy, getTypes(), DL, RetAI))
2367a0747c9fSpatrick       RetAttrs.addAttribute(llvm::Attribute::NoUndef);
2368a0747c9fSpatrick   }
2369a0747c9fSpatrick 
2370e5dd7070Spatrick   switch (RetAI.getKind()) {
2371e5dd7070Spatrick   case ABIArgInfo::Extend:
2372e5dd7070Spatrick     if (RetAI.isSignExt())
2373e5dd7070Spatrick       RetAttrs.addAttribute(llvm::Attribute::SExt);
2374e5dd7070Spatrick     else
2375e5dd7070Spatrick       RetAttrs.addAttribute(llvm::Attribute::ZExt);
2376*7a9b00ceSrobert     [[fallthrough]];
2377e5dd7070Spatrick   case ABIArgInfo::Direct:
2378e5dd7070Spatrick     if (RetAI.getInReg())
2379e5dd7070Spatrick       RetAttrs.addAttribute(llvm::Attribute::InReg);
2380e5dd7070Spatrick     break;
2381e5dd7070Spatrick   case ABIArgInfo::Ignore:
2382e5dd7070Spatrick     break;
2383e5dd7070Spatrick 
2384e5dd7070Spatrick   case ABIArgInfo::InAlloca:
2385e5dd7070Spatrick   case ABIArgInfo::Indirect: {
2386e5dd7070Spatrick     // inalloca and sret disable readnone and readonly
2387*7a9b00ceSrobert     AddPotentialArgAccess();
2388e5dd7070Spatrick     break;
2389e5dd7070Spatrick   }
2390e5dd7070Spatrick 
2391e5dd7070Spatrick   case ABIArgInfo::CoerceAndExpand:
2392e5dd7070Spatrick     break;
2393e5dd7070Spatrick 
2394e5dd7070Spatrick   case ABIArgInfo::Expand:
2395a0747c9fSpatrick   case ABIArgInfo::IndirectAliased:
2396e5dd7070Spatrick     llvm_unreachable("Invalid ABI kind for return argument");
2397e5dd7070Spatrick   }
2398e5dd7070Spatrick 
2399a0747c9fSpatrick   if (!IsThunk) {
2400a0747c9fSpatrick     // FIXME: fix this properly, https://reviews.llvm.org/D100388
2401e5dd7070Spatrick     if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
2402e5dd7070Spatrick       QualType PTy = RefTy->getPointeeType();
2403e5dd7070Spatrick       if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2404ec727ea7Spatrick         RetAttrs.addDereferenceableAttr(
2405ec727ea7Spatrick             getMinimumObjectSize(PTy).getQuantity());
2406*7a9b00ceSrobert       if (getTypes().getTargetAddressSpace(PTy) == 0 &&
2407e5dd7070Spatrick           !CodeGenOpts.NullPointerIsValid)
2408e5dd7070Spatrick         RetAttrs.addAttribute(llvm::Attribute::NonNull);
2409ec727ea7Spatrick       if (PTy->isObjectType()) {
2410ec727ea7Spatrick         llvm::Align Alignment =
2411ec727ea7Spatrick             getNaturalPointeeTypeAlignment(RetTy).getAsAlign();
2412ec727ea7Spatrick         RetAttrs.addAlignmentAttr(Alignment);
2413ec727ea7Spatrick       }
2414e5dd7070Spatrick     }
2415a0747c9fSpatrick   }
2416e5dd7070Spatrick 
2417e5dd7070Spatrick   bool hasUsedSRet = false;
2418e5dd7070Spatrick   SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs());
2419e5dd7070Spatrick 
2420e5dd7070Spatrick   // Attach attributes to sret.
2421e5dd7070Spatrick   if (IRFunctionArgs.hasSRetArg()) {
2422*7a9b00ceSrobert     llvm::AttrBuilder SRETAttrs(getLLVMContext());
2423a0747c9fSpatrick     SRETAttrs.addStructRetAttr(getTypes().ConvertTypeForMem(RetTy));
2424e5dd7070Spatrick     hasUsedSRet = true;
2425e5dd7070Spatrick     if (RetAI.getInReg())
2426e5dd7070Spatrick       SRETAttrs.addAttribute(llvm::Attribute::InReg);
2427ec727ea7Spatrick     SRETAttrs.addAlignmentAttr(RetAI.getIndirectAlign().getQuantity());
2428e5dd7070Spatrick     ArgAttrs[IRFunctionArgs.getSRetArgNo()] =
2429e5dd7070Spatrick         llvm::AttributeSet::get(getLLVMContext(), SRETAttrs);
2430e5dd7070Spatrick   }
2431e5dd7070Spatrick 
2432e5dd7070Spatrick   // Attach attributes to inalloca argument.
2433e5dd7070Spatrick   if (IRFunctionArgs.hasInallocaArg()) {
2434*7a9b00ceSrobert     llvm::AttrBuilder Attrs(getLLVMContext());
2435a0747c9fSpatrick     Attrs.addInAllocaAttr(FI.getArgStruct());
2436e5dd7070Spatrick     ArgAttrs[IRFunctionArgs.getInallocaArgNo()] =
2437e5dd7070Spatrick         llvm::AttributeSet::get(getLLVMContext(), Attrs);
2438e5dd7070Spatrick   }
2439e5dd7070Spatrick 
2440a0747c9fSpatrick   // Apply `nonnull`, `dereferencable(N)` and `align N` to the `this` argument,
2441a0747c9fSpatrick   // unless this is a thunk function.
2442a0747c9fSpatrick   // FIXME: fix this properly, https://reviews.llvm.org/D100388
2443a0747c9fSpatrick   if (FI.isInstanceMethod() && !IRFunctionArgs.hasInallocaArg() &&
2444a0747c9fSpatrick       !FI.arg_begin()->type->isVoidPointerType() && !IsThunk) {
2445a0747c9fSpatrick     auto IRArgs = IRFunctionArgs.getIRArgs(0);
2446a0747c9fSpatrick 
2447a0747c9fSpatrick     assert(IRArgs.second == 1 && "Expected only a single `this` pointer.");
2448a0747c9fSpatrick 
2449*7a9b00ceSrobert     llvm::AttrBuilder Attrs(getLLVMContext());
2450a0747c9fSpatrick 
2451a0747c9fSpatrick     QualType ThisTy =
2452a0747c9fSpatrick         FI.arg_begin()->type.castAs<PointerType>()->getPointeeType();
2453a0747c9fSpatrick 
2454a0747c9fSpatrick     if (!CodeGenOpts.NullPointerIsValid &&
2455*7a9b00ceSrobert         getTypes().getTargetAddressSpace(FI.arg_begin()->type) == 0) {
2456a0747c9fSpatrick       Attrs.addAttribute(llvm::Attribute::NonNull);
2457a0747c9fSpatrick       Attrs.addDereferenceableAttr(getMinimumObjectSize(ThisTy).getQuantity());
2458a0747c9fSpatrick     } else {
2459a0747c9fSpatrick       // FIXME dereferenceable should be correct here, regardless of
2460a0747c9fSpatrick       // NullPointerIsValid. However, dereferenceable currently does not always
2461a0747c9fSpatrick       // respect NullPointerIsValid and may imply nonnull and break the program.
2462a0747c9fSpatrick       // See https://reviews.llvm.org/D66618 for discussions.
2463a0747c9fSpatrick       Attrs.addDereferenceableOrNullAttr(
2464a0747c9fSpatrick           getMinimumObjectSize(
2465a0747c9fSpatrick               FI.arg_begin()->type.castAs<PointerType>()->getPointeeType())
2466a0747c9fSpatrick               .getQuantity());
2467a0747c9fSpatrick     }
2468a0747c9fSpatrick 
2469a0747c9fSpatrick     llvm::Align Alignment =
2470a0747c9fSpatrick         getNaturalTypeAlignment(ThisTy, /*BaseInfo=*/nullptr,
2471a0747c9fSpatrick                                 /*TBAAInfo=*/nullptr, /*forPointeeType=*/true)
2472a0747c9fSpatrick             .getAsAlign();
2473a0747c9fSpatrick     Attrs.addAlignmentAttr(Alignment);
2474a0747c9fSpatrick 
2475a0747c9fSpatrick     ArgAttrs[IRArgs.first] = llvm::AttributeSet::get(getLLVMContext(), Attrs);
2476a0747c9fSpatrick   }
2477a0747c9fSpatrick 
2478e5dd7070Spatrick   unsigned ArgNo = 0;
2479e5dd7070Spatrick   for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
2480e5dd7070Spatrick                                           E = FI.arg_end();
2481e5dd7070Spatrick        I != E; ++I, ++ArgNo) {
2482e5dd7070Spatrick     QualType ParamType = I->type;
2483e5dd7070Spatrick     const ABIArgInfo &AI = I->info;
2484*7a9b00ceSrobert     llvm::AttrBuilder Attrs(getLLVMContext());
2485e5dd7070Spatrick 
2486e5dd7070Spatrick     // Add attribute for padding argument, if necessary.
2487e5dd7070Spatrick     if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
2488e5dd7070Spatrick       if (AI.getPaddingInReg()) {
2489e5dd7070Spatrick         ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2490e5dd7070Spatrick             llvm::AttributeSet::get(
2491e5dd7070Spatrick                 getLLVMContext(),
2492*7a9b00ceSrobert                 llvm::AttrBuilder(getLLVMContext()).addAttribute(llvm::Attribute::InReg));
2493e5dd7070Spatrick       }
2494e5dd7070Spatrick     }
2495e5dd7070Spatrick 
2496a0747c9fSpatrick     // Decide whether the argument we're handling could be partially undef
2497*7a9b00ceSrobert     if (CodeGenOpts.EnableNoundefAttrs &&
2498*7a9b00ceSrobert         DetermineNoUndef(ParamType, getTypes(), DL, AI)) {
2499a0747c9fSpatrick       Attrs.addAttribute(llvm::Attribute::NoUndef);
2500*7a9b00ceSrobert     }
2501a0747c9fSpatrick 
2502e5dd7070Spatrick     // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
2503e5dd7070Spatrick     // have the corresponding parameter variable.  It doesn't make
2504e5dd7070Spatrick     // sense to do it here because parameters are so messed up.
2505e5dd7070Spatrick     switch (AI.getKind()) {
2506e5dd7070Spatrick     case ABIArgInfo::Extend:
2507e5dd7070Spatrick       if (AI.isSignExt())
2508e5dd7070Spatrick         Attrs.addAttribute(llvm::Attribute::SExt);
2509e5dd7070Spatrick       else
2510e5dd7070Spatrick         Attrs.addAttribute(llvm::Attribute::ZExt);
2511*7a9b00ceSrobert       [[fallthrough]];
2512e5dd7070Spatrick     case ABIArgInfo::Direct:
2513e5dd7070Spatrick       if (ArgNo == 0 && FI.isChainCall())
2514e5dd7070Spatrick         Attrs.addAttribute(llvm::Attribute::Nest);
2515e5dd7070Spatrick       else if (AI.getInReg())
2516e5dd7070Spatrick         Attrs.addAttribute(llvm::Attribute::InReg);
2517a0747c9fSpatrick       Attrs.addStackAlignmentAttr(llvm::MaybeAlign(AI.getDirectAlign()));
2518e5dd7070Spatrick       break;
2519e5dd7070Spatrick 
2520e5dd7070Spatrick     case ABIArgInfo::Indirect: {
2521e5dd7070Spatrick       if (AI.getInReg())
2522e5dd7070Spatrick         Attrs.addAttribute(llvm::Attribute::InReg);
2523e5dd7070Spatrick 
2524e5dd7070Spatrick       if (AI.getIndirectByVal())
2525e5dd7070Spatrick         Attrs.addByValAttr(getTypes().ConvertTypeForMem(ParamType));
2526e5dd7070Spatrick 
2527a0747c9fSpatrick       auto *Decl = ParamType->getAsRecordDecl();
2528a0747c9fSpatrick       if (CodeGenOpts.PassByValueIsNoAlias && Decl &&
2529a0747c9fSpatrick           Decl->getArgPassingRestrictions() == RecordDecl::APK_CanPassInRegs)
2530a0747c9fSpatrick         // When calling the function, the pointer passed in will be the only
2531a0747c9fSpatrick         // reference to the underlying object. Mark it accordingly.
2532a0747c9fSpatrick         Attrs.addAttribute(llvm::Attribute::NoAlias);
2533a0747c9fSpatrick 
2534a0747c9fSpatrick       // TODO: We could add the byref attribute if not byval, but it would
2535a0747c9fSpatrick       // require updating many testcases.
2536a0747c9fSpatrick 
2537e5dd7070Spatrick       CharUnits Align = AI.getIndirectAlign();
2538e5dd7070Spatrick 
2539e5dd7070Spatrick       // In a byval argument, it is important that the required
2540e5dd7070Spatrick       // alignment of the type is honored, as LLVM might be creating a
2541e5dd7070Spatrick       // *new* stack object, and needs to know what alignment to give
2542e5dd7070Spatrick       // it. (Sometimes it can deduce a sensible alignment on its own,
2543e5dd7070Spatrick       // but not if clang decides it must emit a packed struct, or the
2544e5dd7070Spatrick       // user specifies increased alignment requirements.)
2545e5dd7070Spatrick       //
2546e5dd7070Spatrick       // This is different from indirect *not* byval, where the object
2547e5dd7070Spatrick       // exists already, and the align attribute is purely
2548e5dd7070Spatrick       // informative.
2549e5dd7070Spatrick       assert(!Align.isZero());
2550e5dd7070Spatrick 
2551e5dd7070Spatrick       // For now, only add this when we have a byval argument.
2552e5dd7070Spatrick       // TODO: be less lazy about updating test cases.
2553e5dd7070Spatrick       if (AI.getIndirectByVal())
2554e5dd7070Spatrick         Attrs.addAlignmentAttr(Align.getQuantity());
2555e5dd7070Spatrick 
2556e5dd7070Spatrick       // byval disables readnone and readonly.
2557*7a9b00ceSrobert       AddPotentialArgAccess();
2558a0747c9fSpatrick       break;
2559a0747c9fSpatrick     }
2560a0747c9fSpatrick     case ABIArgInfo::IndirectAliased: {
2561a0747c9fSpatrick       CharUnits Align = AI.getIndirectAlign();
2562a0747c9fSpatrick       Attrs.addByRefAttr(getTypes().ConvertTypeForMem(ParamType));
2563a0747c9fSpatrick       Attrs.addAlignmentAttr(Align.getQuantity());
2564e5dd7070Spatrick       break;
2565e5dd7070Spatrick     }
2566e5dd7070Spatrick     case ABIArgInfo::Ignore:
2567e5dd7070Spatrick     case ABIArgInfo::Expand:
2568e5dd7070Spatrick     case ABIArgInfo::CoerceAndExpand:
2569e5dd7070Spatrick       break;
2570e5dd7070Spatrick 
2571e5dd7070Spatrick     case ABIArgInfo::InAlloca:
2572e5dd7070Spatrick       // inalloca disables readnone and readonly.
2573*7a9b00ceSrobert       AddPotentialArgAccess();
2574e5dd7070Spatrick       continue;
2575e5dd7070Spatrick     }
2576e5dd7070Spatrick 
2577e5dd7070Spatrick     if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
2578e5dd7070Spatrick       QualType PTy = RefTy->getPointeeType();
2579e5dd7070Spatrick       if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2580ec727ea7Spatrick         Attrs.addDereferenceableAttr(
2581ec727ea7Spatrick             getMinimumObjectSize(PTy).getQuantity());
2582*7a9b00ceSrobert       if (getTypes().getTargetAddressSpace(PTy) == 0 &&
2583e5dd7070Spatrick           !CodeGenOpts.NullPointerIsValid)
2584e5dd7070Spatrick         Attrs.addAttribute(llvm::Attribute::NonNull);
2585ec727ea7Spatrick       if (PTy->isObjectType()) {
2586ec727ea7Spatrick         llvm::Align Alignment =
2587ec727ea7Spatrick             getNaturalPointeeTypeAlignment(ParamType).getAsAlign();
2588ec727ea7Spatrick         Attrs.addAlignmentAttr(Alignment);
2589ec727ea7Spatrick       }
2590e5dd7070Spatrick     }
2591e5dd7070Spatrick 
2592*7a9b00ceSrobert     // From OpenCL spec v3.0.10 section 6.3.5 Alignment of Types:
2593*7a9b00ceSrobert     // > For arguments to a __kernel function declared to be a pointer to a
2594*7a9b00ceSrobert     // > data type, the OpenCL compiler can assume that the pointee is always
2595*7a9b00ceSrobert     // > appropriately aligned as required by the data type.
2596*7a9b00ceSrobert     if (TargetDecl && TargetDecl->hasAttr<OpenCLKernelAttr>() &&
2597*7a9b00ceSrobert         ParamType->isPointerType()) {
2598*7a9b00ceSrobert       QualType PTy = ParamType->getPointeeType();
2599*7a9b00ceSrobert       if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2600*7a9b00ceSrobert         llvm::Align Alignment =
2601*7a9b00ceSrobert             getNaturalPointeeTypeAlignment(ParamType).getAsAlign();
2602*7a9b00ceSrobert         Attrs.addAlignmentAttr(Alignment);
2603*7a9b00ceSrobert       }
2604*7a9b00ceSrobert     }
2605*7a9b00ceSrobert 
2606e5dd7070Spatrick     switch (FI.getExtParameterInfo(ArgNo).getABI()) {
2607e5dd7070Spatrick     case ParameterABI::Ordinary:
2608e5dd7070Spatrick       break;
2609e5dd7070Spatrick 
2610e5dd7070Spatrick     case ParameterABI::SwiftIndirectResult: {
2611e5dd7070Spatrick       // Add 'sret' if we haven't already used it for something, but
2612e5dd7070Spatrick       // only if the result is void.
2613e5dd7070Spatrick       if (!hasUsedSRet && RetTy->isVoidType()) {
2614a0747c9fSpatrick         Attrs.addStructRetAttr(getTypes().ConvertTypeForMem(ParamType));
2615e5dd7070Spatrick         hasUsedSRet = true;
2616e5dd7070Spatrick       }
2617e5dd7070Spatrick 
2618e5dd7070Spatrick       // Add 'noalias' in either case.
2619e5dd7070Spatrick       Attrs.addAttribute(llvm::Attribute::NoAlias);
2620e5dd7070Spatrick 
2621e5dd7070Spatrick       // Add 'dereferenceable' and 'alignment'.
2622e5dd7070Spatrick       auto PTy = ParamType->getPointeeType();
2623e5dd7070Spatrick       if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2624e5dd7070Spatrick         auto info = getContext().getTypeInfoInChars(PTy);
2625a0747c9fSpatrick         Attrs.addDereferenceableAttr(info.Width.getQuantity());
2626a0747c9fSpatrick         Attrs.addAlignmentAttr(info.Align.getAsAlign());
2627e5dd7070Spatrick       }
2628e5dd7070Spatrick       break;
2629e5dd7070Spatrick     }
2630e5dd7070Spatrick 
2631e5dd7070Spatrick     case ParameterABI::SwiftErrorResult:
2632e5dd7070Spatrick       Attrs.addAttribute(llvm::Attribute::SwiftError);
2633e5dd7070Spatrick       break;
2634e5dd7070Spatrick 
2635e5dd7070Spatrick     case ParameterABI::SwiftContext:
2636e5dd7070Spatrick       Attrs.addAttribute(llvm::Attribute::SwiftSelf);
2637e5dd7070Spatrick       break;
2638a0747c9fSpatrick 
2639a0747c9fSpatrick     case ParameterABI::SwiftAsyncContext:
2640a0747c9fSpatrick       Attrs.addAttribute(llvm::Attribute::SwiftAsync);
2641a0747c9fSpatrick       break;
2642e5dd7070Spatrick     }
2643e5dd7070Spatrick 
2644e5dd7070Spatrick     if (FI.getExtParameterInfo(ArgNo).isNoEscape())
2645e5dd7070Spatrick       Attrs.addAttribute(llvm::Attribute::NoCapture);
2646e5dd7070Spatrick 
2647e5dd7070Spatrick     if (Attrs.hasAttributes()) {
2648e5dd7070Spatrick       unsigned FirstIRArg, NumIRArgs;
2649e5dd7070Spatrick       std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2650e5dd7070Spatrick       for (unsigned i = 0; i < NumIRArgs; i++)
2651*7a9b00ceSrobert         ArgAttrs[FirstIRArg + i] = ArgAttrs[FirstIRArg + i].addAttributes(
2652*7a9b00ceSrobert             getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), Attrs));
2653e5dd7070Spatrick     }
2654e5dd7070Spatrick   }
2655e5dd7070Spatrick   assert(ArgNo == FI.arg_size());
2656e5dd7070Spatrick 
2657e5dd7070Spatrick   AttrList = llvm::AttributeList::get(
2658e5dd7070Spatrick       getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs),
2659e5dd7070Spatrick       llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs);
2660e5dd7070Spatrick }
2661e5dd7070Spatrick 
2662e5dd7070Spatrick /// An argument came in as a promoted argument; demote it back to its
2663e5dd7070Spatrick /// declared type.
emitArgumentDemotion(CodeGenFunction & CGF,const VarDecl * var,llvm::Value * value)2664e5dd7070Spatrick static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
2665e5dd7070Spatrick                                          const VarDecl *var,
2666e5dd7070Spatrick                                          llvm::Value *value) {
2667e5dd7070Spatrick   llvm::Type *varType = CGF.ConvertType(var->getType());
2668e5dd7070Spatrick 
2669e5dd7070Spatrick   // This can happen with promotions that actually don't change the
2670e5dd7070Spatrick   // underlying type, like the enum promotions.
2671e5dd7070Spatrick   if (value->getType() == varType) return value;
2672e5dd7070Spatrick 
2673e5dd7070Spatrick   assert((varType->isIntegerTy() || varType->isFloatingPointTy())
2674e5dd7070Spatrick          && "unexpected promotion type");
2675e5dd7070Spatrick 
2676e5dd7070Spatrick   if (isa<llvm::IntegerType>(varType))
2677e5dd7070Spatrick     return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2678e5dd7070Spatrick 
2679e5dd7070Spatrick   return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2680e5dd7070Spatrick }
2681e5dd7070Spatrick 
2682e5dd7070Spatrick /// Returns the attribute (either parameter attribute, or function
2683e5dd7070Spatrick /// attribute), which declares argument ArgNo to be non-null.
getNonNullAttr(const Decl * FD,const ParmVarDecl * PVD,QualType ArgType,unsigned ArgNo)2684e5dd7070Spatrick static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2685e5dd7070Spatrick                                          QualType ArgType, unsigned ArgNo) {
2686e5dd7070Spatrick   // FIXME: __attribute__((nonnull)) can also be applied to:
2687e5dd7070Spatrick   //   - references to pointers, where the pointee is known to be
2688e5dd7070Spatrick   //     nonnull (apparently a Clang extension)
2689e5dd7070Spatrick   //   - transparent unions containing pointers
2690e5dd7070Spatrick   // In the former case, LLVM IR cannot represent the constraint. In
2691e5dd7070Spatrick   // the latter case, we have no guarantee that the transparent union
2692e5dd7070Spatrick   // is in fact passed as a pointer.
2693e5dd7070Spatrick   if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2694e5dd7070Spatrick     return nullptr;
2695e5dd7070Spatrick   // First, check attribute on parameter itself.
2696e5dd7070Spatrick   if (PVD) {
2697e5dd7070Spatrick     if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2698e5dd7070Spatrick       return ParmNNAttr;
2699e5dd7070Spatrick   }
2700e5dd7070Spatrick   // Check function attributes.
2701e5dd7070Spatrick   if (!FD)
2702e5dd7070Spatrick     return nullptr;
2703e5dd7070Spatrick   for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
2704e5dd7070Spatrick     if (NNAttr->isNonNull(ArgNo))
2705e5dd7070Spatrick       return NNAttr;
2706e5dd7070Spatrick   }
2707e5dd7070Spatrick   return nullptr;
2708e5dd7070Spatrick }
2709e5dd7070Spatrick 
2710e5dd7070Spatrick namespace {
2711e5dd7070Spatrick   struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2712e5dd7070Spatrick     Address Temp;
2713e5dd7070Spatrick     Address Arg;
CopyBackSwiftError__anon5c86009b0911::CopyBackSwiftError2714e5dd7070Spatrick     CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
Emit__anon5c86009b0911::CopyBackSwiftError2715e5dd7070Spatrick     void Emit(CodeGenFunction &CGF, Flags flags) override {
2716e5dd7070Spatrick       llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2717e5dd7070Spatrick       CGF.Builder.CreateStore(errorValue, Arg);
2718e5dd7070Spatrick     }
2719e5dd7070Spatrick   };
2720e5dd7070Spatrick }
2721e5dd7070Spatrick 
EmitFunctionProlog(const CGFunctionInfo & FI,llvm::Function * Fn,const FunctionArgList & Args)2722e5dd7070Spatrick void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
2723e5dd7070Spatrick                                          llvm::Function *Fn,
2724e5dd7070Spatrick                                          const FunctionArgList &Args) {
2725e5dd7070Spatrick   if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
2726e5dd7070Spatrick     // Naked functions don't have prologues.
2727e5dd7070Spatrick     return;
2728e5dd7070Spatrick 
2729e5dd7070Spatrick   // If this is an implicit-return-zero function, go ahead and
2730e5dd7070Spatrick   // initialize the return value.  TODO: it might be nice to have
2731e5dd7070Spatrick   // a more general mechanism for this that didn't require synthesized
2732e5dd7070Spatrick   // return statements.
2733e5dd7070Spatrick   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
2734e5dd7070Spatrick     if (FD->hasImplicitReturnZero()) {
2735e5dd7070Spatrick       QualType RetTy = FD->getReturnType().getUnqualifiedType();
2736e5dd7070Spatrick       llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
2737e5dd7070Spatrick       llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
2738e5dd7070Spatrick       Builder.CreateStore(Zero, ReturnValue);
2739e5dd7070Spatrick     }
2740e5dd7070Spatrick   }
2741e5dd7070Spatrick 
2742e5dd7070Spatrick   // FIXME: We no longer need the types from FunctionArgList; lift up and
2743e5dd7070Spatrick   // simplify.
2744e5dd7070Spatrick 
2745e5dd7070Spatrick   ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
2746ec727ea7Spatrick   assert(Fn->arg_size() == IRFunctionArgs.totalIRArgs());
2747e5dd7070Spatrick 
2748e5dd7070Spatrick   // If we're using inalloca, all the memory arguments are GEPs off of the last
2749e5dd7070Spatrick   // parameter, which is a pointer to the complete memory area.
2750e5dd7070Spatrick   Address ArgStruct = Address::invalid();
2751e5dd7070Spatrick   if (IRFunctionArgs.hasInallocaArg()) {
2752ec727ea7Spatrick     ArgStruct = Address(Fn->getArg(IRFunctionArgs.getInallocaArgNo()),
2753*7a9b00ceSrobert                         FI.getArgStruct(), FI.getArgStructAlignment());
2754e5dd7070Spatrick 
2755e5dd7070Spatrick     assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
2756e5dd7070Spatrick   }
2757e5dd7070Spatrick 
2758e5dd7070Spatrick   // Name the struct return parameter.
2759e5dd7070Spatrick   if (IRFunctionArgs.hasSRetArg()) {
2760ec727ea7Spatrick     auto AI = Fn->getArg(IRFunctionArgs.getSRetArgNo());
2761e5dd7070Spatrick     AI->setName("agg.result");
2762e5dd7070Spatrick     AI->addAttr(llvm::Attribute::NoAlias);
2763e5dd7070Spatrick   }
2764e5dd7070Spatrick 
2765e5dd7070Spatrick   // Track if we received the parameter as a pointer (indirect, byval, or
2766e5dd7070Spatrick   // inalloca).  If already have a pointer, EmitParmDecl doesn't need to copy it
2767e5dd7070Spatrick   // into a local alloca for us.
2768e5dd7070Spatrick   SmallVector<ParamValue, 16> ArgVals;
2769e5dd7070Spatrick   ArgVals.reserve(Args.size());
2770e5dd7070Spatrick 
2771e5dd7070Spatrick   // Create a pointer value for every parameter declaration.  This usually
2772e5dd7070Spatrick   // entails copying one or more LLVM IR arguments into an alloca.  Don't push
2773e5dd7070Spatrick   // any cleanups or do anything that might unwind.  We do that separately, so
2774e5dd7070Spatrick   // we can push the cleanups in the correct order for the ABI.
2775e5dd7070Spatrick   assert(FI.arg_size() == Args.size() &&
2776e5dd7070Spatrick          "Mismatch between function signature & arguments.");
2777e5dd7070Spatrick   unsigned ArgNo = 0;
2778e5dd7070Spatrick   CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
2779e5dd7070Spatrick   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
2780e5dd7070Spatrick        i != e; ++i, ++info_it, ++ArgNo) {
2781e5dd7070Spatrick     const VarDecl *Arg = *i;
2782e5dd7070Spatrick     const ABIArgInfo &ArgI = info_it->info;
2783e5dd7070Spatrick 
2784e5dd7070Spatrick     bool isPromoted =
2785e5dd7070Spatrick       isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
2786e5dd7070Spatrick     // We are converting from ABIArgInfo type to VarDecl type directly, unless
2787e5dd7070Spatrick     // the parameter is promoted. In this case we convert to
2788e5dd7070Spatrick     // CGFunctionInfo::ArgInfo type with subsequent argument demotion.
2789e5dd7070Spatrick     QualType Ty = isPromoted ? info_it->type : Arg->getType();
2790e5dd7070Spatrick     assert(hasScalarEvaluationKind(Ty) ==
2791e5dd7070Spatrick            hasScalarEvaluationKind(Arg->getType()));
2792e5dd7070Spatrick 
2793e5dd7070Spatrick     unsigned FirstIRArg, NumIRArgs;
2794e5dd7070Spatrick     std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2795e5dd7070Spatrick 
2796e5dd7070Spatrick     switch (ArgI.getKind()) {
2797e5dd7070Spatrick     case ABIArgInfo::InAlloca: {
2798e5dd7070Spatrick       assert(NumIRArgs == 0);
2799e5dd7070Spatrick       auto FieldIndex = ArgI.getInAllocaFieldIndex();
2800e5dd7070Spatrick       Address V =
2801e5dd7070Spatrick           Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName());
2802ec727ea7Spatrick       if (ArgI.getInAllocaIndirect())
2803*7a9b00ceSrobert         V = Address(Builder.CreateLoad(V), ConvertTypeForMem(Ty),
2804ec727ea7Spatrick                     getContext().getTypeAlignInChars(Ty));
2805e5dd7070Spatrick       ArgVals.push_back(ParamValue::forIndirect(V));
2806e5dd7070Spatrick       break;
2807e5dd7070Spatrick     }
2808e5dd7070Spatrick 
2809a0747c9fSpatrick     case ABIArgInfo::Indirect:
2810a0747c9fSpatrick     case ABIArgInfo::IndirectAliased: {
2811e5dd7070Spatrick       assert(NumIRArgs == 1);
2812*7a9b00ceSrobert       Address ParamAddr = Address(Fn->getArg(FirstIRArg), ConvertTypeForMem(Ty),
2813*7a9b00ceSrobert                                   ArgI.getIndirectAlign());
2814e5dd7070Spatrick 
2815e5dd7070Spatrick       if (!hasScalarEvaluationKind(Ty)) {
2816e5dd7070Spatrick         // Aggregates and complex variables are accessed by reference. All we
2817a0747c9fSpatrick         // need to do is realign the value, if requested. Also, if the address
2818a0747c9fSpatrick         // may be aliased, copy it to ensure that the parameter variable is
2819a0747c9fSpatrick         // mutable and has a unique adress, as C requires.
2820e5dd7070Spatrick         Address V = ParamAddr;
2821a0747c9fSpatrick         if (ArgI.getIndirectRealign() || ArgI.isIndirectAliased()) {
2822e5dd7070Spatrick           Address AlignedTemp = CreateMemTemp(Ty, "coerce");
2823e5dd7070Spatrick 
2824e5dd7070Spatrick           // Copy from the incoming argument pointer to the temporary with the
2825e5dd7070Spatrick           // appropriate alignment.
2826e5dd7070Spatrick           //
2827e5dd7070Spatrick           // FIXME: We should have a common utility for generating an aggregate
2828e5dd7070Spatrick           // copy.
2829e5dd7070Spatrick           CharUnits Size = getContext().getTypeSizeInChars(Ty);
2830ec727ea7Spatrick           Builder.CreateMemCpy(
2831ec727ea7Spatrick               AlignedTemp.getPointer(), AlignedTemp.getAlignment().getAsAlign(),
2832ec727ea7Spatrick               ParamAddr.getPointer(), ParamAddr.getAlignment().getAsAlign(),
2833ec727ea7Spatrick               llvm::ConstantInt::get(IntPtrTy, Size.getQuantity()));
2834e5dd7070Spatrick           V = AlignedTemp;
2835e5dd7070Spatrick         }
2836e5dd7070Spatrick         ArgVals.push_back(ParamValue::forIndirect(V));
2837e5dd7070Spatrick       } else {
2838e5dd7070Spatrick         // Load scalar value from indirect argument.
2839e5dd7070Spatrick         llvm::Value *V =
2840e5dd7070Spatrick             EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc());
2841e5dd7070Spatrick 
2842e5dd7070Spatrick         if (isPromoted)
2843e5dd7070Spatrick           V = emitArgumentDemotion(*this, Arg, V);
2844e5dd7070Spatrick         ArgVals.push_back(ParamValue::forDirect(V));
2845e5dd7070Spatrick       }
2846e5dd7070Spatrick       break;
2847e5dd7070Spatrick     }
2848e5dd7070Spatrick 
2849e5dd7070Spatrick     case ABIArgInfo::Extend:
2850e5dd7070Spatrick     case ABIArgInfo::Direct: {
2851ec727ea7Spatrick       auto AI = Fn->getArg(FirstIRArg);
2852ec727ea7Spatrick       llvm::Type *LTy = ConvertType(Arg->getType());
2853e5dd7070Spatrick 
2854ec727ea7Spatrick       // Prepare parameter attributes. So far, only attributes for pointer
2855ec727ea7Spatrick       // parameters are prepared. See
2856ec727ea7Spatrick       // http://llvm.org/docs/LangRef.html#paramattrs.
2857ec727ea7Spatrick       if (ArgI.getDirectOffset() == 0 && LTy->isPointerTy() &&
2858ec727ea7Spatrick           ArgI.getCoerceToType()->isPointerTy()) {
2859e5dd7070Spatrick         assert(NumIRArgs == 1);
2860e5dd7070Spatrick 
2861e5dd7070Spatrick         if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
2862ec727ea7Spatrick           // Set `nonnull` attribute if any.
2863e5dd7070Spatrick           if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
2864e5dd7070Spatrick                              PVD->getFunctionScopeIndex()) &&
2865e5dd7070Spatrick               !CGM.getCodeGenOpts().NullPointerIsValid)
2866e5dd7070Spatrick             AI->addAttr(llvm::Attribute::NonNull);
2867e5dd7070Spatrick 
2868e5dd7070Spatrick           QualType OTy = PVD->getOriginalType();
2869e5dd7070Spatrick           if (const auto *ArrTy =
2870e5dd7070Spatrick               getContext().getAsConstantArrayType(OTy)) {
2871e5dd7070Spatrick             // A C99 array parameter declaration with the static keyword also
2872e5dd7070Spatrick             // indicates dereferenceability, and if the size is constant we can
2873e5dd7070Spatrick             // use the dereferenceable attribute (which requires the size in
2874e5dd7070Spatrick             // bytes).
2875e5dd7070Spatrick             if (ArrTy->getSizeModifier() == ArrayType::Static) {
2876e5dd7070Spatrick               QualType ETy = ArrTy->getElementType();
2877a0747c9fSpatrick               llvm::Align Alignment =
2878a0747c9fSpatrick                   CGM.getNaturalTypeAlignment(ETy).getAsAlign();
2879*7a9b00ceSrobert               AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(Alignment));
2880e5dd7070Spatrick               uint64_t ArrSize = ArrTy->getSize().getZExtValue();
2881e5dd7070Spatrick               if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
2882e5dd7070Spatrick                   ArrSize) {
2883*7a9b00ceSrobert                 llvm::AttrBuilder Attrs(getLLVMContext());
2884e5dd7070Spatrick                 Attrs.addDereferenceableAttr(
2885ec727ea7Spatrick                     getContext().getTypeSizeInChars(ETy).getQuantity() *
2886ec727ea7Spatrick                     ArrSize);
2887e5dd7070Spatrick                 AI->addAttrs(Attrs);
2888ec727ea7Spatrick               } else if (getContext().getTargetInfo().getNullPointerValue(
2889ec727ea7Spatrick                              ETy.getAddressSpace()) == 0 &&
2890e5dd7070Spatrick                          !CGM.getCodeGenOpts().NullPointerIsValid) {
2891e5dd7070Spatrick                 AI->addAttr(llvm::Attribute::NonNull);
2892e5dd7070Spatrick               }
2893e5dd7070Spatrick             }
2894e5dd7070Spatrick           } else if (const auto *ArrTy =
2895e5dd7070Spatrick                      getContext().getAsVariableArrayType(OTy)) {
2896e5dd7070Spatrick             // For C99 VLAs with the static keyword, we don't know the size so
2897e5dd7070Spatrick             // we can't use the dereferenceable attribute, but in addrspace(0)
2898e5dd7070Spatrick             // we know that it must be nonnull.
2899a0747c9fSpatrick             if (ArrTy->getSizeModifier() == VariableArrayType::Static) {
2900a0747c9fSpatrick               QualType ETy = ArrTy->getElementType();
2901a0747c9fSpatrick               llvm::Align Alignment =
2902a0747c9fSpatrick                   CGM.getNaturalTypeAlignment(ETy).getAsAlign();
2903*7a9b00ceSrobert               AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(Alignment));
2904*7a9b00ceSrobert               if (!getTypes().getTargetAddressSpace(ETy) &&
2905e5dd7070Spatrick                   !CGM.getCodeGenOpts().NullPointerIsValid)
2906e5dd7070Spatrick                 AI->addAttr(llvm::Attribute::NonNull);
2907e5dd7070Spatrick             }
2908a0747c9fSpatrick           }
2909e5dd7070Spatrick 
2910ec727ea7Spatrick           // Set `align` attribute if any.
2911e5dd7070Spatrick           const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
2912e5dd7070Spatrick           if (!AVAttr)
2913*7a9b00ceSrobert             if (const auto *TOTy = OTy->getAs<TypedefType>())
2914e5dd7070Spatrick               AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
2915e5dd7070Spatrick           if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) {
2916e5dd7070Spatrick             // If alignment-assumption sanitizer is enabled, we do *not* add
2917e5dd7070Spatrick             // alignment attribute here, but emit normal alignment assumption,
2918e5dd7070Spatrick             // so the UBSAN check could function.
2919e5dd7070Spatrick             llvm::ConstantInt *AlignmentCI =
2920ec727ea7Spatrick                 cast<llvm::ConstantInt>(EmitScalarExpr(AVAttr->getAlignment()));
2921*7a9b00ceSrobert             uint64_t AlignmentInt =
2922ec727ea7Spatrick                 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment);
2923ec727ea7Spatrick             if (AI->getParamAlign().valueOrOne() < AlignmentInt) {
2924ec727ea7Spatrick               AI->removeAttr(llvm::Attribute::AttrKind::Alignment);
2925*7a9b00ceSrobert               AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(
2926ec727ea7Spatrick                   llvm::Align(AlignmentInt)));
2927ec727ea7Spatrick             }
2928e5dd7070Spatrick           }
2929e5dd7070Spatrick         }
2930e5dd7070Spatrick 
2931ec727ea7Spatrick         // Set 'noalias' if an argument type has the `restrict` qualifier.
2932e5dd7070Spatrick         if (Arg->getType().isRestrictQualified())
2933e5dd7070Spatrick           AI->addAttr(llvm::Attribute::NoAlias);
2934ec727ea7Spatrick       }
2935ec727ea7Spatrick 
2936ec727ea7Spatrick       // Prepare the argument value. If we have the trivial case, handle it
2937ec727ea7Spatrick       // with no muss and fuss.
2938ec727ea7Spatrick       if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
2939ec727ea7Spatrick           ArgI.getCoerceToType() == ConvertType(Ty) &&
2940ec727ea7Spatrick           ArgI.getDirectOffset() == 0) {
2941ec727ea7Spatrick         assert(NumIRArgs == 1);
2942e5dd7070Spatrick 
2943e5dd7070Spatrick         // LLVM expects swifterror parameters to be used in very restricted
2944e5dd7070Spatrick         // ways.  Copy the value into a less-restricted temporary.
2945ec727ea7Spatrick         llvm::Value *V = AI;
2946e5dd7070Spatrick         if (FI.getExtParameterInfo(ArgNo).getABI()
2947e5dd7070Spatrick               == ParameterABI::SwiftErrorResult) {
2948e5dd7070Spatrick           QualType pointeeTy = Ty->getPointeeType();
2949e5dd7070Spatrick           assert(pointeeTy->isPointerType());
2950e5dd7070Spatrick           Address temp =
2951e5dd7070Spatrick             CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
2952*7a9b00ceSrobert           Address arg(V, ConvertTypeForMem(pointeeTy),
2953*7a9b00ceSrobert                       getContext().getTypeAlignInChars(pointeeTy));
2954e5dd7070Spatrick           llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
2955e5dd7070Spatrick           Builder.CreateStore(incomingErrorValue, temp);
2956e5dd7070Spatrick           V = temp.getPointer();
2957e5dd7070Spatrick 
2958e5dd7070Spatrick           // Push a cleanup to copy the value back at the end of the function.
2959e5dd7070Spatrick           // The convention does not guarantee that the value will be written
2960e5dd7070Spatrick           // back if the function exits with an unwind exception.
2961e5dd7070Spatrick           EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
2962e5dd7070Spatrick         }
2963e5dd7070Spatrick 
2964e5dd7070Spatrick         // Ensure the argument is the correct type.
2965e5dd7070Spatrick         if (V->getType() != ArgI.getCoerceToType())
2966e5dd7070Spatrick           V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
2967e5dd7070Spatrick 
2968e5dd7070Spatrick         if (isPromoted)
2969e5dd7070Spatrick           V = emitArgumentDemotion(*this, Arg, V);
2970e5dd7070Spatrick 
2971e5dd7070Spatrick         // Because of merging of function types from multiple decls it is
2972e5dd7070Spatrick         // possible for the type of an argument to not match the corresponding
2973e5dd7070Spatrick         // type in the function type. Since we are codegening the callee
2974e5dd7070Spatrick         // in here, add a cast to the argument type.
2975e5dd7070Spatrick         llvm::Type *LTy = ConvertType(Arg->getType());
2976e5dd7070Spatrick         if (V->getType() != LTy)
2977e5dd7070Spatrick           V = Builder.CreateBitCast(V, LTy);
2978e5dd7070Spatrick 
2979e5dd7070Spatrick         ArgVals.push_back(ParamValue::forDirect(V));
2980e5dd7070Spatrick         break;
2981e5dd7070Spatrick       }
2982e5dd7070Spatrick 
2983a0747c9fSpatrick       // VLST arguments are coerced to VLATs at the function boundary for
2984a0747c9fSpatrick       // ABI consistency. If this is a VLST that was coerced to
2985a0747c9fSpatrick       // a VLAT at the function boundary and the types match up, use
2986*7a9b00ceSrobert       // llvm.vector.extract to convert back to the original VLST.
2987a0747c9fSpatrick       if (auto *VecTyTo = dyn_cast<llvm::FixedVectorType>(ConvertType(Ty))) {
2988*7a9b00ceSrobert         llvm::Value *Coerced = Fn->getArg(FirstIRArg);
2989a0747c9fSpatrick         if (auto *VecTyFrom =
2990a0747c9fSpatrick                 dyn_cast<llvm::ScalableVectorType>(Coerced->getType())) {
2991*7a9b00ceSrobert           // If we are casting a scalable 16 x i1 predicate vector to a fixed i8
2992*7a9b00ceSrobert           // vector, bitcast the source and use a vector extract.
2993*7a9b00ceSrobert           auto PredType =
2994*7a9b00ceSrobert               llvm::ScalableVectorType::get(Builder.getInt1Ty(), 16);
2995*7a9b00ceSrobert           if (VecTyFrom == PredType &&
2996*7a9b00ceSrobert               VecTyTo->getElementType() == Builder.getInt8Ty()) {
2997*7a9b00ceSrobert             VecTyFrom = llvm::ScalableVectorType::get(Builder.getInt8Ty(), 2);
2998*7a9b00ceSrobert             Coerced = Builder.CreateBitCast(Coerced, VecTyFrom);
2999*7a9b00ceSrobert           }
3000a0747c9fSpatrick           if (VecTyFrom->getElementType() == VecTyTo->getElementType()) {
3001a0747c9fSpatrick             llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty);
3002a0747c9fSpatrick 
3003a0747c9fSpatrick             assert(NumIRArgs == 1);
3004a0747c9fSpatrick             Coerced->setName(Arg->getName() + ".coerce");
3005a0747c9fSpatrick             ArgVals.push_back(ParamValue::forDirect(Builder.CreateExtractVector(
3006a0747c9fSpatrick                 VecTyTo, Coerced, Zero, "castFixedSve")));
3007a0747c9fSpatrick             break;
3008a0747c9fSpatrick           }
3009a0747c9fSpatrick         }
3010a0747c9fSpatrick       }
3011a0747c9fSpatrick 
3012e5dd7070Spatrick       Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
3013e5dd7070Spatrick                                      Arg->getName());
3014e5dd7070Spatrick 
3015e5dd7070Spatrick       // Pointer to store into.
3016e5dd7070Spatrick       Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
3017e5dd7070Spatrick 
3018e5dd7070Spatrick       // Fast-isel and the optimizer generally like scalar values better than
3019e5dd7070Spatrick       // FCAs, so we flatten them if this is safe to do for this argument.
3020e5dd7070Spatrick       llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
3021e5dd7070Spatrick       if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
3022e5dd7070Spatrick           STy->getNumElements() > 1) {
3023e5dd7070Spatrick         uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
3024e5dd7070Spatrick         llvm::Type *DstTy = Ptr.getElementType();
3025e5dd7070Spatrick         uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
3026e5dd7070Spatrick 
3027e5dd7070Spatrick         Address AddrToStoreInto = Address::invalid();
3028e5dd7070Spatrick         if (SrcSize <= DstSize) {
3029e5dd7070Spatrick           AddrToStoreInto = Builder.CreateElementBitCast(Ptr, STy);
3030e5dd7070Spatrick         } else {
3031e5dd7070Spatrick           AddrToStoreInto =
3032e5dd7070Spatrick             CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
3033e5dd7070Spatrick         }
3034e5dd7070Spatrick 
3035e5dd7070Spatrick         assert(STy->getNumElements() == NumIRArgs);
3036e5dd7070Spatrick         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3037ec727ea7Spatrick           auto AI = Fn->getArg(FirstIRArg + i);
3038e5dd7070Spatrick           AI->setName(Arg->getName() + ".coerce" + Twine(i));
3039e5dd7070Spatrick           Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i);
3040e5dd7070Spatrick           Builder.CreateStore(AI, EltPtr);
3041e5dd7070Spatrick         }
3042e5dd7070Spatrick 
3043e5dd7070Spatrick         if (SrcSize > DstSize) {
3044e5dd7070Spatrick           Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
3045e5dd7070Spatrick         }
3046e5dd7070Spatrick 
3047e5dd7070Spatrick       } else {
3048e5dd7070Spatrick         // Simple case, just do a coerced store of the argument into the alloca.
3049e5dd7070Spatrick         assert(NumIRArgs == 1);
3050ec727ea7Spatrick         auto AI = Fn->getArg(FirstIRArg);
3051e5dd7070Spatrick         AI->setName(Arg->getName() + ".coerce");
3052e5dd7070Spatrick         CreateCoercedStore(AI, Ptr, /*DstIsVolatile=*/false, *this);
3053e5dd7070Spatrick       }
3054e5dd7070Spatrick 
3055e5dd7070Spatrick       // Match to what EmitParmDecl is expecting for this type.
3056e5dd7070Spatrick       if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
3057e5dd7070Spatrick         llvm::Value *V =
3058e5dd7070Spatrick             EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc());
3059e5dd7070Spatrick         if (isPromoted)
3060e5dd7070Spatrick           V = emitArgumentDemotion(*this, Arg, V);
3061e5dd7070Spatrick         ArgVals.push_back(ParamValue::forDirect(V));
3062e5dd7070Spatrick       } else {
3063e5dd7070Spatrick         ArgVals.push_back(ParamValue::forIndirect(Alloca));
3064e5dd7070Spatrick       }
3065e5dd7070Spatrick       break;
3066e5dd7070Spatrick     }
3067e5dd7070Spatrick 
3068e5dd7070Spatrick     case ABIArgInfo::CoerceAndExpand: {
3069e5dd7070Spatrick       // Reconstruct into a temporary.
3070e5dd7070Spatrick       Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
3071e5dd7070Spatrick       ArgVals.push_back(ParamValue::forIndirect(alloca));
3072e5dd7070Spatrick 
3073e5dd7070Spatrick       auto coercionType = ArgI.getCoerceAndExpandType();
3074e5dd7070Spatrick       alloca = Builder.CreateElementBitCast(alloca, coercionType);
3075e5dd7070Spatrick 
3076e5dd7070Spatrick       unsigned argIndex = FirstIRArg;
3077e5dd7070Spatrick       for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3078e5dd7070Spatrick         llvm::Type *eltType = coercionType->getElementType(i);
3079e5dd7070Spatrick         if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
3080e5dd7070Spatrick           continue;
3081e5dd7070Spatrick 
3082e5dd7070Spatrick         auto eltAddr = Builder.CreateStructGEP(alloca, i);
3083ec727ea7Spatrick         auto elt = Fn->getArg(argIndex++);
3084e5dd7070Spatrick         Builder.CreateStore(elt, eltAddr);
3085e5dd7070Spatrick       }
3086e5dd7070Spatrick       assert(argIndex == FirstIRArg + NumIRArgs);
3087e5dd7070Spatrick       break;
3088e5dd7070Spatrick     }
3089e5dd7070Spatrick 
3090e5dd7070Spatrick     case ABIArgInfo::Expand: {
3091e5dd7070Spatrick       // If this structure was expanded into multiple arguments then
3092e5dd7070Spatrick       // we need to create a temporary and reconstruct it from the
3093e5dd7070Spatrick       // arguments.
3094e5dd7070Spatrick       Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
3095e5dd7070Spatrick       LValue LV = MakeAddrLValue(Alloca, Ty);
3096e5dd7070Spatrick       ArgVals.push_back(ParamValue::forIndirect(Alloca));
3097e5dd7070Spatrick 
3098ec727ea7Spatrick       auto FnArgIter = Fn->arg_begin() + FirstIRArg;
3099e5dd7070Spatrick       ExpandTypeFromArgs(Ty, LV, FnArgIter);
3100ec727ea7Spatrick       assert(FnArgIter == Fn->arg_begin() + FirstIRArg + NumIRArgs);
3101e5dd7070Spatrick       for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
3102ec727ea7Spatrick         auto AI = Fn->getArg(FirstIRArg + i);
3103e5dd7070Spatrick         AI->setName(Arg->getName() + "." + Twine(i));
3104e5dd7070Spatrick       }
3105e5dd7070Spatrick       break;
3106e5dd7070Spatrick     }
3107e5dd7070Spatrick 
3108e5dd7070Spatrick     case ABIArgInfo::Ignore:
3109e5dd7070Spatrick       assert(NumIRArgs == 0);
3110e5dd7070Spatrick       // Initialize the local variable appropriately.
3111e5dd7070Spatrick       if (!hasScalarEvaluationKind(Ty)) {
3112e5dd7070Spatrick         ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
3113e5dd7070Spatrick       } else {
3114e5dd7070Spatrick         llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
3115e5dd7070Spatrick         ArgVals.push_back(ParamValue::forDirect(U));
3116e5dd7070Spatrick       }
3117e5dd7070Spatrick       break;
3118e5dd7070Spatrick     }
3119e5dd7070Spatrick   }
3120e5dd7070Spatrick 
3121e5dd7070Spatrick   if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3122e5dd7070Spatrick     for (int I = Args.size() - 1; I >= 0; --I)
3123e5dd7070Spatrick       EmitParmDecl(*Args[I], ArgVals[I], I + 1);
3124e5dd7070Spatrick   } else {
3125e5dd7070Spatrick     for (unsigned I = 0, E = Args.size(); I != E; ++I)
3126e5dd7070Spatrick       EmitParmDecl(*Args[I], ArgVals[I], I + 1);
3127e5dd7070Spatrick   }
3128e5dd7070Spatrick }
3129e5dd7070Spatrick 
eraseUnusedBitCasts(llvm::Instruction * insn)3130e5dd7070Spatrick static void eraseUnusedBitCasts(llvm::Instruction *insn) {
3131e5dd7070Spatrick   while (insn->use_empty()) {
3132e5dd7070Spatrick     llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
3133e5dd7070Spatrick     if (!bitcast) return;
3134e5dd7070Spatrick 
3135e5dd7070Spatrick     // This is "safe" because we would have used a ConstantExpr otherwise.
3136e5dd7070Spatrick     insn = cast<llvm::Instruction>(bitcast->getOperand(0));
3137e5dd7070Spatrick     bitcast->eraseFromParent();
3138e5dd7070Spatrick   }
3139e5dd7070Spatrick }
3140e5dd7070Spatrick 
3141e5dd7070Spatrick /// Try to emit a fused autorelease of a return result.
tryEmitFusedAutoreleaseOfResult(CodeGenFunction & CGF,llvm::Value * result)3142e5dd7070Spatrick static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
3143e5dd7070Spatrick                                                     llvm::Value *result) {
3144e5dd7070Spatrick   // We must be immediately followed the cast.
3145e5dd7070Spatrick   llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
3146e5dd7070Spatrick   if (BB->empty()) return nullptr;
3147e5dd7070Spatrick   if (&BB->back() != result) return nullptr;
3148e5dd7070Spatrick 
3149e5dd7070Spatrick   llvm::Type *resultType = result->getType();
3150e5dd7070Spatrick 
3151e5dd7070Spatrick   // result is in a BasicBlock and is therefore an Instruction.
3152e5dd7070Spatrick   llvm::Instruction *generator = cast<llvm::Instruction>(result);
3153e5dd7070Spatrick 
3154e5dd7070Spatrick   SmallVector<llvm::Instruction *, 4> InstsToKill;
3155e5dd7070Spatrick 
3156e5dd7070Spatrick   // Look for:
3157e5dd7070Spatrick   //  %generator = bitcast %type1* %generator2 to %type2*
3158e5dd7070Spatrick   while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
3159e5dd7070Spatrick     // We would have emitted this as a constant if the operand weren't
3160e5dd7070Spatrick     // an Instruction.
3161e5dd7070Spatrick     generator = cast<llvm::Instruction>(bitcast->getOperand(0));
3162e5dd7070Spatrick 
3163e5dd7070Spatrick     // Require the generator to be immediately followed by the cast.
3164e5dd7070Spatrick     if (generator->getNextNode() != bitcast)
3165e5dd7070Spatrick       return nullptr;
3166e5dd7070Spatrick 
3167e5dd7070Spatrick     InstsToKill.push_back(bitcast);
3168e5dd7070Spatrick   }
3169e5dd7070Spatrick 
3170e5dd7070Spatrick   // Look for:
3171e5dd7070Spatrick   //   %generator = call i8* @objc_retain(i8* %originalResult)
3172e5dd7070Spatrick   // or
3173e5dd7070Spatrick   //   %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
3174e5dd7070Spatrick   llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
3175e5dd7070Spatrick   if (!call) return nullptr;
3176e5dd7070Spatrick 
3177e5dd7070Spatrick   bool doRetainAutorelease;
3178e5dd7070Spatrick 
3179ec727ea7Spatrick   if (call->getCalledOperand() == CGF.CGM.getObjCEntrypoints().objc_retain) {
3180e5dd7070Spatrick     doRetainAutorelease = true;
3181ec727ea7Spatrick   } else if (call->getCalledOperand() ==
3182ec727ea7Spatrick              CGF.CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue) {
3183e5dd7070Spatrick     doRetainAutorelease = false;
3184e5dd7070Spatrick 
3185e5dd7070Spatrick     // If we emitted an assembly marker for this call (and the
3186e5dd7070Spatrick     // ARCEntrypoints field should have been set if so), go looking
3187e5dd7070Spatrick     // for that call.  If we can't find it, we can't do this
3188e5dd7070Spatrick     // optimization.  But it should always be the immediately previous
3189e5dd7070Spatrick     // instruction, unless we needed bitcasts around the call.
3190e5dd7070Spatrick     if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
3191e5dd7070Spatrick       llvm::Instruction *prev = call->getPrevNode();
3192e5dd7070Spatrick       assert(prev);
3193e5dd7070Spatrick       if (isa<llvm::BitCastInst>(prev)) {
3194e5dd7070Spatrick         prev = prev->getPrevNode();
3195e5dd7070Spatrick         assert(prev);
3196e5dd7070Spatrick       }
3197e5dd7070Spatrick       assert(isa<llvm::CallInst>(prev));
3198ec727ea7Spatrick       assert(cast<llvm::CallInst>(prev)->getCalledOperand() ==
3199e5dd7070Spatrick              CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
3200e5dd7070Spatrick       InstsToKill.push_back(prev);
3201e5dd7070Spatrick     }
3202e5dd7070Spatrick   } else {
3203e5dd7070Spatrick     return nullptr;
3204e5dd7070Spatrick   }
3205e5dd7070Spatrick 
3206e5dd7070Spatrick   result = call->getArgOperand(0);
3207e5dd7070Spatrick   InstsToKill.push_back(call);
3208e5dd7070Spatrick 
3209e5dd7070Spatrick   // Keep killing bitcasts, for sanity.  Note that we no longer care
3210e5dd7070Spatrick   // about precise ordering as long as there's exactly one use.
3211e5dd7070Spatrick   while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
3212e5dd7070Spatrick     if (!bitcast->hasOneUse()) break;
3213e5dd7070Spatrick     InstsToKill.push_back(bitcast);
3214e5dd7070Spatrick     result = bitcast->getOperand(0);
3215e5dd7070Spatrick   }
3216e5dd7070Spatrick 
3217e5dd7070Spatrick   // Delete all the unnecessary instructions, from latest to earliest.
3218e5dd7070Spatrick   for (auto *I : InstsToKill)
3219e5dd7070Spatrick     I->eraseFromParent();
3220e5dd7070Spatrick 
3221e5dd7070Spatrick   // Do the fused retain/autorelease if we were asked to.
3222e5dd7070Spatrick   if (doRetainAutorelease)
3223e5dd7070Spatrick     result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
3224e5dd7070Spatrick 
3225e5dd7070Spatrick   // Cast back to the result type.
3226e5dd7070Spatrick   return CGF.Builder.CreateBitCast(result, resultType);
3227e5dd7070Spatrick }
3228e5dd7070Spatrick 
3229e5dd7070Spatrick /// If this is a +1 of the value of an immutable 'self', remove it.
tryRemoveRetainOfSelf(CodeGenFunction & CGF,llvm::Value * result)3230e5dd7070Spatrick static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
3231e5dd7070Spatrick                                           llvm::Value *result) {
3232e5dd7070Spatrick   // This is only applicable to a method with an immutable 'self'.
3233e5dd7070Spatrick   const ObjCMethodDecl *method =
3234e5dd7070Spatrick     dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
3235e5dd7070Spatrick   if (!method) return nullptr;
3236e5dd7070Spatrick   const VarDecl *self = method->getSelfDecl();
3237e5dd7070Spatrick   if (!self->getType().isConstQualified()) return nullptr;
3238e5dd7070Spatrick 
3239e5dd7070Spatrick   // Look for a retain call.
3240e5dd7070Spatrick   llvm::CallInst *retainCall =
3241e5dd7070Spatrick     dyn_cast<llvm::CallInst>(result->stripPointerCasts());
3242ec727ea7Spatrick   if (!retainCall || retainCall->getCalledOperand() !=
3243ec727ea7Spatrick                          CGF.CGM.getObjCEntrypoints().objc_retain)
3244e5dd7070Spatrick     return nullptr;
3245e5dd7070Spatrick 
3246e5dd7070Spatrick   // Look for an ordinary load of 'self'.
3247e5dd7070Spatrick   llvm::Value *retainedValue = retainCall->getArgOperand(0);
3248e5dd7070Spatrick   llvm::LoadInst *load =
3249e5dd7070Spatrick     dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
3250e5dd7070Spatrick   if (!load || load->isAtomic() || load->isVolatile() ||
3251e5dd7070Spatrick       load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
3252e5dd7070Spatrick     return nullptr;
3253e5dd7070Spatrick 
3254e5dd7070Spatrick   // Okay!  Burn it all down.  This relies for correctness on the
3255e5dd7070Spatrick   // assumption that the retain is emitted as part of the return and
3256e5dd7070Spatrick   // that thereafter everything is used "linearly".
3257e5dd7070Spatrick   llvm::Type *resultType = result->getType();
3258e5dd7070Spatrick   eraseUnusedBitCasts(cast<llvm::Instruction>(result));
3259e5dd7070Spatrick   assert(retainCall->use_empty());
3260e5dd7070Spatrick   retainCall->eraseFromParent();
3261e5dd7070Spatrick   eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
3262e5dd7070Spatrick 
3263e5dd7070Spatrick   return CGF.Builder.CreateBitCast(load, resultType);
3264e5dd7070Spatrick }
3265e5dd7070Spatrick 
3266e5dd7070Spatrick /// Emit an ARC autorelease of the result of a function.
3267e5dd7070Spatrick ///
3268e5dd7070Spatrick /// \return the value to actually return from the function
emitAutoreleaseOfResult(CodeGenFunction & CGF,llvm::Value * result)3269e5dd7070Spatrick static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
3270e5dd7070Spatrick                                             llvm::Value *result) {
3271e5dd7070Spatrick   // If we're returning 'self', kill the initial retain.  This is a
3272e5dd7070Spatrick   // heuristic attempt to "encourage correctness" in the really unfortunate
3273e5dd7070Spatrick   // case where we have a return of self during a dealloc and we desperately
3274e5dd7070Spatrick   // need to avoid the possible autorelease.
3275e5dd7070Spatrick   if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
3276e5dd7070Spatrick     return self;
3277e5dd7070Spatrick 
3278e5dd7070Spatrick   // At -O0, try to emit a fused retain/autorelease.
3279e5dd7070Spatrick   if (CGF.shouldUseFusedARCCalls())
3280e5dd7070Spatrick     if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
3281e5dd7070Spatrick       return fused;
3282e5dd7070Spatrick 
3283e5dd7070Spatrick   return CGF.EmitARCAutoreleaseReturnValue(result);
3284e5dd7070Spatrick }
3285e5dd7070Spatrick 
3286e5dd7070Spatrick /// Heuristically search for a dominating store to the return-value slot.
findDominatingStoreToReturnValue(CodeGenFunction & CGF)3287e5dd7070Spatrick static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
3288e5dd7070Spatrick   // Check if a User is a store which pointerOperand is the ReturnValue.
3289e5dd7070Spatrick   // We are looking for stores to the ReturnValue, not for stores of the
3290e5dd7070Spatrick   // ReturnValue to some other location.
3291e5dd7070Spatrick   auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
3292e5dd7070Spatrick     auto *SI = dyn_cast<llvm::StoreInst>(U);
3293*7a9b00ceSrobert     if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer() ||
3294*7a9b00ceSrobert         SI->getValueOperand()->getType() != CGF.ReturnValue.getElementType())
3295e5dd7070Spatrick       return nullptr;
3296e5dd7070Spatrick     // These aren't actually possible for non-coerced returns, and we
3297e5dd7070Spatrick     // only care about non-coerced returns on this code path.
3298e5dd7070Spatrick     assert(!SI->isAtomic() && !SI->isVolatile());
3299e5dd7070Spatrick     return SI;
3300e5dd7070Spatrick   };
3301e5dd7070Spatrick   // If there are multiple uses of the return-value slot, just check
3302e5dd7070Spatrick   // for something immediately preceding the IP.  Sometimes this can
3303e5dd7070Spatrick   // happen with how we generate implicit-returns; it can also happen
3304e5dd7070Spatrick   // with noreturn cleanups.
3305e5dd7070Spatrick   if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
3306e5dd7070Spatrick     llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
3307e5dd7070Spatrick     if (IP->empty()) return nullptr;
3308e5dd7070Spatrick 
3309*7a9b00ceSrobert     // Look at directly preceding instruction, skipping bitcasts and lifetime
3310*7a9b00ceSrobert     // markers.
3311*7a9b00ceSrobert     for (llvm::Instruction &I : make_range(IP->rbegin(), IP->rend())) {
3312*7a9b00ceSrobert       if (isa<llvm::BitCastInst>(&I))
3313e5dd7070Spatrick         continue;
3314*7a9b00ceSrobert       if (auto *II = dyn_cast<llvm::IntrinsicInst>(&I))
3315*7a9b00ceSrobert         if (II->getIntrinsicID() == llvm::Intrinsic::lifetime_end)
3316*7a9b00ceSrobert           continue;
3317e5dd7070Spatrick 
3318*7a9b00ceSrobert       return GetStoreIfValid(&I);
3319*7a9b00ceSrobert     }
3320*7a9b00ceSrobert     return nullptr;
3321e5dd7070Spatrick   }
3322e5dd7070Spatrick 
3323e5dd7070Spatrick   llvm::StoreInst *store =
3324e5dd7070Spatrick       GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
3325e5dd7070Spatrick   if (!store) return nullptr;
3326e5dd7070Spatrick 
3327e5dd7070Spatrick   // Now do a first-and-dirty dominance check: just walk up the
3328e5dd7070Spatrick   // single-predecessors chain from the current insertion point.
3329e5dd7070Spatrick   llvm::BasicBlock *StoreBB = store->getParent();
3330e5dd7070Spatrick   llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
3331e5dd7070Spatrick   while (IP != StoreBB) {
3332e5dd7070Spatrick     if (!(IP = IP->getSinglePredecessor()))
3333e5dd7070Spatrick       return nullptr;
3334e5dd7070Spatrick   }
3335e5dd7070Spatrick 
3336e5dd7070Spatrick   // Okay, the store's basic block dominates the insertion point; we
3337e5dd7070Spatrick   // can do our thing.
3338e5dd7070Spatrick   return store;
3339e5dd7070Spatrick }
3340e5dd7070Spatrick 
3341ec727ea7Spatrick // Helper functions for EmitCMSEClearRecord
3342ec727ea7Spatrick 
3343ec727ea7Spatrick // Set the bits corresponding to a field having width `BitWidth` and located at
3344ec727ea7Spatrick // offset `BitOffset` (from the least significant bit) within a storage unit of
3345ec727ea7Spatrick // `Bits.size()` bytes. Each element of `Bits` corresponds to one target byte.
3346ec727ea7Spatrick // Use little-endian layout, i.e.`Bits[0]` is the LSB.
setBitRange(SmallVectorImpl<uint64_t> & Bits,int BitOffset,int BitWidth,int CharWidth)3347ec727ea7Spatrick static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int BitOffset,
3348ec727ea7Spatrick                         int BitWidth, int CharWidth) {
3349ec727ea7Spatrick   assert(CharWidth <= 64);
3350ec727ea7Spatrick   assert(static_cast<unsigned>(BitWidth) <= Bits.size() * CharWidth);
3351ec727ea7Spatrick 
3352ec727ea7Spatrick   int Pos = 0;
3353ec727ea7Spatrick   if (BitOffset >= CharWidth) {
3354ec727ea7Spatrick     Pos += BitOffset / CharWidth;
3355ec727ea7Spatrick     BitOffset = BitOffset % CharWidth;
3356ec727ea7Spatrick   }
3357ec727ea7Spatrick 
3358ec727ea7Spatrick   const uint64_t Used = (uint64_t(1) << CharWidth) - 1;
3359ec727ea7Spatrick   if (BitOffset + BitWidth >= CharWidth) {
3360ec727ea7Spatrick     Bits[Pos++] |= (Used << BitOffset) & Used;
3361ec727ea7Spatrick     BitWidth -= CharWidth - BitOffset;
3362ec727ea7Spatrick     BitOffset = 0;
3363ec727ea7Spatrick   }
3364ec727ea7Spatrick 
3365ec727ea7Spatrick   while (BitWidth >= CharWidth) {
3366ec727ea7Spatrick     Bits[Pos++] = Used;
3367ec727ea7Spatrick     BitWidth -= CharWidth;
3368ec727ea7Spatrick   }
3369ec727ea7Spatrick 
3370ec727ea7Spatrick   if (BitWidth > 0)
3371ec727ea7Spatrick     Bits[Pos++] |= (Used >> (CharWidth - BitWidth)) << BitOffset;
3372ec727ea7Spatrick }
3373ec727ea7Spatrick 
3374ec727ea7Spatrick // Set the bits corresponding to a field having width `BitWidth` and located at
3375ec727ea7Spatrick // offset `BitOffset` (from the least significant bit) within a storage unit of
3376ec727ea7Spatrick // `StorageSize` bytes, located at `StorageOffset` in `Bits`. Each element of
3377ec727ea7Spatrick // `Bits` corresponds to one target byte. Use target endian layout.
setBitRange(SmallVectorImpl<uint64_t> & Bits,int StorageOffset,int StorageSize,int BitOffset,int BitWidth,int CharWidth,bool BigEndian)3378ec727ea7Spatrick static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int StorageOffset,
3379ec727ea7Spatrick                         int StorageSize, int BitOffset, int BitWidth,
3380ec727ea7Spatrick                         int CharWidth, bool BigEndian) {
3381ec727ea7Spatrick 
3382ec727ea7Spatrick   SmallVector<uint64_t, 8> TmpBits(StorageSize);
3383ec727ea7Spatrick   setBitRange(TmpBits, BitOffset, BitWidth, CharWidth);
3384ec727ea7Spatrick 
3385ec727ea7Spatrick   if (BigEndian)
3386ec727ea7Spatrick     std::reverse(TmpBits.begin(), TmpBits.end());
3387ec727ea7Spatrick 
3388ec727ea7Spatrick   for (uint64_t V : TmpBits)
3389ec727ea7Spatrick     Bits[StorageOffset++] |= V;
3390ec727ea7Spatrick }
3391ec727ea7Spatrick 
3392ec727ea7Spatrick static void setUsedBits(CodeGenModule &, QualType, int,
3393ec727ea7Spatrick                         SmallVectorImpl<uint64_t> &);
3394ec727ea7Spatrick 
3395ec727ea7Spatrick // Set the bits in `Bits`, which correspond to the value representations of
3396ec727ea7Spatrick // the actual members of the record type `RTy`. Note that this function does
3397ec727ea7Spatrick // not handle base classes, virtual tables, etc, since they cannot happen in
3398ec727ea7Spatrick // CMSE function arguments or return. The bit mask corresponds to the target
3399ec727ea7Spatrick // memory layout, i.e. it's endian dependent.
setUsedBits(CodeGenModule & CGM,const RecordType * RTy,int Offset,SmallVectorImpl<uint64_t> & Bits)3400ec727ea7Spatrick static void setUsedBits(CodeGenModule &CGM, const RecordType *RTy, int Offset,
3401ec727ea7Spatrick                         SmallVectorImpl<uint64_t> &Bits) {
3402ec727ea7Spatrick   ASTContext &Context = CGM.getContext();
3403ec727ea7Spatrick   int CharWidth = Context.getCharWidth();
3404ec727ea7Spatrick   const RecordDecl *RD = RTy->getDecl()->getDefinition();
3405ec727ea7Spatrick   const ASTRecordLayout &ASTLayout = Context.getASTRecordLayout(RD);
3406ec727ea7Spatrick   const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(RD);
3407ec727ea7Spatrick 
3408ec727ea7Spatrick   int Idx = 0;
3409ec727ea7Spatrick   for (auto I = RD->field_begin(), E = RD->field_end(); I != E; ++I, ++Idx) {
3410ec727ea7Spatrick     const FieldDecl *F = *I;
3411ec727ea7Spatrick 
3412ec727ea7Spatrick     if (F->isUnnamedBitfield() || F->isZeroLengthBitField(Context) ||
3413ec727ea7Spatrick         F->getType()->isIncompleteArrayType())
3414ec727ea7Spatrick       continue;
3415ec727ea7Spatrick 
3416ec727ea7Spatrick     if (F->isBitField()) {
3417ec727ea7Spatrick       const CGBitFieldInfo &BFI = Layout.getBitFieldInfo(F);
3418ec727ea7Spatrick       setBitRange(Bits, Offset + BFI.StorageOffset.getQuantity(),
3419ec727ea7Spatrick                   BFI.StorageSize / CharWidth, BFI.Offset,
3420ec727ea7Spatrick                   BFI.Size, CharWidth,
3421ec727ea7Spatrick                   CGM.getDataLayout().isBigEndian());
3422ec727ea7Spatrick       continue;
3423ec727ea7Spatrick     }
3424ec727ea7Spatrick 
3425ec727ea7Spatrick     setUsedBits(CGM, F->getType(),
3426ec727ea7Spatrick                 Offset + ASTLayout.getFieldOffset(Idx) / CharWidth, Bits);
3427ec727ea7Spatrick   }
3428ec727ea7Spatrick }
3429ec727ea7Spatrick 
3430ec727ea7Spatrick // Set the bits in `Bits`, which correspond to the value representations of
3431ec727ea7Spatrick // the elements of an array type `ATy`.
setUsedBits(CodeGenModule & CGM,const ConstantArrayType * ATy,int Offset,SmallVectorImpl<uint64_t> & Bits)3432ec727ea7Spatrick static void setUsedBits(CodeGenModule &CGM, const ConstantArrayType *ATy,
3433ec727ea7Spatrick                         int Offset, SmallVectorImpl<uint64_t> &Bits) {
3434ec727ea7Spatrick   const ASTContext &Context = CGM.getContext();
3435ec727ea7Spatrick 
3436ec727ea7Spatrick   QualType ETy = Context.getBaseElementType(ATy);
3437ec727ea7Spatrick   int Size = Context.getTypeSizeInChars(ETy).getQuantity();
3438ec727ea7Spatrick   SmallVector<uint64_t, 4> TmpBits(Size);
3439ec727ea7Spatrick   setUsedBits(CGM, ETy, 0, TmpBits);
3440ec727ea7Spatrick 
3441ec727ea7Spatrick   for (int I = 0, N = Context.getConstantArrayElementCount(ATy); I < N; ++I) {
3442ec727ea7Spatrick     auto Src = TmpBits.begin();
3443ec727ea7Spatrick     auto Dst = Bits.begin() + Offset + I * Size;
3444ec727ea7Spatrick     for (int J = 0; J < Size; ++J)
3445ec727ea7Spatrick       *Dst++ |= *Src++;
3446ec727ea7Spatrick   }
3447ec727ea7Spatrick }
3448ec727ea7Spatrick 
3449ec727ea7Spatrick // Set the bits in `Bits`, which correspond to the value representations of
3450ec727ea7Spatrick // the type `QTy`.
setUsedBits(CodeGenModule & CGM,QualType QTy,int Offset,SmallVectorImpl<uint64_t> & Bits)3451ec727ea7Spatrick static void setUsedBits(CodeGenModule &CGM, QualType QTy, int Offset,
3452ec727ea7Spatrick                         SmallVectorImpl<uint64_t> &Bits) {
3453ec727ea7Spatrick   if (const auto *RTy = QTy->getAs<RecordType>())
3454ec727ea7Spatrick     return setUsedBits(CGM, RTy, Offset, Bits);
3455ec727ea7Spatrick 
3456ec727ea7Spatrick   ASTContext &Context = CGM.getContext();
3457ec727ea7Spatrick   if (const auto *ATy = Context.getAsConstantArrayType(QTy))
3458ec727ea7Spatrick     return setUsedBits(CGM, ATy, Offset, Bits);
3459ec727ea7Spatrick 
3460ec727ea7Spatrick   int Size = Context.getTypeSizeInChars(QTy).getQuantity();
3461ec727ea7Spatrick   if (Size <= 0)
3462ec727ea7Spatrick     return;
3463ec727ea7Spatrick 
3464ec727ea7Spatrick   std::fill_n(Bits.begin() + Offset, Size,
3465ec727ea7Spatrick               (uint64_t(1) << Context.getCharWidth()) - 1);
3466ec727ea7Spatrick }
3467ec727ea7Spatrick 
buildMultiCharMask(const SmallVectorImpl<uint64_t> & Bits,int Pos,int Size,int CharWidth,bool BigEndian)3468ec727ea7Spatrick static uint64_t buildMultiCharMask(const SmallVectorImpl<uint64_t> &Bits,
3469ec727ea7Spatrick                                    int Pos, int Size, int CharWidth,
3470ec727ea7Spatrick                                    bool BigEndian) {
3471ec727ea7Spatrick   assert(Size > 0);
3472ec727ea7Spatrick   uint64_t Mask = 0;
3473ec727ea7Spatrick   if (BigEndian) {
3474ec727ea7Spatrick     for (auto P = Bits.begin() + Pos, E = Bits.begin() + Pos + Size; P != E;
3475ec727ea7Spatrick          ++P)
3476ec727ea7Spatrick       Mask = (Mask << CharWidth) | *P;
3477ec727ea7Spatrick   } else {
3478ec727ea7Spatrick     auto P = Bits.begin() + Pos + Size, End = Bits.begin() + Pos;
3479ec727ea7Spatrick     do
3480ec727ea7Spatrick       Mask = (Mask << CharWidth) | *--P;
3481ec727ea7Spatrick     while (P != End);
3482ec727ea7Spatrick   }
3483ec727ea7Spatrick   return Mask;
3484ec727ea7Spatrick }
3485ec727ea7Spatrick 
3486ec727ea7Spatrick // Emit code to clear the bits in a record, which aren't a part of any user
3487ec727ea7Spatrick // declared member, when the record is a function return.
EmitCMSEClearRecord(llvm::Value * Src,llvm::IntegerType * ITy,QualType QTy)3488ec727ea7Spatrick llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3489ec727ea7Spatrick                                                   llvm::IntegerType *ITy,
3490ec727ea7Spatrick                                                   QualType QTy) {
3491ec727ea7Spatrick   assert(Src->getType() == ITy);
3492ec727ea7Spatrick   assert(ITy->getScalarSizeInBits() <= 64);
3493ec727ea7Spatrick 
3494ec727ea7Spatrick   const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3495ec727ea7Spatrick   int Size = DataLayout.getTypeStoreSize(ITy);
3496ec727ea7Spatrick   SmallVector<uint64_t, 4> Bits(Size);
3497a0747c9fSpatrick   setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
3498ec727ea7Spatrick 
3499ec727ea7Spatrick   int CharWidth = CGM.getContext().getCharWidth();
3500ec727ea7Spatrick   uint64_t Mask =
3501ec727ea7Spatrick       buildMultiCharMask(Bits, 0, Size, CharWidth, DataLayout.isBigEndian());
3502ec727ea7Spatrick 
3503ec727ea7Spatrick   return Builder.CreateAnd(Src, Mask, "cmse.clear");
3504ec727ea7Spatrick }
3505ec727ea7Spatrick 
3506ec727ea7Spatrick // Emit code to clear the bits in a record, which aren't a part of any user
3507ec727ea7Spatrick // declared member, when the record is a function argument.
EmitCMSEClearRecord(llvm::Value * Src,llvm::ArrayType * ATy,QualType QTy)3508ec727ea7Spatrick llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3509ec727ea7Spatrick                                                   llvm::ArrayType *ATy,
3510ec727ea7Spatrick                                                   QualType QTy) {
3511ec727ea7Spatrick   const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3512ec727ea7Spatrick   int Size = DataLayout.getTypeStoreSize(ATy);
3513ec727ea7Spatrick   SmallVector<uint64_t, 16> Bits(Size);
3514a0747c9fSpatrick   setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
3515ec727ea7Spatrick 
3516ec727ea7Spatrick   // Clear each element of the LLVM array.
3517ec727ea7Spatrick   int CharWidth = CGM.getContext().getCharWidth();
3518ec727ea7Spatrick   int CharsPerElt =
3519ec727ea7Spatrick       ATy->getArrayElementType()->getScalarSizeInBits() / CharWidth;
3520ec727ea7Spatrick   int MaskIndex = 0;
3521*7a9b00ceSrobert   llvm::Value *R = llvm::PoisonValue::get(ATy);
3522ec727ea7Spatrick   for (int I = 0, N = ATy->getArrayNumElements(); I != N; ++I) {
3523ec727ea7Spatrick     uint64_t Mask = buildMultiCharMask(Bits, MaskIndex, CharsPerElt, CharWidth,
3524ec727ea7Spatrick                                        DataLayout.isBigEndian());
3525ec727ea7Spatrick     MaskIndex += CharsPerElt;
3526ec727ea7Spatrick     llvm::Value *T0 = Builder.CreateExtractValue(Src, I);
3527ec727ea7Spatrick     llvm::Value *T1 = Builder.CreateAnd(T0, Mask, "cmse.clear");
3528ec727ea7Spatrick     R = Builder.CreateInsertValue(R, T1, I);
3529ec727ea7Spatrick   }
3530ec727ea7Spatrick 
3531ec727ea7Spatrick   return R;
3532ec727ea7Spatrick }
3533ec727ea7Spatrick 
EmitFunctionEpilog(const CGFunctionInfo & FI,bool EmitRetDbgLoc,SourceLocation EndLoc)3534e5dd7070Spatrick void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
3535e5dd7070Spatrick                                          bool EmitRetDbgLoc,
3536e5dd7070Spatrick                                          SourceLocation EndLoc) {
3537e5dd7070Spatrick   if (FI.isNoReturn()) {
3538e5dd7070Spatrick     // Noreturn functions don't return.
3539e5dd7070Spatrick     EmitUnreachable(EndLoc);
3540e5dd7070Spatrick     return;
3541e5dd7070Spatrick   }
3542e5dd7070Spatrick 
3543e5dd7070Spatrick   if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
3544e5dd7070Spatrick     // Naked functions don't have epilogues.
3545e5dd7070Spatrick     Builder.CreateUnreachable();
3546e5dd7070Spatrick     return;
3547e5dd7070Spatrick   }
3548e5dd7070Spatrick 
3549e5dd7070Spatrick   // Functions with no result always return void.
3550e5dd7070Spatrick   if (!ReturnValue.isValid()) {
3551e5dd7070Spatrick     Builder.CreateRetVoid();
3552e5dd7070Spatrick     return;
3553e5dd7070Spatrick   }
3554e5dd7070Spatrick 
3555e5dd7070Spatrick   llvm::DebugLoc RetDbgLoc;
3556e5dd7070Spatrick   llvm::Value *RV = nullptr;
3557e5dd7070Spatrick   QualType RetTy = FI.getReturnType();
3558e5dd7070Spatrick   const ABIArgInfo &RetAI = FI.getReturnInfo();
3559e5dd7070Spatrick 
3560e5dd7070Spatrick   switch (RetAI.getKind()) {
3561e5dd7070Spatrick   case ABIArgInfo::InAlloca:
3562*7a9b00ceSrobert     // Aggregates get evaluated directly into the destination.  Sometimes we
3563e5dd7070Spatrick     // need to return the sret value in a register, though.
3564e5dd7070Spatrick     assert(hasAggregateEvaluationKind(RetTy));
3565e5dd7070Spatrick     if (RetAI.getInAllocaSRet()) {
3566e5dd7070Spatrick       llvm::Function::arg_iterator EI = CurFn->arg_end();
3567e5dd7070Spatrick       --EI;
3568e5dd7070Spatrick       llvm::Value *ArgStruct = &*EI;
3569e5dd7070Spatrick       llvm::Value *SRet = Builder.CreateStructGEP(
3570*7a9b00ceSrobert           FI.getArgStruct(), ArgStruct, RetAI.getInAllocaFieldIndex());
3571a0747c9fSpatrick       llvm::Type *Ty =
3572a0747c9fSpatrick           cast<llvm::GetElementPtrInst>(SRet)->getResultElementType();
3573a0747c9fSpatrick       RV = Builder.CreateAlignedLoad(Ty, SRet, getPointerAlign(), "sret");
3574e5dd7070Spatrick     }
3575e5dd7070Spatrick     break;
3576e5dd7070Spatrick 
3577e5dd7070Spatrick   case ABIArgInfo::Indirect: {
3578e5dd7070Spatrick     auto AI = CurFn->arg_begin();
3579e5dd7070Spatrick     if (RetAI.isSRetAfterThis())
3580e5dd7070Spatrick       ++AI;
3581e5dd7070Spatrick     switch (getEvaluationKind(RetTy)) {
3582e5dd7070Spatrick     case TEK_Complex: {
3583e5dd7070Spatrick       ComplexPairTy RT =
3584e5dd7070Spatrick         EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
3585e5dd7070Spatrick       EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
3586e5dd7070Spatrick                          /*isInit*/ true);
3587e5dd7070Spatrick       break;
3588e5dd7070Spatrick     }
3589e5dd7070Spatrick     case TEK_Aggregate:
3590*7a9b00ceSrobert       // Do nothing; aggregates get evaluated directly into the destination.
3591e5dd7070Spatrick       break;
3592*7a9b00ceSrobert     case TEK_Scalar: {
3593*7a9b00ceSrobert       LValueBaseInfo BaseInfo;
3594*7a9b00ceSrobert       TBAAAccessInfo TBAAInfo;
3595*7a9b00ceSrobert       CharUnits Alignment =
3596*7a9b00ceSrobert           CGM.getNaturalTypeAlignment(RetTy, &BaseInfo, &TBAAInfo);
3597*7a9b00ceSrobert       Address ArgAddr(&*AI, ConvertType(RetTy), Alignment);
3598*7a9b00ceSrobert       LValue ArgVal =
3599*7a9b00ceSrobert           LValue::MakeAddr(ArgAddr, RetTy, getContext(), BaseInfo, TBAAInfo);
3600*7a9b00ceSrobert       EmitStoreOfScalar(
3601*7a9b00ceSrobert           Builder.CreateLoad(ReturnValue), ArgVal, /*isInit*/ true);
3602e5dd7070Spatrick       break;
3603e5dd7070Spatrick     }
3604*7a9b00ceSrobert     }
3605e5dd7070Spatrick     break;
3606e5dd7070Spatrick   }
3607e5dd7070Spatrick 
3608e5dd7070Spatrick   case ABIArgInfo::Extend:
3609e5dd7070Spatrick   case ABIArgInfo::Direct:
3610e5dd7070Spatrick     if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
3611e5dd7070Spatrick         RetAI.getDirectOffset() == 0) {
3612e5dd7070Spatrick       // The internal return value temp always will have pointer-to-return-type
3613e5dd7070Spatrick       // type, just do a load.
3614e5dd7070Spatrick 
3615e5dd7070Spatrick       // If there is a dominating store to ReturnValue, we can elide
3616e5dd7070Spatrick       // the load, zap the store, and usually zap the alloca.
3617e5dd7070Spatrick       if (llvm::StoreInst *SI =
3618e5dd7070Spatrick               findDominatingStoreToReturnValue(*this)) {
3619e5dd7070Spatrick         // Reuse the debug location from the store unless there is
3620e5dd7070Spatrick         // cleanup code to be emitted between the store and return
3621e5dd7070Spatrick         // instruction.
3622e5dd7070Spatrick         if (EmitRetDbgLoc && !AutoreleaseResult)
3623e5dd7070Spatrick           RetDbgLoc = SI->getDebugLoc();
3624e5dd7070Spatrick         // Get the stored value and nuke the now-dead store.
3625e5dd7070Spatrick         RV = SI->getValueOperand();
3626e5dd7070Spatrick         SI->eraseFromParent();
3627e5dd7070Spatrick 
3628e5dd7070Spatrick       // Otherwise, we have to do a simple load.
3629e5dd7070Spatrick       } else {
3630e5dd7070Spatrick         RV = Builder.CreateLoad(ReturnValue);
3631e5dd7070Spatrick       }
3632e5dd7070Spatrick     } else {
3633e5dd7070Spatrick       // If the value is offset in memory, apply the offset now.
3634e5dd7070Spatrick       Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
3635e5dd7070Spatrick 
3636e5dd7070Spatrick       RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
3637e5dd7070Spatrick     }
3638e5dd7070Spatrick 
3639e5dd7070Spatrick     // In ARC, end functions that return a retainable type with a call
3640e5dd7070Spatrick     // to objc_autoreleaseReturnValue.
3641e5dd7070Spatrick     if (AutoreleaseResult) {
3642e5dd7070Spatrick #ifndef NDEBUG
3643e5dd7070Spatrick       // Type::isObjCRetainabletype has to be called on a QualType that hasn't
3644e5dd7070Spatrick       // been stripped of the typedefs, so we cannot use RetTy here. Get the
3645e5dd7070Spatrick       // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
3646e5dd7070Spatrick       // CurCodeDecl or BlockInfo.
3647e5dd7070Spatrick       QualType RT;
3648e5dd7070Spatrick 
3649e5dd7070Spatrick       if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
3650e5dd7070Spatrick         RT = FD->getReturnType();
3651e5dd7070Spatrick       else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
3652e5dd7070Spatrick         RT = MD->getReturnType();
3653e5dd7070Spatrick       else if (isa<BlockDecl>(CurCodeDecl))
3654e5dd7070Spatrick         RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
3655e5dd7070Spatrick       else
3656e5dd7070Spatrick         llvm_unreachable("Unexpected function/method type");
3657e5dd7070Spatrick 
3658e5dd7070Spatrick       assert(getLangOpts().ObjCAutoRefCount &&
3659e5dd7070Spatrick              !FI.isReturnsRetained() &&
3660e5dd7070Spatrick              RT->isObjCRetainableType());
3661e5dd7070Spatrick #endif
3662e5dd7070Spatrick       RV = emitAutoreleaseOfResult(*this, RV);
3663e5dd7070Spatrick     }
3664e5dd7070Spatrick 
3665e5dd7070Spatrick     break;
3666e5dd7070Spatrick 
3667e5dd7070Spatrick   case ABIArgInfo::Ignore:
3668e5dd7070Spatrick     break;
3669e5dd7070Spatrick 
3670e5dd7070Spatrick   case ABIArgInfo::CoerceAndExpand: {
3671e5dd7070Spatrick     auto coercionType = RetAI.getCoerceAndExpandType();
3672e5dd7070Spatrick 
3673e5dd7070Spatrick     // Load all of the coerced elements out into results.
3674e5dd7070Spatrick     llvm::SmallVector<llvm::Value*, 4> results;
3675e5dd7070Spatrick     Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
3676e5dd7070Spatrick     for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3677e5dd7070Spatrick       auto coercedEltType = coercionType->getElementType(i);
3678e5dd7070Spatrick       if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
3679e5dd7070Spatrick         continue;
3680e5dd7070Spatrick 
3681e5dd7070Spatrick       auto eltAddr = Builder.CreateStructGEP(addr, i);
3682e5dd7070Spatrick       auto elt = Builder.CreateLoad(eltAddr);
3683e5dd7070Spatrick       results.push_back(elt);
3684e5dd7070Spatrick     }
3685e5dd7070Spatrick 
3686e5dd7070Spatrick     // If we have one result, it's the single direct result type.
3687e5dd7070Spatrick     if (results.size() == 1) {
3688e5dd7070Spatrick       RV = results[0];
3689e5dd7070Spatrick 
3690e5dd7070Spatrick     // Otherwise, we need to make a first-class aggregate.
3691e5dd7070Spatrick     } else {
3692e5dd7070Spatrick       // Construct a return type that lacks padding elements.
3693e5dd7070Spatrick       llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
3694e5dd7070Spatrick 
3695*7a9b00ceSrobert       RV = llvm::PoisonValue::get(returnType);
3696e5dd7070Spatrick       for (unsigned i = 0, e = results.size(); i != e; ++i) {
3697e5dd7070Spatrick         RV = Builder.CreateInsertValue(RV, results[i], i);
3698e5dd7070Spatrick       }
3699e5dd7070Spatrick     }
3700e5dd7070Spatrick     break;
3701e5dd7070Spatrick   }
3702e5dd7070Spatrick   case ABIArgInfo::Expand:
3703a0747c9fSpatrick   case ABIArgInfo::IndirectAliased:
3704e5dd7070Spatrick     llvm_unreachable("Invalid ABI kind for return argument");
3705e5dd7070Spatrick   }
3706e5dd7070Spatrick 
3707e5dd7070Spatrick   llvm::Instruction *Ret;
3708e5dd7070Spatrick   if (RV) {
3709ec727ea7Spatrick     if (CurFuncDecl && CurFuncDecl->hasAttr<CmseNSEntryAttr>()) {
3710ec727ea7Spatrick       // For certain return types, clear padding bits, as they may reveal
3711ec727ea7Spatrick       // sensitive information.
3712ec727ea7Spatrick       // Small struct/union types are passed as integers.
3713ec727ea7Spatrick       auto *ITy = dyn_cast<llvm::IntegerType>(RV->getType());
3714ec727ea7Spatrick       if (ITy != nullptr && isa<RecordType>(RetTy.getCanonicalType()))
3715ec727ea7Spatrick         RV = EmitCMSEClearRecord(RV, ITy, RetTy);
3716ec727ea7Spatrick     }
3717e5dd7070Spatrick     EmitReturnValueCheck(RV);
3718e5dd7070Spatrick     Ret = Builder.CreateRet(RV);
3719e5dd7070Spatrick   } else {
3720e5dd7070Spatrick     Ret = Builder.CreateRetVoid();
3721e5dd7070Spatrick   }
3722e5dd7070Spatrick 
3723e5dd7070Spatrick   if (RetDbgLoc)
3724e5dd7070Spatrick     Ret->setDebugLoc(std::move(RetDbgLoc));
3725e5dd7070Spatrick }
3726e5dd7070Spatrick 
EmitReturnValueCheck(llvm::Value * RV)3727e5dd7070Spatrick void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) {
3728e5dd7070Spatrick   // A current decl may not be available when emitting vtable thunks.
3729e5dd7070Spatrick   if (!CurCodeDecl)
3730e5dd7070Spatrick     return;
3731e5dd7070Spatrick 
3732ec727ea7Spatrick   // If the return block isn't reachable, neither is this check, so don't emit
3733ec727ea7Spatrick   // it.
3734ec727ea7Spatrick   if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty())
3735ec727ea7Spatrick     return;
3736ec727ea7Spatrick 
3737e5dd7070Spatrick   ReturnsNonNullAttr *RetNNAttr = nullptr;
3738e5dd7070Spatrick   if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
3739e5dd7070Spatrick     RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
3740e5dd7070Spatrick 
3741e5dd7070Spatrick   if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
3742e5dd7070Spatrick     return;
3743e5dd7070Spatrick 
3744e5dd7070Spatrick   // Prefer the returns_nonnull attribute if it's present.
3745e5dd7070Spatrick   SourceLocation AttrLoc;
3746e5dd7070Spatrick   SanitizerMask CheckKind;
3747e5dd7070Spatrick   SanitizerHandler Handler;
3748e5dd7070Spatrick   if (RetNNAttr) {
3749e5dd7070Spatrick     assert(!requiresReturnValueNullabilityCheck() &&
3750e5dd7070Spatrick            "Cannot check nullability and the nonnull attribute");
3751e5dd7070Spatrick     AttrLoc = RetNNAttr->getLocation();
3752e5dd7070Spatrick     CheckKind = SanitizerKind::ReturnsNonnullAttribute;
3753e5dd7070Spatrick     Handler = SanitizerHandler::NonnullReturn;
3754e5dd7070Spatrick   } else {
3755e5dd7070Spatrick     if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl))
3756e5dd7070Spatrick       if (auto *TSI = DD->getTypeSourceInfo())
3757ec727ea7Spatrick         if (auto FTL = TSI->getTypeLoc().getAsAdjusted<FunctionTypeLoc>())
3758e5dd7070Spatrick           AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
3759e5dd7070Spatrick     CheckKind = SanitizerKind::NullabilityReturn;
3760e5dd7070Spatrick     Handler = SanitizerHandler::NullabilityReturn;
3761e5dd7070Spatrick   }
3762e5dd7070Spatrick 
3763e5dd7070Spatrick   SanitizerScope SanScope(this);
3764e5dd7070Spatrick 
3765e5dd7070Spatrick   // Make sure the "return" source location is valid. If we're checking a
3766e5dd7070Spatrick   // nullability annotation, make sure the preconditions for the check are met.
3767e5dd7070Spatrick   llvm::BasicBlock *Check = createBasicBlock("nullcheck");
3768e5dd7070Spatrick   llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck");
3769e5dd7070Spatrick   llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load");
3770e5dd7070Spatrick   llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr);
3771e5dd7070Spatrick   if (requiresReturnValueNullabilityCheck())
3772e5dd7070Spatrick     CanNullCheck =
3773e5dd7070Spatrick         Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition);
3774e5dd7070Spatrick   Builder.CreateCondBr(CanNullCheck, Check, NoCheck);
3775e5dd7070Spatrick   EmitBlock(Check);
3776e5dd7070Spatrick 
3777e5dd7070Spatrick   // Now do the null check.
3778e5dd7070Spatrick   llvm::Value *Cond = Builder.CreateIsNotNull(RV);
3779e5dd7070Spatrick   llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)};
3780e5dd7070Spatrick   llvm::Value *DynamicData[] = {SLocPtr};
3781e5dd7070Spatrick   EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData);
3782e5dd7070Spatrick 
3783e5dd7070Spatrick   EmitBlock(NoCheck);
3784e5dd7070Spatrick 
3785e5dd7070Spatrick #ifndef NDEBUG
3786e5dd7070Spatrick   // The return location should not be used after the check has been emitted.
3787e5dd7070Spatrick   ReturnLocation = Address::invalid();
3788e5dd7070Spatrick #endif
3789e5dd7070Spatrick }
3790e5dd7070Spatrick 
isInAllocaArgument(CGCXXABI & ABI,QualType type)3791e5dd7070Spatrick static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
3792e5dd7070Spatrick   const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
3793e5dd7070Spatrick   return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
3794e5dd7070Spatrick }
3795e5dd7070Spatrick 
createPlaceholderSlot(CodeGenFunction & CGF,QualType Ty)3796e5dd7070Spatrick static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
3797e5dd7070Spatrick                                           QualType Ty) {
3798e5dd7070Spatrick   // FIXME: Generate IR in one pass, rather than going back and fixing up these
3799e5dd7070Spatrick   // placeholders.
3800e5dd7070Spatrick   llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
3801e5dd7070Spatrick   llvm::Type *IRPtrTy = IRTy->getPointerTo();
3802*7a9b00ceSrobert   llvm::Value *Placeholder = llvm::PoisonValue::get(IRPtrTy->getPointerTo());
3803e5dd7070Spatrick 
3804e5dd7070Spatrick   // FIXME: When we generate this IR in one pass, we shouldn't need
3805e5dd7070Spatrick   // this win32-specific alignment hack.
3806e5dd7070Spatrick   CharUnits Align = CharUnits::fromQuantity(4);
3807e5dd7070Spatrick   Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
3808e5dd7070Spatrick 
3809*7a9b00ceSrobert   return AggValueSlot::forAddr(Address(Placeholder, IRTy, Align),
3810e5dd7070Spatrick                                Ty.getQualifiers(),
3811e5dd7070Spatrick                                AggValueSlot::IsNotDestructed,
3812e5dd7070Spatrick                                AggValueSlot::DoesNotNeedGCBarriers,
3813e5dd7070Spatrick                                AggValueSlot::IsNotAliased,
3814e5dd7070Spatrick                                AggValueSlot::DoesNotOverlap);
3815e5dd7070Spatrick }
3816e5dd7070Spatrick 
EmitDelegateCallArg(CallArgList & args,const VarDecl * param,SourceLocation loc)3817e5dd7070Spatrick void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
3818e5dd7070Spatrick                                           const VarDecl *param,
3819e5dd7070Spatrick                                           SourceLocation loc) {
3820e5dd7070Spatrick   // StartFunction converted the ABI-lowered parameter(s) into a
3821e5dd7070Spatrick   // local alloca.  We need to turn that into an r-value suitable
3822e5dd7070Spatrick   // for EmitCall.
3823e5dd7070Spatrick   Address local = GetAddrOfLocalVar(param);
3824e5dd7070Spatrick 
3825e5dd7070Spatrick   QualType type = param->getType();
3826e5dd7070Spatrick 
3827e5dd7070Spatrick   if (isInAllocaArgument(CGM.getCXXABI(), type)) {
3828e5dd7070Spatrick     CGM.ErrorUnsupported(param, "forwarded non-trivially copyable parameter");
3829e5dd7070Spatrick   }
3830e5dd7070Spatrick 
3831e5dd7070Spatrick   // GetAddrOfLocalVar returns a pointer-to-pointer for references,
3832e5dd7070Spatrick   // but the argument needs to be the original pointer.
3833e5dd7070Spatrick   if (type->isReferenceType()) {
3834e5dd7070Spatrick     args.add(RValue::get(Builder.CreateLoad(local)), type);
3835e5dd7070Spatrick 
3836e5dd7070Spatrick   // In ARC, move out of consumed arguments so that the release cleanup
3837e5dd7070Spatrick   // entered by StartFunction doesn't cause an over-release.  This isn't
3838e5dd7070Spatrick   // optimal -O0 code generation, but it should get cleaned up when
3839e5dd7070Spatrick   // optimization is enabled.  This also assumes that delegate calls are
3840e5dd7070Spatrick   // performed exactly once for a set of arguments, but that should be safe.
3841e5dd7070Spatrick   } else if (getLangOpts().ObjCAutoRefCount &&
3842e5dd7070Spatrick              param->hasAttr<NSConsumedAttr>() &&
3843e5dd7070Spatrick              type->isObjCRetainableType()) {
3844e5dd7070Spatrick     llvm::Value *ptr = Builder.CreateLoad(local);
3845e5dd7070Spatrick     auto null =
3846e5dd7070Spatrick       llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
3847e5dd7070Spatrick     Builder.CreateStore(null, local);
3848e5dd7070Spatrick     args.add(RValue::get(ptr), type);
3849e5dd7070Spatrick 
3850e5dd7070Spatrick   // For the most part, we just need to load the alloca, except that
3851e5dd7070Spatrick   // aggregate r-values are actually pointers to temporaries.
3852e5dd7070Spatrick   } else {
3853e5dd7070Spatrick     args.add(convertTempToRValue(local, type, loc), type);
3854e5dd7070Spatrick   }
3855e5dd7070Spatrick 
3856e5dd7070Spatrick   // Deactivate the cleanup for the callee-destructed param that was pushed.
3857a0747c9fSpatrick   if (type->isRecordType() && !CurFuncIsThunk &&
3858e5dd7070Spatrick       type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee() &&
3859e5dd7070Spatrick       param->needsDestruction(getContext())) {
3860e5dd7070Spatrick     EHScopeStack::stable_iterator cleanup =
3861e5dd7070Spatrick         CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param));
3862e5dd7070Spatrick     assert(cleanup.isValid() &&
3863e5dd7070Spatrick            "cleanup for callee-destructed param not recorded");
3864e5dd7070Spatrick     // This unreachable is a temporary marker which will be removed later.
3865e5dd7070Spatrick     llvm::Instruction *isActive = Builder.CreateUnreachable();
3866e5dd7070Spatrick     args.addArgCleanupDeactivation(cleanup, isActive);
3867e5dd7070Spatrick   }
3868e5dd7070Spatrick }
3869e5dd7070Spatrick 
isProvablyNull(llvm::Value * addr)3870e5dd7070Spatrick static bool isProvablyNull(llvm::Value *addr) {
3871e5dd7070Spatrick   return isa<llvm::ConstantPointerNull>(addr);
3872e5dd7070Spatrick }
3873e5dd7070Spatrick 
3874e5dd7070Spatrick /// Emit the actual writing-back of a writeback.
emitWriteback(CodeGenFunction & CGF,const CallArgList::Writeback & writeback)3875e5dd7070Spatrick static void emitWriteback(CodeGenFunction &CGF,
3876e5dd7070Spatrick                           const CallArgList::Writeback &writeback) {
3877e5dd7070Spatrick   const LValue &srcLV = writeback.Source;
3878e5dd7070Spatrick   Address srcAddr = srcLV.getAddress(CGF);
3879e5dd7070Spatrick   assert(!isProvablyNull(srcAddr.getPointer()) &&
3880e5dd7070Spatrick          "shouldn't have writeback for provably null argument");
3881e5dd7070Spatrick 
3882e5dd7070Spatrick   llvm::BasicBlock *contBB = nullptr;
3883e5dd7070Spatrick 
3884e5dd7070Spatrick   // If the argument wasn't provably non-null, we need to null check
3885e5dd7070Spatrick   // before doing the store.
3886e5dd7070Spatrick   bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
3887e5dd7070Spatrick                                               CGF.CGM.getDataLayout());
3888e5dd7070Spatrick   if (!provablyNonNull) {
3889e5dd7070Spatrick     llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
3890e5dd7070Spatrick     contBB = CGF.createBasicBlock("icr.done");
3891e5dd7070Spatrick 
3892e5dd7070Spatrick     llvm::Value *isNull =
3893e5dd7070Spatrick       CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
3894e5dd7070Spatrick     CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
3895e5dd7070Spatrick     CGF.EmitBlock(writebackBB);
3896e5dd7070Spatrick   }
3897e5dd7070Spatrick 
3898e5dd7070Spatrick   // Load the value to writeback.
3899e5dd7070Spatrick   llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
3900e5dd7070Spatrick 
3901e5dd7070Spatrick   // Cast it back, in case we're writing an id to a Foo* or something.
3902e5dd7070Spatrick   value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
3903e5dd7070Spatrick                                     "icr.writeback-cast");
3904e5dd7070Spatrick 
3905e5dd7070Spatrick   // Perform the writeback.
3906e5dd7070Spatrick 
3907e5dd7070Spatrick   // If we have a "to use" value, it's something we need to emit a use
3908e5dd7070Spatrick   // of.  This has to be carefully threaded in: if it's done after the
3909e5dd7070Spatrick   // release it's potentially undefined behavior (and the optimizer
3910e5dd7070Spatrick   // will ignore it), and if it happens before the retain then the
3911e5dd7070Spatrick   // optimizer could move the release there.
3912e5dd7070Spatrick   if (writeback.ToUse) {
3913e5dd7070Spatrick     assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
3914e5dd7070Spatrick 
3915e5dd7070Spatrick     // Retain the new value.  No need to block-copy here:  the block's
3916e5dd7070Spatrick     // being passed up the stack.
3917e5dd7070Spatrick     value = CGF.EmitARCRetainNonBlock(value);
3918e5dd7070Spatrick 
3919e5dd7070Spatrick     // Emit the intrinsic use here.
3920e5dd7070Spatrick     CGF.EmitARCIntrinsicUse(writeback.ToUse);
3921e5dd7070Spatrick 
3922e5dd7070Spatrick     // Load the old value (primitively).
3923e5dd7070Spatrick     llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
3924e5dd7070Spatrick 
3925e5dd7070Spatrick     // Put the new value in place (primitively).
3926e5dd7070Spatrick     CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
3927e5dd7070Spatrick 
3928e5dd7070Spatrick     // Release the old value.
3929e5dd7070Spatrick     CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
3930e5dd7070Spatrick 
3931e5dd7070Spatrick   // Otherwise, we can just do a normal lvalue store.
3932e5dd7070Spatrick   } else {
3933e5dd7070Spatrick     CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
3934e5dd7070Spatrick   }
3935e5dd7070Spatrick 
3936e5dd7070Spatrick   // Jump to the continuation block.
3937e5dd7070Spatrick   if (!provablyNonNull)
3938e5dd7070Spatrick     CGF.EmitBlock(contBB);
3939e5dd7070Spatrick }
3940e5dd7070Spatrick 
emitWritebacks(CodeGenFunction & CGF,const CallArgList & args)3941e5dd7070Spatrick static void emitWritebacks(CodeGenFunction &CGF,
3942e5dd7070Spatrick                            const CallArgList &args) {
3943e5dd7070Spatrick   for (const auto &I : args.writebacks())
3944e5dd7070Spatrick     emitWriteback(CGF, I);
3945e5dd7070Spatrick }
3946e5dd7070Spatrick 
deactivateArgCleanupsBeforeCall(CodeGenFunction & CGF,const CallArgList & CallArgs)3947e5dd7070Spatrick static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
3948e5dd7070Spatrick                                             const CallArgList &CallArgs) {
3949e5dd7070Spatrick   ArrayRef<CallArgList::CallArgCleanup> Cleanups =
3950e5dd7070Spatrick     CallArgs.getCleanupsToDeactivate();
3951e5dd7070Spatrick   // Iterate in reverse to increase the likelihood of popping the cleanup.
3952e5dd7070Spatrick   for (const auto &I : llvm::reverse(Cleanups)) {
3953e5dd7070Spatrick     CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
3954e5dd7070Spatrick     I.IsActiveIP->eraseFromParent();
3955e5dd7070Spatrick   }
3956e5dd7070Spatrick }
3957e5dd7070Spatrick 
maybeGetUnaryAddrOfOperand(const Expr * E)3958e5dd7070Spatrick static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
3959e5dd7070Spatrick   if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
3960e5dd7070Spatrick     if (uop->getOpcode() == UO_AddrOf)
3961e5dd7070Spatrick       return uop->getSubExpr();
3962e5dd7070Spatrick   return nullptr;
3963e5dd7070Spatrick }
3964e5dd7070Spatrick 
3965e5dd7070Spatrick /// Emit an argument that's being passed call-by-writeback.  That is,
3966e5dd7070Spatrick /// we are passing the address of an __autoreleased temporary; it
3967e5dd7070Spatrick /// might be copy-initialized with the current value of the given
3968e5dd7070Spatrick /// address, but it will definitely be copied out of after the call.
emitWritebackArg(CodeGenFunction & CGF,CallArgList & args,const ObjCIndirectCopyRestoreExpr * CRE)3969e5dd7070Spatrick static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
3970e5dd7070Spatrick                              const ObjCIndirectCopyRestoreExpr *CRE) {
3971e5dd7070Spatrick   LValue srcLV;
3972e5dd7070Spatrick 
3973e5dd7070Spatrick   // Make an optimistic effort to emit the address as an l-value.
3974e5dd7070Spatrick   // This can fail if the argument expression is more complicated.
3975e5dd7070Spatrick   if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
3976e5dd7070Spatrick     srcLV = CGF.EmitLValue(lvExpr);
3977e5dd7070Spatrick 
3978e5dd7070Spatrick   // Otherwise, just emit it as a scalar.
3979e5dd7070Spatrick   } else {
3980e5dd7070Spatrick     Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
3981e5dd7070Spatrick 
3982e5dd7070Spatrick     QualType srcAddrType =
3983e5dd7070Spatrick       CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
3984e5dd7070Spatrick     srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
3985e5dd7070Spatrick   }
3986e5dd7070Spatrick   Address srcAddr = srcLV.getAddress(CGF);
3987e5dd7070Spatrick 
3988e5dd7070Spatrick   // The dest and src types don't necessarily match in LLVM terms
3989e5dd7070Spatrick   // because of the crazy ObjC compatibility rules.
3990e5dd7070Spatrick 
3991e5dd7070Spatrick   llvm::PointerType *destType =
3992e5dd7070Spatrick       cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
3993*7a9b00ceSrobert   llvm::Type *destElemType =
3994*7a9b00ceSrobert       CGF.ConvertTypeForMem(CRE->getType()->getPointeeType());
3995e5dd7070Spatrick 
3996e5dd7070Spatrick   // If the address is a constant null, just pass the appropriate null.
3997e5dd7070Spatrick   if (isProvablyNull(srcAddr.getPointer())) {
3998e5dd7070Spatrick     args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
3999e5dd7070Spatrick              CRE->getType());
4000e5dd7070Spatrick     return;
4001e5dd7070Spatrick   }
4002e5dd7070Spatrick 
4003e5dd7070Spatrick   // Create the temporary.
4004*7a9b00ceSrobert   Address temp =
4005*7a9b00ceSrobert       CGF.CreateTempAlloca(destElemType, CGF.getPointerAlign(), "icr.temp");
4006e5dd7070Spatrick   // Loading an l-value can introduce a cleanup if the l-value is __weak,
4007e5dd7070Spatrick   // and that cleanup will be conditional if we can't prove that the l-value
4008e5dd7070Spatrick   // isn't null, so we need to register a dominating point so that the cleanups
4009e5dd7070Spatrick   // system will make valid IR.
4010e5dd7070Spatrick   CodeGenFunction::ConditionalEvaluation condEval(CGF);
4011e5dd7070Spatrick 
4012e5dd7070Spatrick   // Zero-initialize it if we're not doing a copy-initialization.
4013e5dd7070Spatrick   bool shouldCopy = CRE->shouldCopy();
4014e5dd7070Spatrick   if (!shouldCopy) {
4015e5dd7070Spatrick     llvm::Value *null =
4016*7a9b00ceSrobert         llvm::ConstantPointerNull::get(cast<llvm::PointerType>(destElemType));
4017e5dd7070Spatrick     CGF.Builder.CreateStore(null, temp);
4018e5dd7070Spatrick   }
4019e5dd7070Spatrick 
4020e5dd7070Spatrick   llvm::BasicBlock *contBB = nullptr;
4021e5dd7070Spatrick   llvm::BasicBlock *originBB = nullptr;
4022e5dd7070Spatrick 
4023e5dd7070Spatrick   // If the address is *not* known to be non-null, we need to switch.
4024e5dd7070Spatrick   llvm::Value *finalArgument;
4025e5dd7070Spatrick 
4026e5dd7070Spatrick   bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
4027e5dd7070Spatrick                                               CGF.CGM.getDataLayout());
4028e5dd7070Spatrick   if (provablyNonNull) {
4029e5dd7070Spatrick     finalArgument = temp.getPointer();
4030e5dd7070Spatrick   } else {
4031e5dd7070Spatrick     llvm::Value *isNull =
4032e5dd7070Spatrick       CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
4033e5dd7070Spatrick 
4034e5dd7070Spatrick     finalArgument = CGF.Builder.CreateSelect(isNull,
4035e5dd7070Spatrick                                    llvm::ConstantPointerNull::get(destType),
4036e5dd7070Spatrick                                              temp.getPointer(), "icr.argument");
4037e5dd7070Spatrick 
4038e5dd7070Spatrick     // If we need to copy, then the load has to be conditional, which
4039e5dd7070Spatrick     // means we need control flow.
4040e5dd7070Spatrick     if (shouldCopy) {
4041e5dd7070Spatrick       originBB = CGF.Builder.GetInsertBlock();
4042e5dd7070Spatrick       contBB = CGF.createBasicBlock("icr.cont");
4043e5dd7070Spatrick       llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
4044e5dd7070Spatrick       CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
4045e5dd7070Spatrick       CGF.EmitBlock(copyBB);
4046e5dd7070Spatrick       condEval.begin(CGF);
4047e5dd7070Spatrick     }
4048e5dd7070Spatrick   }
4049e5dd7070Spatrick 
4050e5dd7070Spatrick   llvm::Value *valueToUse = nullptr;
4051e5dd7070Spatrick 
4052e5dd7070Spatrick   // Perform a copy if necessary.
4053e5dd7070Spatrick   if (shouldCopy) {
4054e5dd7070Spatrick     RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
4055e5dd7070Spatrick     assert(srcRV.isScalar());
4056e5dd7070Spatrick 
4057e5dd7070Spatrick     llvm::Value *src = srcRV.getScalarVal();
4058*7a9b00ceSrobert     src = CGF.Builder.CreateBitCast(src, destElemType, "icr.cast");
4059e5dd7070Spatrick 
4060e5dd7070Spatrick     // Use an ordinary store, not a store-to-lvalue.
4061e5dd7070Spatrick     CGF.Builder.CreateStore(src, temp);
4062e5dd7070Spatrick 
4063e5dd7070Spatrick     // If optimization is enabled, and the value was held in a
4064e5dd7070Spatrick     // __strong variable, we need to tell the optimizer that this
4065e5dd7070Spatrick     // value has to stay alive until we're doing the store back.
4066e5dd7070Spatrick     // This is because the temporary is effectively unretained,
4067e5dd7070Spatrick     // and so otherwise we can violate the high-level semantics.
4068e5dd7070Spatrick     if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
4069e5dd7070Spatrick         srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
4070e5dd7070Spatrick       valueToUse = src;
4071e5dd7070Spatrick     }
4072e5dd7070Spatrick   }
4073e5dd7070Spatrick 
4074e5dd7070Spatrick   // Finish the control flow if we needed it.
4075e5dd7070Spatrick   if (shouldCopy && !provablyNonNull) {
4076e5dd7070Spatrick     llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
4077e5dd7070Spatrick     CGF.EmitBlock(contBB);
4078e5dd7070Spatrick 
4079e5dd7070Spatrick     // Make a phi for the value to intrinsically use.
4080e5dd7070Spatrick     if (valueToUse) {
4081e5dd7070Spatrick       llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
4082e5dd7070Spatrick                                                       "icr.to-use");
4083e5dd7070Spatrick       phiToUse->addIncoming(valueToUse, copyBB);
4084e5dd7070Spatrick       phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
4085e5dd7070Spatrick                             originBB);
4086e5dd7070Spatrick       valueToUse = phiToUse;
4087e5dd7070Spatrick     }
4088e5dd7070Spatrick 
4089e5dd7070Spatrick     condEval.end(CGF);
4090e5dd7070Spatrick   }
4091e5dd7070Spatrick 
4092e5dd7070Spatrick   args.addWriteback(srcLV, temp, valueToUse);
4093e5dd7070Spatrick   args.add(RValue::get(finalArgument), CRE->getType());
4094e5dd7070Spatrick }
4095e5dd7070Spatrick 
allocateArgumentMemory(CodeGenFunction & CGF)4096e5dd7070Spatrick void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
4097e5dd7070Spatrick   assert(!StackBase);
4098e5dd7070Spatrick 
4099e5dd7070Spatrick   // Save the stack.
4100e5dd7070Spatrick   llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
4101e5dd7070Spatrick   StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
4102e5dd7070Spatrick }
4103e5dd7070Spatrick 
freeArgumentMemory(CodeGenFunction & CGF) const4104e5dd7070Spatrick void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
4105e5dd7070Spatrick   if (StackBase) {
4106e5dd7070Spatrick     // Restore the stack after the call.
4107e5dd7070Spatrick     llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
4108e5dd7070Spatrick     CGF.Builder.CreateCall(F, StackBase);
4109e5dd7070Spatrick   }
4110e5dd7070Spatrick }
4111e5dd7070Spatrick 
EmitNonNullArgCheck(RValue RV,QualType ArgType,SourceLocation ArgLoc,AbstractCallee AC,unsigned ParmNum)4112e5dd7070Spatrick void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
4113e5dd7070Spatrick                                           SourceLocation ArgLoc,
4114e5dd7070Spatrick                                           AbstractCallee AC,
4115e5dd7070Spatrick                                           unsigned ParmNum) {
4116e5dd7070Spatrick   if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
4117e5dd7070Spatrick                          SanOpts.has(SanitizerKind::NullabilityArg)))
4118e5dd7070Spatrick     return;
4119e5dd7070Spatrick 
4120e5dd7070Spatrick   // The param decl may be missing in a variadic function.
4121e5dd7070Spatrick   auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr;
4122e5dd7070Spatrick   unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
4123e5dd7070Spatrick 
4124e5dd7070Spatrick   // Prefer the nonnull attribute if it's present.
4125e5dd7070Spatrick   const NonNullAttr *NNAttr = nullptr;
4126e5dd7070Spatrick   if (SanOpts.has(SanitizerKind::NonnullAttribute))
4127e5dd7070Spatrick     NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
4128e5dd7070Spatrick 
4129e5dd7070Spatrick   bool CanCheckNullability = false;
4130e5dd7070Spatrick   if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD) {
4131*7a9b00ceSrobert     auto Nullability = PVD->getType()->getNullability();
4132e5dd7070Spatrick     CanCheckNullability = Nullability &&
4133e5dd7070Spatrick                           *Nullability == NullabilityKind::NonNull &&
4134e5dd7070Spatrick                           PVD->getTypeSourceInfo();
4135e5dd7070Spatrick   }
4136e5dd7070Spatrick 
4137e5dd7070Spatrick   if (!NNAttr && !CanCheckNullability)
4138e5dd7070Spatrick     return;
4139e5dd7070Spatrick 
4140e5dd7070Spatrick   SourceLocation AttrLoc;
4141e5dd7070Spatrick   SanitizerMask CheckKind;
4142e5dd7070Spatrick   SanitizerHandler Handler;
4143e5dd7070Spatrick   if (NNAttr) {
4144e5dd7070Spatrick     AttrLoc = NNAttr->getLocation();
4145e5dd7070Spatrick     CheckKind = SanitizerKind::NonnullAttribute;
4146e5dd7070Spatrick     Handler = SanitizerHandler::NonnullArg;
4147e5dd7070Spatrick   } else {
4148e5dd7070Spatrick     AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
4149e5dd7070Spatrick     CheckKind = SanitizerKind::NullabilityArg;
4150e5dd7070Spatrick     Handler = SanitizerHandler::NullabilityArg;
4151e5dd7070Spatrick   }
4152e5dd7070Spatrick 
4153e5dd7070Spatrick   SanitizerScope SanScope(this);
4154a0747c9fSpatrick   llvm::Value *Cond = EmitNonNullRValueCheck(RV, ArgType);
4155e5dd7070Spatrick   llvm::Constant *StaticData[] = {
4156e5dd7070Spatrick       EmitCheckSourceLocation(ArgLoc), EmitCheckSourceLocation(AttrLoc),
4157e5dd7070Spatrick       llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
4158e5dd7070Spatrick   };
4159*7a9b00ceSrobert   EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, std::nullopt);
4160e5dd7070Spatrick }
4161e5dd7070Spatrick 
4162a0747c9fSpatrick // Check if the call is going to use the inalloca convention. This needs to
4163a0747c9fSpatrick // agree with CGFunctionInfo::usesInAlloca. The CGFunctionInfo is arranged
4164a0747c9fSpatrick // later, so we can't check it directly.
hasInAllocaArgs(CodeGenModule & CGM,CallingConv ExplicitCC,ArrayRef<QualType> ArgTypes)4165a0747c9fSpatrick static bool hasInAllocaArgs(CodeGenModule &CGM, CallingConv ExplicitCC,
4166a0747c9fSpatrick                             ArrayRef<QualType> ArgTypes) {
4167a0747c9fSpatrick   // The Swift calling conventions don't go through the target-specific
4168a0747c9fSpatrick   // argument classification, they never use inalloca.
4169a0747c9fSpatrick   // TODO: Consider limiting inalloca use to only calling conventions supported
4170a0747c9fSpatrick   // by MSVC.
4171a0747c9fSpatrick   if (ExplicitCC == CC_Swift || ExplicitCC == CC_SwiftAsync)
4172a0747c9fSpatrick     return false;
4173a0747c9fSpatrick   if (!CGM.getTarget().getCXXABI().isMicrosoft())
4174a0747c9fSpatrick     return false;
4175a0747c9fSpatrick   return llvm::any_of(ArgTypes, [&](QualType Ty) {
4176a0747c9fSpatrick     return isInAllocaArgument(CGM.getCXXABI(), Ty);
4177a0747c9fSpatrick   });
4178a0747c9fSpatrick }
4179a0747c9fSpatrick 
4180a0747c9fSpatrick #ifndef NDEBUG
4181a0747c9fSpatrick // Determine whether the given argument is an Objective-C method
4182a0747c9fSpatrick // that may have type parameters in its signature.
isObjCMethodWithTypeParams(const ObjCMethodDecl * method)4183a0747c9fSpatrick static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
4184a0747c9fSpatrick   const DeclContext *dc = method->getDeclContext();
4185a0747c9fSpatrick   if (const ObjCInterfaceDecl *classDecl = dyn_cast<ObjCInterfaceDecl>(dc)) {
4186a0747c9fSpatrick     return classDecl->getTypeParamListAsWritten();
4187a0747c9fSpatrick   }
4188a0747c9fSpatrick 
4189a0747c9fSpatrick   if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
4190a0747c9fSpatrick     return catDecl->getTypeParamList();
4191a0747c9fSpatrick   }
4192a0747c9fSpatrick 
4193a0747c9fSpatrick   return false;
4194a0747c9fSpatrick }
4195a0747c9fSpatrick #endif
4196a0747c9fSpatrick 
4197a0747c9fSpatrick /// EmitCallArgs - Emit call arguments for a function.
EmitCallArgs(CallArgList & Args,PrototypeWrapper Prototype,llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,AbstractCallee AC,unsigned ParamsToSkip,EvaluationOrder Order)4198e5dd7070Spatrick void CodeGenFunction::EmitCallArgs(
4199a0747c9fSpatrick     CallArgList &Args, PrototypeWrapper Prototype,
4200e5dd7070Spatrick     llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
4201e5dd7070Spatrick     AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
4202a0747c9fSpatrick   SmallVector<QualType, 16> ArgTypes;
4203a0747c9fSpatrick 
4204a0747c9fSpatrick   assert((ParamsToSkip == 0 || Prototype.P) &&
4205a0747c9fSpatrick          "Can't skip parameters if type info is not provided");
4206a0747c9fSpatrick 
4207a0747c9fSpatrick   // This variable only captures *explicitly* written conventions, not those
4208a0747c9fSpatrick   // applied by default via command line flags or target defaults, such as
4209a0747c9fSpatrick   // thiscall, aapcs, stdcall via -mrtd, etc. Computing that correctly would
4210a0747c9fSpatrick   // require knowing if this is a C++ instance method or being able to see
4211a0747c9fSpatrick   // unprototyped FunctionTypes.
4212a0747c9fSpatrick   CallingConv ExplicitCC = CC_C;
4213a0747c9fSpatrick 
4214a0747c9fSpatrick   // First, if a prototype was provided, use those argument types.
4215a0747c9fSpatrick   bool IsVariadic = false;
4216a0747c9fSpatrick   if (Prototype.P) {
4217a0747c9fSpatrick     const auto *MD = Prototype.P.dyn_cast<const ObjCMethodDecl *>();
4218a0747c9fSpatrick     if (MD) {
4219a0747c9fSpatrick       IsVariadic = MD->isVariadic();
4220a0747c9fSpatrick       ExplicitCC = getCallingConventionForDecl(
4221a0747c9fSpatrick           MD, CGM.getTarget().getTriple().isOSWindows());
4222a0747c9fSpatrick       ArgTypes.assign(MD->param_type_begin() + ParamsToSkip,
4223a0747c9fSpatrick                       MD->param_type_end());
4224a0747c9fSpatrick     } else {
4225a0747c9fSpatrick       const auto *FPT = Prototype.P.get<const FunctionProtoType *>();
4226a0747c9fSpatrick       IsVariadic = FPT->isVariadic();
4227a0747c9fSpatrick       ExplicitCC = FPT->getExtInfo().getCC();
4228a0747c9fSpatrick       ArgTypes.assign(FPT->param_type_begin() + ParamsToSkip,
4229a0747c9fSpatrick                       FPT->param_type_end());
4230a0747c9fSpatrick     }
4231a0747c9fSpatrick 
4232a0747c9fSpatrick #ifndef NDEBUG
4233a0747c9fSpatrick     // Check that the prototyped types match the argument expression types.
4234a0747c9fSpatrick     bool isGenericMethod = MD && isObjCMethodWithTypeParams(MD);
4235a0747c9fSpatrick     CallExpr::const_arg_iterator Arg = ArgRange.begin();
4236a0747c9fSpatrick     for (QualType Ty : ArgTypes) {
4237a0747c9fSpatrick       assert(Arg != ArgRange.end() && "Running over edge of argument list!");
4238a0747c9fSpatrick       assert(
4239a0747c9fSpatrick           (isGenericMethod || Ty->isVariablyModifiedType() ||
4240a0747c9fSpatrick            Ty.getNonReferenceType()->isObjCRetainableType() ||
4241a0747c9fSpatrick            getContext()
4242a0747c9fSpatrick                    .getCanonicalType(Ty.getNonReferenceType())
4243a0747c9fSpatrick                    .getTypePtr() ==
4244a0747c9fSpatrick                getContext().getCanonicalType((*Arg)->getType()).getTypePtr()) &&
4245a0747c9fSpatrick           "type mismatch in call argument!");
4246a0747c9fSpatrick       ++Arg;
4247a0747c9fSpatrick     }
4248a0747c9fSpatrick 
4249a0747c9fSpatrick     // Either we've emitted all the call args, or we have a call to variadic
4250a0747c9fSpatrick     // function.
4251a0747c9fSpatrick     assert((Arg == ArgRange.end() || IsVariadic) &&
4252a0747c9fSpatrick            "Extra arguments in non-variadic function!");
4253a0747c9fSpatrick #endif
4254a0747c9fSpatrick   }
4255a0747c9fSpatrick 
4256a0747c9fSpatrick   // If we still have any arguments, emit them using the type of the argument.
4257*7a9b00ceSrobert   for (auto *A : llvm::drop_begin(ArgRange, ArgTypes.size()))
4258a0747c9fSpatrick     ArgTypes.push_back(IsVariadic ? getVarArgType(A) : A->getType());
4259e5dd7070Spatrick   assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
4260e5dd7070Spatrick 
4261a0747c9fSpatrick   // We must evaluate arguments from right to left in the MS C++ ABI,
4262e5dd7070Spatrick   // because arguments are destroyed left to right in the callee. As a special
4263e5dd7070Spatrick   // case, there are certain language constructs that require left-to-right
4264e5dd7070Spatrick   // evaluation, and in those cases we consider the evaluation order requirement
4265e5dd7070Spatrick   // to trump the "destruction order is reverse construction order" guarantee.
4266e5dd7070Spatrick   bool LeftToRight =
4267e5dd7070Spatrick       CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
4268e5dd7070Spatrick           ? Order == EvaluationOrder::ForceLeftToRight
4269e5dd7070Spatrick           : Order != EvaluationOrder::ForceRightToLeft;
4270e5dd7070Spatrick 
4271e5dd7070Spatrick   auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
4272e5dd7070Spatrick                                          RValue EmittedArg) {
4273e5dd7070Spatrick     if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
4274e5dd7070Spatrick       return;
4275e5dd7070Spatrick     auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
4276e5dd7070Spatrick     if (PS == nullptr)
4277e5dd7070Spatrick       return;
4278e5dd7070Spatrick 
4279e5dd7070Spatrick     const auto &Context = getContext();
4280e5dd7070Spatrick     auto SizeTy = Context.getSizeType();
4281e5dd7070Spatrick     auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
4282e5dd7070Spatrick     assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?");
4283e5dd7070Spatrick     llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
4284e5dd7070Spatrick                                                      EmittedArg.getScalarVal(),
4285e5dd7070Spatrick                                                      PS->isDynamic());
4286e5dd7070Spatrick     Args.add(RValue::get(V), SizeTy);
4287e5dd7070Spatrick     // If we're emitting args in reverse, be sure to do so with
4288e5dd7070Spatrick     // pass_object_size, as well.
4289e5dd7070Spatrick     if (!LeftToRight)
4290e5dd7070Spatrick       std::swap(Args.back(), *(&Args.back() - 1));
4291e5dd7070Spatrick   };
4292e5dd7070Spatrick 
4293e5dd7070Spatrick   // Insert a stack save if we're going to need any inalloca args.
4294a0747c9fSpatrick   if (hasInAllocaArgs(CGM, ExplicitCC, ArgTypes)) {
4295a0747c9fSpatrick     assert(getTarget().getTriple().getArch() == llvm::Triple::x86 &&
4296a0747c9fSpatrick            "inalloca only supported on x86");
4297e5dd7070Spatrick     Args.allocateArgumentMemory(*this);
4298e5dd7070Spatrick   }
4299e5dd7070Spatrick 
4300e5dd7070Spatrick   // Evaluate each argument in the appropriate order.
4301e5dd7070Spatrick   size_t CallArgsStart = Args.size();
4302e5dd7070Spatrick   for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
4303e5dd7070Spatrick     unsigned Idx = LeftToRight ? I : E - I - 1;
4304e5dd7070Spatrick     CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
4305e5dd7070Spatrick     unsigned InitialArgSize = Args.size();
4306e5dd7070Spatrick     // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of
4307e5dd7070Spatrick     // the argument and parameter match or the objc method is parameterized.
4308e5dd7070Spatrick     assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) ||
4309e5dd7070Spatrick             getContext().hasSameUnqualifiedType((*Arg)->getType(),
4310e5dd7070Spatrick                                                 ArgTypes[Idx]) ||
4311e5dd7070Spatrick             (isa<ObjCMethodDecl>(AC.getDecl()) &&
4312e5dd7070Spatrick              isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) &&
4313e5dd7070Spatrick            "Argument and parameter types don't match");
4314e5dd7070Spatrick     EmitCallArg(Args, *Arg, ArgTypes[Idx]);
4315e5dd7070Spatrick     // In particular, we depend on it being the last arg in Args, and the
4316e5dd7070Spatrick     // objectsize bits depend on there only being one arg if !LeftToRight.
4317e5dd7070Spatrick     assert(InitialArgSize + 1 == Args.size() &&
4318e5dd7070Spatrick            "The code below depends on only adding one arg per EmitCallArg");
4319e5dd7070Spatrick     (void)InitialArgSize;
4320e5dd7070Spatrick     // Since pointer argument are never emitted as LValue, it is safe to emit
4321e5dd7070Spatrick     // non-null argument check for r-value only.
4322e5dd7070Spatrick     if (!Args.back().hasLValue()) {
4323e5dd7070Spatrick       RValue RVArg = Args.back().getKnownRValue();
4324e5dd7070Spatrick       EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
4325e5dd7070Spatrick                           ParamsToSkip + Idx);
4326e5dd7070Spatrick       // @llvm.objectsize should never have side-effects and shouldn't need
4327e5dd7070Spatrick       // destruction/cleanups, so we can safely "emit" it after its arg,
4328e5dd7070Spatrick       // regardless of right-to-leftness
4329e5dd7070Spatrick       MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
4330e5dd7070Spatrick     }
4331e5dd7070Spatrick   }
4332e5dd7070Spatrick 
4333e5dd7070Spatrick   if (!LeftToRight) {
4334e5dd7070Spatrick     // Un-reverse the arguments we just evaluated so they match up with the LLVM
4335e5dd7070Spatrick     // IR function.
4336e5dd7070Spatrick     std::reverse(Args.begin() + CallArgsStart, Args.end());
4337e5dd7070Spatrick   }
4338e5dd7070Spatrick }
4339e5dd7070Spatrick 
4340e5dd7070Spatrick namespace {
4341e5dd7070Spatrick 
4342e5dd7070Spatrick struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
DestroyUnpassedArg__anon5c86009b0d11::DestroyUnpassedArg4343e5dd7070Spatrick   DestroyUnpassedArg(Address Addr, QualType Ty)
4344e5dd7070Spatrick       : Addr(Addr), Ty(Ty) {}
4345e5dd7070Spatrick 
4346e5dd7070Spatrick   Address Addr;
4347e5dd7070Spatrick   QualType Ty;
4348e5dd7070Spatrick 
Emit__anon5c86009b0d11::DestroyUnpassedArg4349e5dd7070Spatrick   void Emit(CodeGenFunction &CGF, Flags flags) override {
4350e5dd7070Spatrick     QualType::DestructionKind DtorKind = Ty.isDestructedType();
4351e5dd7070Spatrick     if (DtorKind == QualType::DK_cxx_destructor) {
4352e5dd7070Spatrick       const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
4353e5dd7070Spatrick       assert(!Dtor->isTrivial());
4354e5dd7070Spatrick       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
4355e5dd7070Spatrick                                 /*Delegating=*/false, Addr, Ty);
4356e5dd7070Spatrick     } else {
4357e5dd7070Spatrick       CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty));
4358e5dd7070Spatrick     }
4359e5dd7070Spatrick   }
4360e5dd7070Spatrick };
4361e5dd7070Spatrick 
4362e5dd7070Spatrick struct DisableDebugLocationUpdates {
4363e5dd7070Spatrick   CodeGenFunction &CGF;
4364e5dd7070Spatrick   bool disabledDebugInfo;
DisableDebugLocationUpdates__anon5c86009b0d11::DisableDebugLocationUpdates4365e5dd7070Spatrick   DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
4366e5dd7070Spatrick     if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
4367e5dd7070Spatrick       CGF.disableDebugInfo();
4368e5dd7070Spatrick   }
~DisableDebugLocationUpdates__anon5c86009b0d11::DisableDebugLocationUpdates4369e5dd7070Spatrick   ~DisableDebugLocationUpdates() {
4370e5dd7070Spatrick     if (disabledDebugInfo)
4371e5dd7070Spatrick       CGF.enableDebugInfo();
4372e5dd7070Spatrick   }
4373e5dd7070Spatrick };
4374e5dd7070Spatrick 
4375e5dd7070Spatrick } // end anonymous namespace
4376e5dd7070Spatrick 
getRValue(CodeGenFunction & CGF) const4377e5dd7070Spatrick RValue CallArg::getRValue(CodeGenFunction &CGF) const {
4378e5dd7070Spatrick   if (!HasLV)
4379e5dd7070Spatrick     return RV;
4380e5dd7070Spatrick   LValue Copy = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty), Ty);
4381e5dd7070Spatrick   CGF.EmitAggregateCopy(Copy, LV, Ty, AggValueSlot::DoesNotOverlap,
4382e5dd7070Spatrick                         LV.isVolatile());
4383e5dd7070Spatrick   IsUsed = true;
4384e5dd7070Spatrick   return RValue::getAggregate(Copy.getAddress(CGF));
4385e5dd7070Spatrick }
4386e5dd7070Spatrick 
copyInto(CodeGenFunction & CGF,Address Addr) const4387e5dd7070Spatrick void CallArg::copyInto(CodeGenFunction &CGF, Address Addr) const {
4388e5dd7070Spatrick   LValue Dst = CGF.MakeAddrLValue(Addr, Ty);
4389e5dd7070Spatrick   if (!HasLV && RV.isScalar())
4390e5dd7070Spatrick     CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*isInit=*/true);
4391e5dd7070Spatrick   else if (!HasLV && RV.isComplex())
4392e5dd7070Spatrick     CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true);
4393e5dd7070Spatrick   else {
4394e5dd7070Spatrick     auto Addr = HasLV ? LV.getAddress(CGF) : RV.getAggregateAddress();
4395e5dd7070Spatrick     LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty);
4396e5dd7070Spatrick     // We assume that call args are never copied into subobjects.
4397e5dd7070Spatrick     CGF.EmitAggregateCopy(Dst, SrcLV, Ty, AggValueSlot::DoesNotOverlap,
4398e5dd7070Spatrick                           HasLV ? LV.isVolatileQualified()
4399e5dd7070Spatrick                                 : RV.isVolatileQualified());
4400e5dd7070Spatrick   }
4401e5dd7070Spatrick   IsUsed = true;
4402e5dd7070Spatrick }
4403e5dd7070Spatrick 
EmitCallArg(CallArgList & args,const Expr * E,QualType type)4404e5dd7070Spatrick void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
4405e5dd7070Spatrick                                   QualType type) {
4406e5dd7070Spatrick   DisableDebugLocationUpdates Dis(*this, E);
4407e5dd7070Spatrick   if (const ObjCIndirectCopyRestoreExpr *CRE
4408e5dd7070Spatrick         = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
4409e5dd7070Spatrick     assert(getLangOpts().ObjCAutoRefCount);
4410e5dd7070Spatrick     return emitWritebackArg(*this, args, CRE);
4411e5dd7070Spatrick   }
4412e5dd7070Spatrick 
4413e5dd7070Spatrick   assert(type->isReferenceType() == E->isGLValue() &&
4414e5dd7070Spatrick          "reference binding to unmaterialized r-value!");
4415e5dd7070Spatrick 
4416e5dd7070Spatrick   if (E->isGLValue()) {
4417e5dd7070Spatrick     assert(E->getObjectKind() == OK_Ordinary);
4418e5dd7070Spatrick     return args.add(EmitReferenceBindingToExpr(E), type);
4419e5dd7070Spatrick   }
4420e5dd7070Spatrick 
4421e5dd7070Spatrick   bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
4422e5dd7070Spatrick 
4423e5dd7070Spatrick   // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
4424e5dd7070Spatrick   // However, we still have to push an EH-only cleanup in case we unwind before
4425e5dd7070Spatrick   // we make it to the call.
4426a0747c9fSpatrick   if (type->isRecordType() &&
4427e5dd7070Spatrick       type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
4428e5dd7070Spatrick     // If we're using inalloca, use the argument memory.  Otherwise, use a
4429e5dd7070Spatrick     // temporary.
4430*7a9b00ceSrobert     AggValueSlot Slot = args.isUsingInAlloca()
4431*7a9b00ceSrobert         ? createPlaceholderSlot(*this, type) : CreateAggTemp(type, "agg.tmp");
4432e5dd7070Spatrick 
4433e5dd7070Spatrick     bool DestroyedInCallee = true, NeedsEHCleanup = true;
4434e5dd7070Spatrick     if (const auto *RD = type->getAsCXXRecordDecl())
4435e5dd7070Spatrick       DestroyedInCallee = RD->hasNonTrivialDestructor();
4436e5dd7070Spatrick     else
4437e5dd7070Spatrick       NeedsEHCleanup = needsEHCleanup(type.isDestructedType());
4438e5dd7070Spatrick 
4439e5dd7070Spatrick     if (DestroyedInCallee)
4440e5dd7070Spatrick       Slot.setExternallyDestructed();
4441e5dd7070Spatrick 
4442e5dd7070Spatrick     EmitAggExpr(E, Slot);
4443e5dd7070Spatrick     RValue RV = Slot.asRValue();
4444e5dd7070Spatrick     args.add(RV, type);
4445e5dd7070Spatrick 
4446e5dd7070Spatrick     if (DestroyedInCallee && NeedsEHCleanup) {
4447e5dd7070Spatrick       // Create a no-op GEP between the placeholder and the cleanup so we can
4448e5dd7070Spatrick       // RAUW it successfully.  It also serves as a marker of the first
4449e5dd7070Spatrick       // instruction where the cleanup is active.
4450e5dd7070Spatrick       pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
4451e5dd7070Spatrick                                               type);
4452e5dd7070Spatrick       // This unreachable is a temporary marker which will be removed later.
4453e5dd7070Spatrick       llvm::Instruction *IsActive = Builder.CreateUnreachable();
4454*7a9b00ceSrobert       args.addArgCleanupDeactivation(EHStack.stable_begin(), IsActive);
4455e5dd7070Spatrick     }
4456e5dd7070Spatrick     return;
4457e5dd7070Spatrick   }
4458e5dd7070Spatrick 
4459e5dd7070Spatrick   if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
4460e5dd7070Spatrick       cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
4461e5dd7070Spatrick     LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
4462e5dd7070Spatrick     assert(L.isSimple());
4463e5dd7070Spatrick     args.addUncopiedAggregate(L, type);
4464e5dd7070Spatrick     return;
4465e5dd7070Spatrick   }
4466e5dd7070Spatrick 
4467e5dd7070Spatrick   args.add(EmitAnyExprToTemp(E), type);
4468e5dd7070Spatrick }
4469e5dd7070Spatrick 
getVarArgType(const Expr * Arg)4470e5dd7070Spatrick QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
4471e5dd7070Spatrick   // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
4472e5dd7070Spatrick   // implicitly widens null pointer constants that are arguments to varargs
4473e5dd7070Spatrick   // functions to pointer-sized ints.
4474e5dd7070Spatrick   if (!getTarget().getTriple().isOSWindows())
4475e5dd7070Spatrick     return Arg->getType();
4476e5dd7070Spatrick 
4477e5dd7070Spatrick   if (Arg->getType()->isIntegerType() &&
4478e5dd7070Spatrick       getContext().getTypeSize(Arg->getType()) <
4479*7a9b00ceSrobert           getContext().getTargetInfo().getPointerWidth(LangAS::Default) &&
4480e5dd7070Spatrick       Arg->isNullPointerConstant(getContext(),
4481e5dd7070Spatrick                                  Expr::NPC_ValueDependentIsNotNull)) {
4482e5dd7070Spatrick     return getContext().getIntPtrType();
4483e5dd7070Spatrick   }
4484e5dd7070Spatrick 
4485e5dd7070Spatrick   return Arg->getType();
4486e5dd7070Spatrick }
4487e5dd7070Spatrick 
4488e5dd7070Spatrick // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4489e5dd7070Spatrick // optimizer it can aggressively ignore unwind edges.
4490e5dd7070Spatrick void
AddObjCARCExceptionMetadata(llvm::Instruction * Inst)4491e5dd7070Spatrick CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
4492e5dd7070Spatrick   if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
4493e5dd7070Spatrick       !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
4494e5dd7070Spatrick     Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
4495e5dd7070Spatrick                       CGM.getNoObjCARCExceptionsMetadata());
4496e5dd7070Spatrick }
4497e5dd7070Spatrick 
4498e5dd7070Spatrick /// Emits a call to the given no-arguments nounwind runtime function.
4499e5dd7070Spatrick llvm::CallInst *
EmitNounwindRuntimeCall(llvm::FunctionCallee callee,const llvm::Twine & name)4500e5dd7070Spatrick CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4501e5dd7070Spatrick                                          const llvm::Twine &name) {
4502*7a9b00ceSrobert   return EmitNounwindRuntimeCall(callee, std::nullopt, name);
4503e5dd7070Spatrick }
4504e5dd7070Spatrick 
4505e5dd7070Spatrick /// Emits a call to the given nounwind runtime function.
4506e5dd7070Spatrick llvm::CallInst *
EmitNounwindRuntimeCall(llvm::FunctionCallee callee,ArrayRef<llvm::Value * > args,const llvm::Twine & name)4507e5dd7070Spatrick CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4508e5dd7070Spatrick                                          ArrayRef<llvm::Value *> args,
4509e5dd7070Spatrick                                          const llvm::Twine &name) {
4510e5dd7070Spatrick   llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
4511e5dd7070Spatrick   call->setDoesNotThrow();
4512e5dd7070Spatrick   return call;
4513e5dd7070Spatrick }
4514e5dd7070Spatrick 
4515e5dd7070Spatrick /// Emits a simple call (never an invoke) to the given no-arguments
4516e5dd7070Spatrick /// runtime function.
EmitRuntimeCall(llvm::FunctionCallee callee,const llvm::Twine & name)4517e5dd7070Spatrick llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
4518e5dd7070Spatrick                                                  const llvm::Twine &name) {
4519*7a9b00ceSrobert   return EmitRuntimeCall(callee, std::nullopt, name);
4520e5dd7070Spatrick }
4521e5dd7070Spatrick 
4522e5dd7070Spatrick // Calls which may throw must have operand bundles indicating which funclet
4523e5dd7070Spatrick // they are nested within.
4524e5dd7070Spatrick SmallVector<llvm::OperandBundleDef, 1>
getBundlesForFunclet(llvm::Value * Callee)4525e5dd7070Spatrick CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) {
4526e5dd7070Spatrick   // There is no need for a funclet operand bundle if we aren't inside a
4527e5dd7070Spatrick   // funclet.
4528e5dd7070Spatrick   if (!CurrentFuncletPad)
4529*7a9b00ceSrobert     return (SmallVector<llvm::OperandBundleDef, 1>());
4530e5dd7070Spatrick 
4531*7a9b00ceSrobert   // Skip intrinsics which cannot throw (as long as they don't lower into
4532*7a9b00ceSrobert   // regular function calls in the course of IR transformations).
4533*7a9b00ceSrobert   if (auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts())) {
4534*7a9b00ceSrobert     if (CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow()) {
4535*7a9b00ceSrobert       auto IID = CalleeFn->getIntrinsicID();
4536*7a9b00ceSrobert       if (!llvm::IntrinsicInst::mayLowerToFunctionCall(IID))
4537*7a9b00ceSrobert         return (SmallVector<llvm::OperandBundleDef, 1>());
4538*7a9b00ceSrobert     }
4539*7a9b00ceSrobert   }
4540e5dd7070Spatrick 
4541*7a9b00ceSrobert   SmallVector<llvm::OperandBundleDef, 1> BundleList;
4542e5dd7070Spatrick   BundleList.emplace_back("funclet", CurrentFuncletPad);
4543e5dd7070Spatrick   return BundleList;
4544e5dd7070Spatrick }
4545e5dd7070Spatrick 
4546e5dd7070Spatrick /// Emits a simple call (never an invoke) to the given runtime function.
EmitRuntimeCall(llvm::FunctionCallee callee,ArrayRef<llvm::Value * > args,const llvm::Twine & name)4547e5dd7070Spatrick llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
4548e5dd7070Spatrick                                                  ArrayRef<llvm::Value *> args,
4549e5dd7070Spatrick                                                  const llvm::Twine &name) {
4550e5dd7070Spatrick   llvm::CallInst *call = Builder.CreateCall(
4551e5dd7070Spatrick       callee, args, getBundlesForFunclet(callee.getCallee()), name);
4552e5dd7070Spatrick   call->setCallingConv(getRuntimeCC());
4553e5dd7070Spatrick   return call;
4554e5dd7070Spatrick }
4555e5dd7070Spatrick 
4556e5dd7070Spatrick /// Emits a call or invoke to the given noreturn runtime function.
EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee,ArrayRef<llvm::Value * > args)4557e5dd7070Spatrick void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(
4558e5dd7070Spatrick     llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) {
4559e5dd7070Spatrick   SmallVector<llvm::OperandBundleDef, 1> BundleList =
4560e5dd7070Spatrick       getBundlesForFunclet(callee.getCallee());
4561e5dd7070Spatrick 
4562e5dd7070Spatrick   if (getInvokeDest()) {
4563e5dd7070Spatrick     llvm::InvokeInst *invoke =
4564e5dd7070Spatrick       Builder.CreateInvoke(callee,
4565e5dd7070Spatrick                            getUnreachableBlock(),
4566e5dd7070Spatrick                            getInvokeDest(),
4567e5dd7070Spatrick                            args,
4568e5dd7070Spatrick                            BundleList);
4569e5dd7070Spatrick     invoke->setDoesNotReturn();
4570e5dd7070Spatrick     invoke->setCallingConv(getRuntimeCC());
4571e5dd7070Spatrick   } else {
4572e5dd7070Spatrick     llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
4573e5dd7070Spatrick     call->setDoesNotReturn();
4574e5dd7070Spatrick     call->setCallingConv(getRuntimeCC());
4575e5dd7070Spatrick     Builder.CreateUnreachable();
4576e5dd7070Spatrick   }
4577e5dd7070Spatrick }
4578e5dd7070Spatrick 
4579e5dd7070Spatrick /// Emits a call or invoke instruction to the given nullary runtime function.
4580e5dd7070Spatrick llvm::CallBase *
EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,const Twine & name)4581e5dd7070Spatrick CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4582e5dd7070Spatrick                                          const Twine &name) {
4583*7a9b00ceSrobert   return EmitRuntimeCallOrInvoke(callee, std::nullopt, name);
4584e5dd7070Spatrick }
4585e5dd7070Spatrick 
4586e5dd7070Spatrick /// Emits a call or invoke instruction to the given runtime function.
4587e5dd7070Spatrick llvm::CallBase *
EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,ArrayRef<llvm::Value * > args,const Twine & name)4588e5dd7070Spatrick CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4589e5dd7070Spatrick                                          ArrayRef<llvm::Value *> args,
4590e5dd7070Spatrick                                          const Twine &name) {
4591e5dd7070Spatrick   llvm::CallBase *call = EmitCallOrInvoke(callee, args, name);
4592e5dd7070Spatrick   call->setCallingConv(getRuntimeCC());
4593e5dd7070Spatrick   return call;
4594e5dd7070Spatrick }
4595e5dd7070Spatrick 
4596e5dd7070Spatrick /// Emits a call or invoke instruction to the given function, depending
4597e5dd7070Spatrick /// on the current state of the EH stack.
EmitCallOrInvoke(llvm::FunctionCallee Callee,ArrayRef<llvm::Value * > Args,const Twine & Name)4598e5dd7070Spatrick llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee,
4599e5dd7070Spatrick                                                   ArrayRef<llvm::Value *> Args,
4600e5dd7070Spatrick                                                   const Twine &Name) {
4601e5dd7070Spatrick   llvm::BasicBlock *InvokeDest = getInvokeDest();
4602e5dd7070Spatrick   SmallVector<llvm::OperandBundleDef, 1> BundleList =
4603e5dd7070Spatrick       getBundlesForFunclet(Callee.getCallee());
4604e5dd7070Spatrick 
4605e5dd7070Spatrick   llvm::CallBase *Inst;
4606e5dd7070Spatrick   if (!InvokeDest)
4607e5dd7070Spatrick     Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
4608e5dd7070Spatrick   else {
4609e5dd7070Spatrick     llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
4610e5dd7070Spatrick     Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
4611e5dd7070Spatrick                                 Name);
4612e5dd7070Spatrick     EmitBlock(ContBB);
4613e5dd7070Spatrick   }
4614e5dd7070Spatrick 
4615e5dd7070Spatrick   // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4616e5dd7070Spatrick   // optimizer it can aggressively ignore unwind edges.
4617e5dd7070Spatrick   if (CGM.getLangOpts().ObjCAutoRefCount)
4618e5dd7070Spatrick     AddObjCARCExceptionMetadata(Inst);
4619e5dd7070Spatrick 
4620e5dd7070Spatrick   return Inst;
4621e5dd7070Spatrick }
4622e5dd7070Spatrick 
deferPlaceholderReplacement(llvm::Instruction * Old,llvm::Value * New)4623e5dd7070Spatrick void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
4624e5dd7070Spatrick                                                   llvm::Value *New) {
4625a0747c9fSpatrick   DeferredReplacements.push_back(
4626a0747c9fSpatrick       std::make_pair(llvm::WeakTrackingVH(Old), New));
4627e5dd7070Spatrick }
4628e5dd7070Spatrick 
4629ec727ea7Spatrick namespace {
4630ec727ea7Spatrick 
4631ec727ea7Spatrick /// Specify given \p NewAlign as the alignment of return value attribute. If
4632ec727ea7Spatrick /// such attribute already exists, re-set it to the maximal one of two options.
4633*7a9b00ceSrobert [[nodiscard]] llvm::AttributeList
maybeRaiseRetAlignmentAttribute(llvm::LLVMContext & Ctx,const llvm::AttributeList & Attrs,llvm::Align NewAlign)4634ec727ea7Spatrick maybeRaiseRetAlignmentAttribute(llvm::LLVMContext &Ctx,
4635ec727ea7Spatrick                                 const llvm::AttributeList &Attrs,
4636ec727ea7Spatrick                                 llvm::Align NewAlign) {
4637ec727ea7Spatrick   llvm::Align CurAlign = Attrs.getRetAlignment().valueOrOne();
4638ec727ea7Spatrick   if (CurAlign >= NewAlign)
4639ec727ea7Spatrick     return Attrs;
4640ec727ea7Spatrick   llvm::Attribute AlignAttr = llvm::Attribute::getWithAlignment(Ctx, NewAlign);
4641*7a9b00ceSrobert   return Attrs.removeRetAttribute(Ctx, llvm::Attribute::AttrKind::Alignment)
4642*7a9b00ceSrobert       .addRetAttribute(Ctx, AlignAttr);
4643ec727ea7Spatrick }
4644ec727ea7Spatrick 
4645ec727ea7Spatrick template <typename AlignedAttrTy> class AbstractAssumeAlignedAttrEmitter {
4646ec727ea7Spatrick protected:
4647ec727ea7Spatrick   CodeGenFunction &CGF;
4648ec727ea7Spatrick 
4649ec727ea7Spatrick   /// We do nothing if this is, or becomes, nullptr.
4650ec727ea7Spatrick   const AlignedAttrTy *AA = nullptr;
4651ec727ea7Spatrick 
4652ec727ea7Spatrick   llvm::Value *Alignment = nullptr;      // May or may not be a constant.
4653ec727ea7Spatrick   llvm::ConstantInt *OffsetCI = nullptr; // Constant, hopefully zero.
4654ec727ea7Spatrick 
AbstractAssumeAlignedAttrEmitter(CodeGenFunction & CGF_,const Decl * FuncDecl)4655ec727ea7Spatrick   AbstractAssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
4656ec727ea7Spatrick       : CGF(CGF_) {
4657ec727ea7Spatrick     if (!FuncDecl)
4658ec727ea7Spatrick       return;
4659ec727ea7Spatrick     AA = FuncDecl->getAttr<AlignedAttrTy>();
4660ec727ea7Spatrick   }
4661ec727ea7Spatrick 
4662ec727ea7Spatrick public:
4663ec727ea7Spatrick   /// If we can, materialize the alignment as an attribute on return value.
4664*7a9b00ceSrobert   [[nodiscard]] llvm::AttributeList
TryEmitAsCallSiteAttribute(const llvm::AttributeList & Attrs)4665ec727ea7Spatrick   TryEmitAsCallSiteAttribute(const llvm::AttributeList &Attrs) {
4666ec727ea7Spatrick     if (!AA || OffsetCI || CGF.SanOpts.has(SanitizerKind::Alignment))
4667ec727ea7Spatrick       return Attrs;
4668ec727ea7Spatrick     const auto *AlignmentCI = dyn_cast<llvm::ConstantInt>(Alignment);
4669ec727ea7Spatrick     if (!AlignmentCI)
4670ec727ea7Spatrick       return Attrs;
4671ec727ea7Spatrick     // We may legitimately have non-power-of-2 alignment here.
4672ec727ea7Spatrick     // If so, this is UB land, emit it via `@llvm.assume` instead.
4673ec727ea7Spatrick     if (!AlignmentCI->getValue().isPowerOf2())
4674ec727ea7Spatrick       return Attrs;
4675ec727ea7Spatrick     llvm::AttributeList NewAttrs = maybeRaiseRetAlignmentAttribute(
4676ec727ea7Spatrick         CGF.getLLVMContext(), Attrs,
4677ec727ea7Spatrick         llvm::Align(
4678ec727ea7Spatrick             AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment)));
4679ec727ea7Spatrick     AA = nullptr; // We're done. Disallow doing anything else.
4680ec727ea7Spatrick     return NewAttrs;
4681ec727ea7Spatrick   }
4682ec727ea7Spatrick 
4683ec727ea7Spatrick   /// Emit alignment assumption.
4684ec727ea7Spatrick   /// This is a general fallback that we take if either there is an offset,
4685ec727ea7Spatrick   /// or the alignment is variable or we are sanitizing for alignment.
EmitAsAnAssumption(SourceLocation Loc,QualType RetTy,RValue & Ret)4686ec727ea7Spatrick   void EmitAsAnAssumption(SourceLocation Loc, QualType RetTy, RValue &Ret) {
4687ec727ea7Spatrick     if (!AA)
4688ec727ea7Spatrick       return;
4689ec727ea7Spatrick     CGF.emitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc,
4690ec727ea7Spatrick                                 AA->getLocation(), Alignment, OffsetCI);
4691ec727ea7Spatrick     AA = nullptr; // We're done. Disallow doing anything else.
4692ec727ea7Spatrick   }
4693ec727ea7Spatrick };
4694ec727ea7Spatrick 
4695ec727ea7Spatrick /// Helper data structure to emit `AssumeAlignedAttr`.
4696ec727ea7Spatrick class AssumeAlignedAttrEmitter final
4697ec727ea7Spatrick     : public AbstractAssumeAlignedAttrEmitter<AssumeAlignedAttr> {
4698ec727ea7Spatrick public:
AssumeAlignedAttrEmitter(CodeGenFunction & CGF_,const Decl * FuncDecl)4699ec727ea7Spatrick   AssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
4700ec727ea7Spatrick       : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
4701ec727ea7Spatrick     if (!AA)
4702ec727ea7Spatrick       return;
4703ec727ea7Spatrick     // It is guaranteed that the alignment/offset are constants.
4704ec727ea7Spatrick     Alignment = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AA->getAlignment()));
4705ec727ea7Spatrick     if (Expr *Offset = AA->getOffset()) {
4706ec727ea7Spatrick       OffsetCI = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(Offset));
4707ec727ea7Spatrick       if (OffsetCI->isNullValue()) // Canonicalize zero offset to no offset.
4708ec727ea7Spatrick         OffsetCI = nullptr;
4709ec727ea7Spatrick     }
4710ec727ea7Spatrick   }
4711ec727ea7Spatrick };
4712ec727ea7Spatrick 
4713ec727ea7Spatrick /// Helper data structure to emit `AllocAlignAttr`.
4714ec727ea7Spatrick class AllocAlignAttrEmitter final
4715ec727ea7Spatrick     : public AbstractAssumeAlignedAttrEmitter<AllocAlignAttr> {
4716ec727ea7Spatrick public:
AllocAlignAttrEmitter(CodeGenFunction & CGF_,const Decl * FuncDecl,const CallArgList & CallArgs)4717ec727ea7Spatrick   AllocAlignAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl,
4718ec727ea7Spatrick                         const CallArgList &CallArgs)
4719ec727ea7Spatrick       : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
4720ec727ea7Spatrick     if (!AA)
4721ec727ea7Spatrick       return;
4722ec727ea7Spatrick     // Alignment may or may not be a constant, and that is okay.
4723ec727ea7Spatrick     Alignment = CallArgs[AA->getParamIndex().getLLVMIndex()]
4724ec727ea7Spatrick                     .getRValue(CGF)
4725ec727ea7Spatrick                     .getScalarVal();
4726ec727ea7Spatrick   }
4727ec727ea7Spatrick };
4728ec727ea7Spatrick 
4729ec727ea7Spatrick } // namespace
4730ec727ea7Spatrick 
getMaxVectorWidth(const llvm::Type * Ty)4731*7a9b00ceSrobert static unsigned getMaxVectorWidth(const llvm::Type *Ty) {
4732*7a9b00ceSrobert   if (auto *VT = dyn_cast<llvm::VectorType>(Ty))
4733*7a9b00ceSrobert     return VT->getPrimitiveSizeInBits().getKnownMinValue();
4734*7a9b00ceSrobert   if (auto *AT = dyn_cast<llvm::ArrayType>(Ty))
4735*7a9b00ceSrobert     return getMaxVectorWidth(AT->getElementType());
4736*7a9b00ceSrobert 
4737*7a9b00ceSrobert   unsigned MaxVectorWidth = 0;
4738*7a9b00ceSrobert   if (auto *ST = dyn_cast<llvm::StructType>(Ty))
4739*7a9b00ceSrobert     for (auto *I : ST->elements())
4740*7a9b00ceSrobert       MaxVectorWidth = std::max(MaxVectorWidth, getMaxVectorWidth(I));
4741*7a9b00ceSrobert   return MaxVectorWidth;
4742*7a9b00ceSrobert }
4743*7a9b00ceSrobert 
EmitCall(const CGFunctionInfo & CallInfo,const CGCallee & Callee,ReturnValueSlot ReturnValue,const CallArgList & CallArgs,llvm::CallBase ** callOrInvoke,bool IsMustTail,SourceLocation Loc)4744e5dd7070Spatrick RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
4745e5dd7070Spatrick                                  const CGCallee &Callee,
4746e5dd7070Spatrick                                  ReturnValueSlot ReturnValue,
4747e5dd7070Spatrick                                  const CallArgList &CallArgs,
4748a0747c9fSpatrick                                  llvm::CallBase **callOrInvoke, bool IsMustTail,
4749e5dd7070Spatrick                                  SourceLocation Loc) {
4750e5dd7070Spatrick   // FIXME: We no longer need the types from CallArgs; lift up and simplify.
4751e5dd7070Spatrick 
4752e5dd7070Spatrick   assert(Callee.isOrdinary() || Callee.isVirtual());
4753e5dd7070Spatrick 
4754e5dd7070Spatrick   // Handle struct-return functions by passing a pointer to the
4755e5dd7070Spatrick   // location that we would like to return into.
4756e5dd7070Spatrick   QualType RetTy = CallInfo.getReturnType();
4757e5dd7070Spatrick   const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
4758e5dd7070Spatrick 
4759e5dd7070Spatrick   llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
4760e5dd7070Spatrick 
4761e5dd7070Spatrick   const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
4762ec727ea7Spatrick   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
4763e5dd7070Spatrick     // We can only guarantee that a function is called from the correct
4764e5dd7070Spatrick     // context/function based on the appropriate target attributes,
4765e5dd7070Spatrick     // so only check in the case where we have both always_inline and target
4766e5dd7070Spatrick     // since otherwise we could be making a conditional call after a check for
4767e5dd7070Spatrick     // the proper cpu features (and it won't cause code generation issues due to
4768e5dd7070Spatrick     // function based code generation).
4769e5dd7070Spatrick     if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4770e5dd7070Spatrick         TargetDecl->hasAttr<TargetAttr>())
4771e5dd7070Spatrick       checkTargetFeatures(Loc, FD);
4772e5dd7070Spatrick 
4773ec727ea7Spatrick     // Some architectures (such as x86-64) have the ABI changed based on
4774ec727ea7Spatrick     // attribute-target/features. Give them a chance to diagnose.
4775ec727ea7Spatrick     CGM.getTargetCodeGenInfo().checkFunctionCallABI(
4776ec727ea7Spatrick         CGM, Loc, dyn_cast_or_null<FunctionDecl>(CurCodeDecl), FD, CallArgs);
4777ec727ea7Spatrick   }
4778ec727ea7Spatrick 
4779e5dd7070Spatrick #ifndef NDEBUG
4780e5dd7070Spatrick   if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) {
4781e5dd7070Spatrick     // For an inalloca varargs function, we don't expect CallInfo to match the
4782e5dd7070Spatrick     // function pointer's type, because the inalloca struct a will have extra
4783e5dd7070Spatrick     // fields in it for the varargs parameters.  Code later in this function
4784e5dd7070Spatrick     // bitcasts the function pointer to the type derived from CallInfo.
4785e5dd7070Spatrick     //
4786e5dd7070Spatrick     // In other cases, we assert that the types match up (until pointers stop
4787e5dd7070Spatrick     // having pointee types).
4788e5dd7070Spatrick     if (Callee.isVirtual())
4789*7a9b00ceSrobert       assert(IRFuncTy == Callee.getVirtualFunctionType());
4790*7a9b00ceSrobert     else {
4791*7a9b00ceSrobert       llvm::PointerType *PtrTy =
4792*7a9b00ceSrobert           llvm::cast<llvm::PointerType>(Callee.getFunctionPointer()->getType());
4793*7a9b00ceSrobert       assert(PtrTy->isOpaqueOrPointeeTypeMatches(IRFuncTy));
4794*7a9b00ceSrobert     }
4795e5dd7070Spatrick   }
4796e5dd7070Spatrick #endif
4797e5dd7070Spatrick 
4798e5dd7070Spatrick   // 1. Set up the arguments.
4799e5dd7070Spatrick 
4800e5dd7070Spatrick   // If we're using inalloca, insert the allocation after the stack save.
4801e5dd7070Spatrick   // FIXME: Do this earlier rather than hacking it in here!
4802e5dd7070Spatrick   Address ArgMemory = Address::invalid();
4803e5dd7070Spatrick   if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
4804e5dd7070Spatrick     const llvm::DataLayout &DL = CGM.getDataLayout();
4805e5dd7070Spatrick     llvm::Instruction *IP = CallArgs.getStackBase();
4806e5dd7070Spatrick     llvm::AllocaInst *AI;
4807e5dd7070Spatrick     if (IP) {
4808e5dd7070Spatrick       IP = IP->getNextNode();
4809e5dd7070Spatrick       AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(),
4810e5dd7070Spatrick                                 "argmem", IP);
4811e5dd7070Spatrick     } else {
4812e5dd7070Spatrick       AI = CreateTempAlloca(ArgStruct, "argmem");
4813e5dd7070Spatrick     }
4814e5dd7070Spatrick     auto Align = CallInfo.getArgStructAlignment();
4815e5dd7070Spatrick     AI->setAlignment(Align.getAsAlign());
4816e5dd7070Spatrick     AI->setUsedWithInAlloca(true);
4817e5dd7070Spatrick     assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
4818*7a9b00ceSrobert     ArgMemory = Address(AI, ArgStruct, Align);
4819e5dd7070Spatrick   }
4820e5dd7070Spatrick 
4821e5dd7070Spatrick   ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
4822e5dd7070Spatrick   SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
4823e5dd7070Spatrick 
4824e5dd7070Spatrick   // If the call returns a temporary with struct return, create a temporary
4825e5dd7070Spatrick   // alloca to hold the result, unless one is given to us.
4826e5dd7070Spatrick   Address SRetPtr = Address::invalid();
4827e5dd7070Spatrick   Address SRetAlloca = Address::invalid();
4828e5dd7070Spatrick   llvm::Value *UnusedReturnSizePtr = nullptr;
4829e5dd7070Spatrick   if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
4830e5dd7070Spatrick     if (!ReturnValue.isNull()) {
4831e5dd7070Spatrick       SRetPtr = ReturnValue.getValue();
4832e5dd7070Spatrick     } else {
4833e5dd7070Spatrick       SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca);
4834e5dd7070Spatrick       if (HaveInsertPoint() && ReturnValue.isUnused()) {
4835a0747c9fSpatrick         llvm::TypeSize size =
4836e5dd7070Spatrick             CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
4837e5dd7070Spatrick         UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer());
4838e5dd7070Spatrick       }
4839e5dd7070Spatrick     }
4840e5dd7070Spatrick     if (IRFunctionArgs.hasSRetArg()) {
4841e5dd7070Spatrick       IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
4842e5dd7070Spatrick     } else if (RetAI.isInAlloca()) {
4843e5dd7070Spatrick       Address Addr =
4844e5dd7070Spatrick           Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
4845e5dd7070Spatrick       Builder.CreateStore(SRetPtr.getPointer(), Addr);
4846e5dd7070Spatrick     }
4847e5dd7070Spatrick   }
4848e5dd7070Spatrick 
4849e5dd7070Spatrick   Address swiftErrorTemp = Address::invalid();
4850e5dd7070Spatrick   Address swiftErrorArg = Address::invalid();
4851e5dd7070Spatrick 
4852e5dd7070Spatrick   // When passing arguments using temporary allocas, we need to add the
4853e5dd7070Spatrick   // appropriate lifetime markers. This vector keeps track of all the lifetime
4854e5dd7070Spatrick   // markers that need to be ended right after the call.
4855e5dd7070Spatrick   SmallVector<CallLifetimeEnd, 2> CallLifetimeEndAfterCall;
4856e5dd7070Spatrick 
4857e5dd7070Spatrick   // Translate all of the arguments as necessary to match the IR lowering.
4858e5dd7070Spatrick   assert(CallInfo.arg_size() == CallArgs.size() &&
4859e5dd7070Spatrick          "Mismatch between function signature & arguments.");
4860e5dd7070Spatrick   unsigned ArgNo = 0;
4861e5dd7070Spatrick   CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
4862e5dd7070Spatrick   for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
4863e5dd7070Spatrick        I != E; ++I, ++info_it, ++ArgNo) {
4864e5dd7070Spatrick     const ABIArgInfo &ArgInfo = info_it->info;
4865e5dd7070Spatrick 
4866e5dd7070Spatrick     // Insert a padding argument to ensure proper alignment.
4867e5dd7070Spatrick     if (IRFunctionArgs.hasPaddingArg(ArgNo))
4868e5dd7070Spatrick       IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
4869e5dd7070Spatrick           llvm::UndefValue::get(ArgInfo.getPaddingType());
4870e5dd7070Spatrick 
4871e5dd7070Spatrick     unsigned FirstIRArg, NumIRArgs;
4872e5dd7070Spatrick     std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
4873e5dd7070Spatrick 
4874*7a9b00ceSrobert     bool ArgHasMaybeUndefAttr =
4875*7a9b00ceSrobert         IsArgumentMaybeUndef(TargetDecl, CallInfo.getNumRequiredArgs(), ArgNo);
4876*7a9b00ceSrobert 
4877e5dd7070Spatrick     switch (ArgInfo.getKind()) {
4878e5dd7070Spatrick     case ABIArgInfo::InAlloca: {
4879e5dd7070Spatrick       assert(NumIRArgs == 0);
4880e5dd7070Spatrick       assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
4881e5dd7070Spatrick       if (I->isAggregate()) {
4882e5dd7070Spatrick         Address Addr = I->hasLValue()
4883e5dd7070Spatrick                            ? I->getKnownLValue().getAddress(*this)
4884e5dd7070Spatrick                            : I->getKnownRValue().getAggregateAddress();
4885e5dd7070Spatrick         llvm::Instruction *Placeholder =
4886e5dd7070Spatrick             cast<llvm::Instruction>(Addr.getPointer());
4887ec727ea7Spatrick 
4888ec727ea7Spatrick         if (!ArgInfo.getInAllocaIndirect()) {
4889ec727ea7Spatrick           // Replace the placeholder with the appropriate argument slot GEP.
4890e5dd7070Spatrick           CGBuilderTy::InsertPoint IP = Builder.saveIP();
4891e5dd7070Spatrick           Builder.SetInsertPoint(Placeholder);
4892ec727ea7Spatrick           Addr = Builder.CreateStructGEP(ArgMemory,
4893ec727ea7Spatrick                                          ArgInfo.getInAllocaFieldIndex());
4894e5dd7070Spatrick           Builder.restoreIP(IP);
4895ec727ea7Spatrick         } else {
4896ec727ea7Spatrick           // For indirect things such as overaligned structs, replace the
4897ec727ea7Spatrick           // placeholder with a regular aggregate temporary alloca. Store the
4898ec727ea7Spatrick           // address of this alloca into the struct.
4899ec727ea7Spatrick           Addr = CreateMemTemp(info_it->type, "inalloca.indirect.tmp");
4900ec727ea7Spatrick           Address ArgSlot = Builder.CreateStructGEP(
4901ec727ea7Spatrick               ArgMemory, ArgInfo.getInAllocaFieldIndex());
4902ec727ea7Spatrick           Builder.CreateStore(Addr.getPointer(), ArgSlot);
4903ec727ea7Spatrick         }
4904e5dd7070Spatrick         deferPlaceholderReplacement(Placeholder, Addr.getPointer());
4905ec727ea7Spatrick       } else if (ArgInfo.getInAllocaIndirect()) {
4906ec727ea7Spatrick         // Make a temporary alloca and store the address of it into the argument
4907ec727ea7Spatrick         // struct.
4908ec727ea7Spatrick         Address Addr = CreateMemTempWithoutCast(
4909ec727ea7Spatrick             I->Ty, getContext().getTypeAlignInChars(I->Ty),
4910ec727ea7Spatrick             "indirect-arg-temp");
4911ec727ea7Spatrick         I->copyInto(*this, Addr);
4912ec727ea7Spatrick         Address ArgSlot =
4913ec727ea7Spatrick             Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
4914ec727ea7Spatrick         Builder.CreateStore(Addr.getPointer(), ArgSlot);
4915e5dd7070Spatrick       } else {
4916e5dd7070Spatrick         // Store the RValue into the argument struct.
4917e5dd7070Spatrick         Address Addr =
4918e5dd7070Spatrick             Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
4919e5dd7070Spatrick         // There are some cases where a trivial bitcast is not avoidable.  The
4920e5dd7070Spatrick         // definition of a type later in a translation unit may change it's type
4921e5dd7070Spatrick         // from {}* to (%struct.foo*)*.
4922*7a9b00ceSrobert         Addr = Builder.CreateElementBitCast(Addr, ConvertTypeForMem(I->Ty));
4923e5dd7070Spatrick         I->copyInto(*this, Addr);
4924e5dd7070Spatrick       }
4925e5dd7070Spatrick       break;
4926e5dd7070Spatrick     }
4927e5dd7070Spatrick 
4928a0747c9fSpatrick     case ABIArgInfo::Indirect:
4929a0747c9fSpatrick     case ABIArgInfo::IndirectAliased: {
4930e5dd7070Spatrick       assert(NumIRArgs == 1);
4931e5dd7070Spatrick       if (!I->isAggregate()) {
4932e5dd7070Spatrick         // Make a temporary alloca to pass the argument.
4933e5dd7070Spatrick         Address Addr = CreateMemTempWithoutCast(
4934e5dd7070Spatrick             I->Ty, ArgInfo.getIndirectAlign(), "indirect-arg-temp");
4935*7a9b00ceSrobert 
4936*7a9b00ceSrobert         llvm::Value *Val = Addr.getPointer();
4937*7a9b00ceSrobert         if (ArgHasMaybeUndefAttr)
4938*7a9b00ceSrobert           Val = Builder.CreateFreeze(Addr.getPointer());
4939*7a9b00ceSrobert         IRCallArgs[FirstIRArg] = Val;
4940e5dd7070Spatrick 
4941e5dd7070Spatrick         I->copyInto(*this, Addr);
4942e5dd7070Spatrick       } else {
4943e5dd7070Spatrick         // We want to avoid creating an unnecessary temporary+copy here;
4944e5dd7070Spatrick         // however, we need one in three cases:
4945e5dd7070Spatrick         // 1. If the argument is not byval, and we are required to copy the
4946e5dd7070Spatrick         //    source.  (This case doesn't occur on any common architecture.)
4947e5dd7070Spatrick         // 2. If the argument is byval, RV is not sufficiently aligned, and
4948e5dd7070Spatrick         //    we cannot force it to be sufficiently aligned.
4949e5dd7070Spatrick         // 3. If the argument is byval, but RV is not located in default
4950e5dd7070Spatrick         //    or alloca address space.
4951e5dd7070Spatrick         Address Addr = I->hasLValue()
4952e5dd7070Spatrick                            ? I->getKnownLValue().getAddress(*this)
4953e5dd7070Spatrick                            : I->getKnownRValue().getAggregateAddress();
4954e5dd7070Spatrick         llvm::Value *V = Addr.getPointer();
4955e5dd7070Spatrick         CharUnits Align = ArgInfo.getIndirectAlign();
4956e5dd7070Spatrick         const llvm::DataLayout *TD = &CGM.getDataLayout();
4957e5dd7070Spatrick 
4958e5dd7070Spatrick         assert((FirstIRArg >= IRFuncTy->getNumParams() ||
4959e5dd7070Spatrick                 IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() ==
4960e5dd7070Spatrick                     TD->getAllocaAddrSpace()) &&
4961e5dd7070Spatrick                "indirect argument must be in alloca address space");
4962e5dd7070Spatrick 
4963e5dd7070Spatrick         bool NeedCopy = false;
4964e5dd7070Spatrick 
4965e5dd7070Spatrick         if (Addr.getAlignment() < Align &&
4966ec727ea7Spatrick             llvm::getOrEnforceKnownAlignment(V, Align.getAsAlign(), *TD) <
4967ec727ea7Spatrick                 Align.getAsAlign()) {
4968e5dd7070Spatrick           NeedCopy = true;
4969e5dd7070Spatrick         } else if (I->hasLValue()) {
4970e5dd7070Spatrick           auto LV = I->getKnownLValue();
4971e5dd7070Spatrick           auto AS = LV.getAddressSpace();
4972e5dd7070Spatrick 
4973e5dd7070Spatrick           if (!ArgInfo.getIndirectByVal() ||
4974e5dd7070Spatrick               (LV.getAlignment() < getContext().getTypeAlignInChars(I->Ty))) {
4975e5dd7070Spatrick             NeedCopy = true;
4976e5dd7070Spatrick           }
4977e5dd7070Spatrick           if (!getLangOpts().OpenCL) {
4978e5dd7070Spatrick             if ((ArgInfo.getIndirectByVal() &&
4979e5dd7070Spatrick                 (AS != LangAS::Default &&
4980e5dd7070Spatrick                  AS != CGM.getASTAllocaAddressSpace()))) {
4981e5dd7070Spatrick               NeedCopy = true;
4982e5dd7070Spatrick             }
4983e5dd7070Spatrick           }
4984e5dd7070Spatrick           // For OpenCL even if RV is located in default or alloca address space
4985e5dd7070Spatrick           // we don't want to perform address space cast for it.
4986e5dd7070Spatrick           else if ((ArgInfo.getIndirectByVal() &&
4987e5dd7070Spatrick                     Addr.getType()->getAddressSpace() != IRFuncTy->
4988e5dd7070Spatrick                       getParamType(FirstIRArg)->getPointerAddressSpace())) {
4989e5dd7070Spatrick             NeedCopy = true;
4990e5dd7070Spatrick           }
4991e5dd7070Spatrick         }
4992e5dd7070Spatrick 
4993e5dd7070Spatrick         if (NeedCopy) {
4994e5dd7070Spatrick           // Create an aligned temporary, and copy to it.
4995e5dd7070Spatrick           Address AI = CreateMemTempWithoutCast(
4996e5dd7070Spatrick               I->Ty, ArgInfo.getIndirectAlign(), "byval-temp");
4997*7a9b00ceSrobert           llvm::Value *Val = AI.getPointer();
4998*7a9b00ceSrobert           if (ArgHasMaybeUndefAttr)
4999*7a9b00ceSrobert             Val = Builder.CreateFreeze(AI.getPointer());
5000*7a9b00ceSrobert           IRCallArgs[FirstIRArg] = Val;
5001e5dd7070Spatrick 
5002e5dd7070Spatrick           // Emit lifetime markers for the temporary alloca.
5003a0747c9fSpatrick           llvm::TypeSize ByvalTempElementSize =
5004e5dd7070Spatrick               CGM.getDataLayout().getTypeAllocSize(AI.getElementType());
5005e5dd7070Spatrick           llvm::Value *LifetimeSize =
5006e5dd7070Spatrick               EmitLifetimeStart(ByvalTempElementSize, AI.getPointer());
5007e5dd7070Spatrick 
5008e5dd7070Spatrick           // Add cleanup code to emit the end lifetime marker after the call.
5009e5dd7070Spatrick           if (LifetimeSize) // In case we disabled lifetime markers.
5010e5dd7070Spatrick             CallLifetimeEndAfterCall.emplace_back(AI, LifetimeSize);
5011e5dd7070Spatrick 
5012e5dd7070Spatrick           // Generate the copy.
5013e5dd7070Spatrick           I->copyInto(*this, AI);
5014e5dd7070Spatrick         } else {
5015e5dd7070Spatrick           // Skip the extra memcpy call.
5016*7a9b00ceSrobert           auto *T = llvm::PointerType::getWithSamePointeeType(
5017*7a9b00ceSrobert               cast<llvm::PointerType>(V->getType()),
5018e5dd7070Spatrick               CGM.getDataLayout().getAllocaAddrSpace());
5019*7a9b00ceSrobert 
5020*7a9b00ceSrobert           llvm::Value *Val = getTargetHooks().performAddrSpaceCast(
5021e5dd7070Spatrick               *this, V, LangAS::Default, CGM.getASTAllocaAddressSpace(), T,
5022e5dd7070Spatrick               true);
5023*7a9b00ceSrobert           if (ArgHasMaybeUndefAttr)
5024*7a9b00ceSrobert             Val = Builder.CreateFreeze(Val);
5025*7a9b00ceSrobert           IRCallArgs[FirstIRArg] = Val;
5026e5dd7070Spatrick         }
5027e5dd7070Spatrick       }
5028e5dd7070Spatrick       break;
5029e5dd7070Spatrick     }
5030e5dd7070Spatrick 
5031e5dd7070Spatrick     case ABIArgInfo::Ignore:
5032e5dd7070Spatrick       assert(NumIRArgs == 0);
5033e5dd7070Spatrick       break;
5034e5dd7070Spatrick 
5035e5dd7070Spatrick     case ABIArgInfo::Extend:
5036e5dd7070Spatrick     case ABIArgInfo::Direct: {
5037e5dd7070Spatrick       if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
5038e5dd7070Spatrick           ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
5039e5dd7070Spatrick           ArgInfo.getDirectOffset() == 0) {
5040e5dd7070Spatrick         assert(NumIRArgs == 1);
5041e5dd7070Spatrick         llvm::Value *V;
5042e5dd7070Spatrick         if (!I->isAggregate())
5043e5dd7070Spatrick           V = I->getKnownRValue().getScalarVal();
5044e5dd7070Spatrick         else
5045e5dd7070Spatrick           V = Builder.CreateLoad(
5046e5dd7070Spatrick               I->hasLValue() ? I->getKnownLValue().getAddress(*this)
5047e5dd7070Spatrick                              : I->getKnownRValue().getAggregateAddress());
5048e5dd7070Spatrick 
5049e5dd7070Spatrick         // Implement swifterror by copying into a new swifterror argument.
5050e5dd7070Spatrick         // We'll write back in the normal path out of the call.
5051e5dd7070Spatrick         if (CallInfo.getExtParameterInfo(ArgNo).getABI()
5052e5dd7070Spatrick               == ParameterABI::SwiftErrorResult) {
5053e5dd7070Spatrick           assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
5054e5dd7070Spatrick 
5055e5dd7070Spatrick           QualType pointeeTy = I->Ty->getPointeeType();
5056*7a9b00ceSrobert           swiftErrorArg = Address(V, ConvertTypeForMem(pointeeTy),
5057*7a9b00ceSrobert                                   getContext().getTypeAlignInChars(pointeeTy));
5058e5dd7070Spatrick 
5059e5dd7070Spatrick           swiftErrorTemp =
5060e5dd7070Spatrick             CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
5061e5dd7070Spatrick           V = swiftErrorTemp.getPointer();
5062e5dd7070Spatrick           cast<llvm::AllocaInst>(V)->setSwiftError(true);
5063e5dd7070Spatrick 
5064e5dd7070Spatrick           llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
5065e5dd7070Spatrick           Builder.CreateStore(errorValue, swiftErrorTemp);
5066e5dd7070Spatrick         }
5067e5dd7070Spatrick 
5068e5dd7070Spatrick         // We might have to widen integers, but we should never truncate.
5069e5dd7070Spatrick         if (ArgInfo.getCoerceToType() != V->getType() &&
5070e5dd7070Spatrick             V->getType()->isIntegerTy())
5071e5dd7070Spatrick           V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
5072e5dd7070Spatrick 
5073e5dd7070Spatrick         // If the argument doesn't match, perform a bitcast to coerce it.  This
5074e5dd7070Spatrick         // can happen due to trivial type mismatches.
5075e5dd7070Spatrick         if (FirstIRArg < IRFuncTy->getNumParams() &&
5076e5dd7070Spatrick             V->getType() != IRFuncTy->getParamType(FirstIRArg))
5077e5dd7070Spatrick           V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
5078e5dd7070Spatrick 
5079*7a9b00ceSrobert         if (ArgHasMaybeUndefAttr)
5080*7a9b00ceSrobert           V = Builder.CreateFreeze(V);
5081e5dd7070Spatrick         IRCallArgs[FirstIRArg] = V;
5082e5dd7070Spatrick         break;
5083e5dd7070Spatrick       }
5084e5dd7070Spatrick 
5085e5dd7070Spatrick       // FIXME: Avoid the conversion through memory if possible.
5086e5dd7070Spatrick       Address Src = Address::invalid();
5087e5dd7070Spatrick       if (!I->isAggregate()) {
5088e5dd7070Spatrick         Src = CreateMemTemp(I->Ty, "coerce");
5089e5dd7070Spatrick         I->copyInto(*this, Src);
5090e5dd7070Spatrick       } else {
5091e5dd7070Spatrick         Src = I->hasLValue() ? I->getKnownLValue().getAddress(*this)
5092e5dd7070Spatrick                              : I->getKnownRValue().getAggregateAddress();
5093e5dd7070Spatrick       }
5094e5dd7070Spatrick 
5095e5dd7070Spatrick       // If the value is offset in memory, apply the offset now.
5096e5dd7070Spatrick       Src = emitAddressAtOffset(*this, Src, ArgInfo);
5097e5dd7070Spatrick 
5098e5dd7070Spatrick       // Fast-isel and the optimizer generally like scalar values better than
5099e5dd7070Spatrick       // FCAs, so we flatten them if this is safe to do for this argument.
5100e5dd7070Spatrick       llvm::StructType *STy =
5101e5dd7070Spatrick             dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
5102e5dd7070Spatrick       if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
5103ec727ea7Spatrick         llvm::Type *SrcTy = Src.getElementType();
5104e5dd7070Spatrick         uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
5105e5dd7070Spatrick         uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
5106e5dd7070Spatrick 
5107e5dd7070Spatrick         // If the source type is smaller than the destination type of the
5108e5dd7070Spatrick         // coerce-to logic, copy the source value into a temp alloca the size
5109e5dd7070Spatrick         // of the destination type to allow loading all of it. The bits past
5110e5dd7070Spatrick         // the source value are left undef.
5111e5dd7070Spatrick         if (SrcSize < DstSize) {
5112e5dd7070Spatrick           Address TempAlloca
5113e5dd7070Spatrick             = CreateTempAlloca(STy, Src.getAlignment(),
5114e5dd7070Spatrick                                Src.getName() + ".coerce");
5115e5dd7070Spatrick           Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
5116e5dd7070Spatrick           Src = TempAlloca;
5117e5dd7070Spatrick         } else {
5118*7a9b00ceSrobert           Src = Builder.CreateElementBitCast(Src, STy);
5119e5dd7070Spatrick         }
5120e5dd7070Spatrick 
5121e5dd7070Spatrick         assert(NumIRArgs == STy->getNumElements());
5122e5dd7070Spatrick         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
5123e5dd7070Spatrick           Address EltPtr = Builder.CreateStructGEP(Src, i);
5124e5dd7070Spatrick           llvm::Value *LI = Builder.CreateLoad(EltPtr);
5125*7a9b00ceSrobert           if (ArgHasMaybeUndefAttr)
5126*7a9b00ceSrobert             LI = Builder.CreateFreeze(LI);
5127e5dd7070Spatrick           IRCallArgs[FirstIRArg + i] = LI;
5128e5dd7070Spatrick         }
5129e5dd7070Spatrick       } else {
5130e5dd7070Spatrick         // In the simple case, just pass the coerced loaded value.
5131e5dd7070Spatrick         assert(NumIRArgs == 1);
5132ec727ea7Spatrick         llvm::Value *Load =
5133e5dd7070Spatrick             CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
5134ec727ea7Spatrick 
5135ec727ea7Spatrick         if (CallInfo.isCmseNSCall()) {
5136ec727ea7Spatrick           // For certain parameter types, clear padding bits, as they may reveal
5137ec727ea7Spatrick           // sensitive information.
5138ec727ea7Spatrick           // Small struct/union types are passed as integer arrays.
5139ec727ea7Spatrick           auto *ATy = dyn_cast<llvm::ArrayType>(Load->getType());
5140ec727ea7Spatrick           if (ATy != nullptr && isa<RecordType>(I->Ty.getCanonicalType()))
5141ec727ea7Spatrick             Load = EmitCMSEClearRecord(Load, ATy, I->Ty);
5142ec727ea7Spatrick         }
5143*7a9b00ceSrobert 
5144*7a9b00ceSrobert         if (ArgHasMaybeUndefAttr)
5145*7a9b00ceSrobert           Load = Builder.CreateFreeze(Load);
5146ec727ea7Spatrick         IRCallArgs[FirstIRArg] = Load;
5147e5dd7070Spatrick       }
5148e5dd7070Spatrick 
5149e5dd7070Spatrick       break;
5150e5dd7070Spatrick     }
5151e5dd7070Spatrick 
5152e5dd7070Spatrick     case ABIArgInfo::CoerceAndExpand: {
5153e5dd7070Spatrick       auto coercionType = ArgInfo.getCoerceAndExpandType();
5154e5dd7070Spatrick       auto layout = CGM.getDataLayout().getStructLayout(coercionType);
5155e5dd7070Spatrick 
5156e5dd7070Spatrick       llvm::Value *tempSize = nullptr;
5157e5dd7070Spatrick       Address addr = Address::invalid();
5158e5dd7070Spatrick       Address AllocaAddr = Address::invalid();
5159e5dd7070Spatrick       if (I->isAggregate()) {
5160e5dd7070Spatrick         addr = I->hasLValue() ? I->getKnownLValue().getAddress(*this)
5161e5dd7070Spatrick                               : I->getKnownRValue().getAggregateAddress();
5162e5dd7070Spatrick 
5163e5dd7070Spatrick       } else {
5164e5dd7070Spatrick         RValue RV = I->getKnownRValue();
5165e5dd7070Spatrick         assert(RV.isScalar()); // complex should always just be direct
5166e5dd7070Spatrick 
5167e5dd7070Spatrick         llvm::Type *scalarType = RV.getScalarVal()->getType();
5168e5dd7070Spatrick         auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
5169*7a9b00ceSrobert         auto scalarAlign = CGM.getDataLayout().getPrefTypeAlign(scalarType);
5170e5dd7070Spatrick 
5171e5dd7070Spatrick         // Materialize to a temporary.
5172e5dd7070Spatrick         addr = CreateTempAlloca(
5173e5dd7070Spatrick             RV.getScalarVal()->getType(),
5174*7a9b00ceSrobert             CharUnits::fromQuantity(std::max(layout->getAlignment(), scalarAlign)),
5175e5dd7070Spatrick             "tmp",
5176e5dd7070Spatrick             /*ArraySize=*/nullptr, &AllocaAddr);
5177e5dd7070Spatrick         tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer());
5178e5dd7070Spatrick 
5179e5dd7070Spatrick         Builder.CreateStore(RV.getScalarVal(), addr);
5180e5dd7070Spatrick       }
5181e5dd7070Spatrick 
5182e5dd7070Spatrick       addr = Builder.CreateElementBitCast(addr, coercionType);
5183e5dd7070Spatrick 
5184e5dd7070Spatrick       unsigned IRArgPos = FirstIRArg;
5185e5dd7070Spatrick       for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
5186e5dd7070Spatrick         llvm::Type *eltType = coercionType->getElementType(i);
5187e5dd7070Spatrick         if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
5188e5dd7070Spatrick         Address eltAddr = Builder.CreateStructGEP(addr, i);
5189e5dd7070Spatrick         llvm::Value *elt = Builder.CreateLoad(eltAddr);
5190*7a9b00ceSrobert         if (ArgHasMaybeUndefAttr)
5191*7a9b00ceSrobert           elt = Builder.CreateFreeze(elt);
5192e5dd7070Spatrick         IRCallArgs[IRArgPos++] = elt;
5193e5dd7070Spatrick       }
5194e5dd7070Spatrick       assert(IRArgPos == FirstIRArg + NumIRArgs);
5195e5dd7070Spatrick 
5196e5dd7070Spatrick       if (tempSize) {
5197e5dd7070Spatrick         EmitLifetimeEnd(tempSize, AllocaAddr.getPointer());
5198e5dd7070Spatrick       }
5199e5dd7070Spatrick 
5200e5dd7070Spatrick       break;
5201e5dd7070Spatrick     }
5202e5dd7070Spatrick 
5203a0747c9fSpatrick     case ABIArgInfo::Expand: {
5204e5dd7070Spatrick       unsigned IRArgPos = FirstIRArg;
5205e5dd7070Spatrick       ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos);
5206e5dd7070Spatrick       assert(IRArgPos == FirstIRArg + NumIRArgs);
5207e5dd7070Spatrick       break;
5208e5dd7070Spatrick     }
5209e5dd7070Spatrick     }
5210a0747c9fSpatrick   }
5211e5dd7070Spatrick 
5212e5dd7070Spatrick   const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this);
5213e5dd7070Spatrick   llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer();
5214e5dd7070Spatrick 
5215e5dd7070Spatrick   // If we're using inalloca, set up that argument.
5216e5dd7070Spatrick   if (ArgMemory.isValid()) {
5217e5dd7070Spatrick     llvm::Value *Arg = ArgMemory.getPointer();
5218e5dd7070Spatrick     if (CallInfo.isVariadic()) {
5219e5dd7070Spatrick       // When passing non-POD arguments by value to variadic functions, we will
5220e5dd7070Spatrick       // end up with a variadic prototype and an inalloca call site.  In such
5221e5dd7070Spatrick       // cases, we can't do any parameter mismatch checks.  Give up and bitcast
5222e5dd7070Spatrick       // the callee.
5223e5dd7070Spatrick       unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace();
5224e5dd7070Spatrick       CalleePtr =
5225e5dd7070Spatrick           Builder.CreateBitCast(CalleePtr, IRFuncTy->getPointerTo(CalleeAS));
5226e5dd7070Spatrick     } else {
5227e5dd7070Spatrick       llvm::Type *LastParamTy =
5228e5dd7070Spatrick           IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
5229e5dd7070Spatrick       if (Arg->getType() != LastParamTy) {
5230e5dd7070Spatrick #ifndef NDEBUG
5231e5dd7070Spatrick         // Assert that these structs have equivalent element types.
5232e5dd7070Spatrick         llvm::StructType *FullTy = CallInfo.getArgStruct();
5233*7a9b00ceSrobert         if (!LastParamTy->isOpaquePointerTy()) {
5234e5dd7070Spatrick           llvm::StructType *DeclaredTy = cast<llvm::StructType>(
5235*7a9b00ceSrobert               LastParamTy->getNonOpaquePointerElementType());
5236e5dd7070Spatrick           assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
5237*7a9b00ceSrobert           for (auto DI = DeclaredTy->element_begin(),
5238e5dd7070Spatrick                     DE = DeclaredTy->element_end(),
5239e5dd7070Spatrick                     FI = FullTy->element_begin();
5240e5dd7070Spatrick                DI != DE; ++DI, ++FI)
5241e5dd7070Spatrick             assert(*DI == *FI);
5242*7a9b00ceSrobert         }
5243e5dd7070Spatrick #endif
5244e5dd7070Spatrick         Arg = Builder.CreateBitCast(Arg, LastParamTy);
5245e5dd7070Spatrick       }
5246e5dd7070Spatrick     }
5247e5dd7070Spatrick     assert(IRFunctionArgs.hasInallocaArg());
5248e5dd7070Spatrick     IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
5249e5dd7070Spatrick   }
5250e5dd7070Spatrick 
5251e5dd7070Spatrick   // 2. Prepare the function pointer.
5252e5dd7070Spatrick 
5253e5dd7070Spatrick   // If the callee is a bitcast of a non-variadic function to have a
5254e5dd7070Spatrick   // variadic function pointer type, check to see if we can remove the
5255e5dd7070Spatrick   // bitcast.  This comes up with unprototyped functions.
5256e5dd7070Spatrick   //
5257e5dd7070Spatrick   // This makes the IR nicer, but more importantly it ensures that we
5258e5dd7070Spatrick   // can inline the function at -O0 if it is marked always_inline.
5259e5dd7070Spatrick   auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT,
5260e5dd7070Spatrick                                    llvm::Value *Ptr) -> llvm::Function * {
5261e5dd7070Spatrick     if (!CalleeFT->isVarArg())
5262e5dd7070Spatrick       return nullptr;
5263e5dd7070Spatrick 
5264e5dd7070Spatrick     // Get underlying value if it's a bitcast
5265e5dd7070Spatrick     if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) {
5266e5dd7070Spatrick       if (CE->getOpcode() == llvm::Instruction::BitCast)
5267e5dd7070Spatrick         Ptr = CE->getOperand(0);
5268e5dd7070Spatrick     }
5269e5dd7070Spatrick 
5270e5dd7070Spatrick     llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr);
5271e5dd7070Spatrick     if (!OrigFn)
5272e5dd7070Spatrick       return nullptr;
5273e5dd7070Spatrick 
5274e5dd7070Spatrick     llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
5275e5dd7070Spatrick 
5276e5dd7070Spatrick     // If the original type is variadic, or if any of the component types
5277e5dd7070Spatrick     // disagree, we cannot remove the cast.
5278e5dd7070Spatrick     if (OrigFT->isVarArg() ||
5279e5dd7070Spatrick         OrigFT->getNumParams() != CalleeFT->getNumParams() ||
5280e5dd7070Spatrick         OrigFT->getReturnType() != CalleeFT->getReturnType())
5281e5dd7070Spatrick       return nullptr;
5282e5dd7070Spatrick 
5283e5dd7070Spatrick     for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
5284e5dd7070Spatrick       if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
5285e5dd7070Spatrick         return nullptr;
5286e5dd7070Spatrick 
5287e5dd7070Spatrick     return OrigFn;
5288e5dd7070Spatrick   };
5289e5dd7070Spatrick 
5290e5dd7070Spatrick   if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) {
5291e5dd7070Spatrick     CalleePtr = OrigFn;
5292e5dd7070Spatrick     IRFuncTy = OrigFn->getFunctionType();
5293e5dd7070Spatrick   }
5294e5dd7070Spatrick 
5295e5dd7070Spatrick   // 3. Perform the actual call.
5296e5dd7070Spatrick 
5297e5dd7070Spatrick   // Deactivate any cleanups that we're supposed to do immediately before
5298e5dd7070Spatrick   // the call.
5299e5dd7070Spatrick   if (!CallArgs.getCleanupsToDeactivate().empty())
5300e5dd7070Spatrick     deactivateArgCleanupsBeforeCall(*this, CallArgs);
5301e5dd7070Spatrick 
5302e5dd7070Spatrick   // Assert that the arguments we computed match up.  The IR verifier
5303e5dd7070Spatrick   // will catch this, but this is a common enough source of problems
5304e5dd7070Spatrick   // during IRGen changes that it's way better for debugging to catch
5305e5dd7070Spatrick   // it ourselves here.
5306e5dd7070Spatrick #ifndef NDEBUG
5307e5dd7070Spatrick   assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
5308e5dd7070Spatrick   for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
5309e5dd7070Spatrick     // Inalloca argument can have different type.
5310e5dd7070Spatrick     if (IRFunctionArgs.hasInallocaArg() &&
5311e5dd7070Spatrick         i == IRFunctionArgs.getInallocaArgNo())
5312e5dd7070Spatrick       continue;
5313e5dd7070Spatrick     if (i < IRFuncTy->getNumParams())
5314e5dd7070Spatrick       assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
5315e5dd7070Spatrick   }
5316e5dd7070Spatrick #endif
5317e5dd7070Spatrick 
5318e5dd7070Spatrick   // Update the largest vector width if any arguments have vector types.
5319*7a9b00ceSrobert   for (unsigned i = 0; i < IRCallArgs.size(); ++i)
5320*7a9b00ceSrobert     LargestVectorWidth = std::max(LargestVectorWidth,
5321*7a9b00ceSrobert                                   getMaxVectorWidth(IRCallArgs[i]->getType()));
5322e5dd7070Spatrick 
5323e5dd7070Spatrick   // Compute the calling convention and attributes.
5324e5dd7070Spatrick   unsigned CallingConv;
5325e5dd7070Spatrick   llvm::AttributeList Attrs;
5326e5dd7070Spatrick   CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
5327e5dd7070Spatrick                              Callee.getAbstractInfo(), Attrs, CallingConv,
5328a0747c9fSpatrick                              /*AttrOnCallSite=*/true,
5329a0747c9fSpatrick                              /*IsThunk=*/false);
5330e5dd7070Spatrick 
5331e5dd7070Spatrick   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
5332a0747c9fSpatrick     if (FD->hasAttr<StrictFPAttr>())
5333e5dd7070Spatrick       // All calls within a strictfp function are marked strictfp
5334*7a9b00ceSrobert       Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::StrictFP);
5335e5dd7070Spatrick 
5336ec727ea7Spatrick   // Add call-site nomerge attribute if exists.
5337ec727ea7Spatrick   if (InNoMergeAttributedStmt)
5338*7a9b00ceSrobert     Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoMerge);
5339*7a9b00ceSrobert 
5340*7a9b00ceSrobert   // Add call-site noinline attribute if exists.
5341*7a9b00ceSrobert   if (InNoInlineAttributedStmt)
5342*7a9b00ceSrobert     Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoInline);
5343*7a9b00ceSrobert 
5344*7a9b00ceSrobert   // Add call-site always_inline attribute if exists.
5345*7a9b00ceSrobert   if (InAlwaysInlineAttributedStmt)
5346ec727ea7Spatrick     Attrs =
5347*7a9b00ceSrobert         Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::AlwaysInline);
5348ec727ea7Spatrick 
5349e5dd7070Spatrick   // Apply some call-site-specific attributes.
5350e5dd7070Spatrick   // TODO: work this into building the attribute set.
5351e5dd7070Spatrick 
5352e5dd7070Spatrick   // Apply always_inline to all calls within flatten functions.
5353e5dd7070Spatrick   // FIXME: should this really take priority over __try, below?
5354e5dd7070Spatrick   if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
5355*7a9b00ceSrobert       !InNoInlineAttributedStmt &&
5356e5dd7070Spatrick       !(TargetDecl && TargetDecl->hasAttr<NoInlineAttr>())) {
5357e5dd7070Spatrick     Attrs =
5358*7a9b00ceSrobert         Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::AlwaysInline);
5359e5dd7070Spatrick   }
5360e5dd7070Spatrick 
5361e5dd7070Spatrick   // Disable inlining inside SEH __try blocks.
5362e5dd7070Spatrick   if (isSEHTryScope()) {
5363*7a9b00ceSrobert     Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoInline);
5364e5dd7070Spatrick   }
5365e5dd7070Spatrick 
5366e5dd7070Spatrick   // Decide whether to use a call or an invoke.
5367e5dd7070Spatrick   bool CannotThrow;
5368e5dd7070Spatrick   if (currentFunctionUsesSEHTry()) {
5369e5dd7070Spatrick     // SEH cares about asynchronous exceptions, so everything can "throw."
5370e5dd7070Spatrick     CannotThrow = false;
5371e5dd7070Spatrick   } else if (isCleanupPadScope() &&
5372e5dd7070Spatrick              EHPersonality::get(*this).isMSVCXXPersonality()) {
5373e5dd7070Spatrick     // The MSVC++ personality will implicitly terminate the program if an
5374e5dd7070Spatrick     // exception is thrown during a cleanup outside of a try/catch.
5375e5dd7070Spatrick     // We don't need to model anything in IR to get this behavior.
5376e5dd7070Spatrick     CannotThrow = true;
5377e5dd7070Spatrick   } else {
5378e5dd7070Spatrick     // Otherwise, nounwind call sites will never throw.
5379*7a9b00ceSrobert     CannotThrow = Attrs.hasFnAttr(llvm::Attribute::NoUnwind);
5380a0747c9fSpatrick 
5381a0747c9fSpatrick     if (auto *FPtr = dyn_cast<llvm::Function>(CalleePtr))
5382a0747c9fSpatrick       if (FPtr->hasFnAttribute(llvm::Attribute::NoUnwind))
5383a0747c9fSpatrick         CannotThrow = true;
5384e5dd7070Spatrick   }
5385e5dd7070Spatrick 
5386e5dd7070Spatrick   // If we made a temporary, be sure to clean up after ourselves. Note that we
5387e5dd7070Spatrick   // can't depend on being inside of an ExprWithCleanups, so we need to manually
5388e5dd7070Spatrick   // pop this cleanup later on. Being eager about this is OK, since this
5389e5dd7070Spatrick   // temporary is 'invisible' outside of the callee.
5390e5dd7070Spatrick   if (UnusedReturnSizePtr)
5391e5dd7070Spatrick     pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca,
5392e5dd7070Spatrick                                          UnusedReturnSizePtr);
5393e5dd7070Spatrick 
5394e5dd7070Spatrick   llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
5395e5dd7070Spatrick 
5396e5dd7070Spatrick   SmallVector<llvm::OperandBundleDef, 1> BundleList =
5397e5dd7070Spatrick       getBundlesForFunclet(CalleePtr);
5398e5dd7070Spatrick 
5399*7a9b00ceSrobert   if (SanOpts.has(SanitizerKind::KCFI) &&
5400*7a9b00ceSrobert       !isa_and_nonnull<FunctionDecl>(TargetDecl))
5401*7a9b00ceSrobert     EmitKCFIOperandBundle(ConcreteCallee, BundleList);
5402*7a9b00ceSrobert 
5403e5dd7070Spatrick   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
5404a0747c9fSpatrick     if (FD->hasAttr<StrictFPAttr>())
5405e5dd7070Spatrick       // All calls within a strictfp function are marked strictfp
5406*7a9b00ceSrobert       Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::StrictFP);
5407e5dd7070Spatrick 
5408ec727ea7Spatrick   AssumeAlignedAttrEmitter AssumeAlignedAttrEmitter(*this, TargetDecl);
5409ec727ea7Spatrick   Attrs = AssumeAlignedAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
5410ec727ea7Spatrick 
5411ec727ea7Spatrick   AllocAlignAttrEmitter AllocAlignAttrEmitter(*this, TargetDecl, CallArgs);
5412ec727ea7Spatrick   Attrs = AllocAlignAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
5413ec727ea7Spatrick 
5414e5dd7070Spatrick   // Emit the actual call/invoke instruction.
5415e5dd7070Spatrick   llvm::CallBase *CI;
5416e5dd7070Spatrick   if (!InvokeDest) {
5417e5dd7070Spatrick     CI = Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList);
5418e5dd7070Spatrick   } else {
5419e5dd7070Spatrick     llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
5420e5dd7070Spatrick     CI = Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs,
5421e5dd7070Spatrick                               BundleList);
5422e5dd7070Spatrick     EmitBlock(Cont);
5423e5dd7070Spatrick   }
5424e5dd7070Spatrick   if (callOrInvoke)
5425e5dd7070Spatrick     *callOrInvoke = CI;
5426e5dd7070Spatrick 
5427e5dd7070Spatrick   // If this is within a function that has the guard(nocf) attribute and is an
5428e5dd7070Spatrick   // indirect call, add the "guard_nocf" attribute to this call to indicate that
5429e5dd7070Spatrick   // Control Flow Guard checks should not be added, even if the call is inlined.
5430e5dd7070Spatrick   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
5431e5dd7070Spatrick     if (const auto *A = FD->getAttr<CFGuardAttr>()) {
5432e5dd7070Spatrick       if (A->getGuard() == CFGuardAttr::GuardArg::nocf && !CI->getCalledFunction())
5433*7a9b00ceSrobert         Attrs = Attrs.addFnAttribute(getLLVMContext(), "guard_nocf");
5434e5dd7070Spatrick     }
5435e5dd7070Spatrick   }
5436e5dd7070Spatrick 
5437e5dd7070Spatrick   // Apply the attributes and calling convention.
5438e5dd7070Spatrick   CI->setAttributes(Attrs);
5439e5dd7070Spatrick   CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
5440e5dd7070Spatrick 
5441e5dd7070Spatrick   // Apply various metadata.
5442e5dd7070Spatrick 
5443e5dd7070Spatrick   if (!CI->getType()->isVoidTy())
5444e5dd7070Spatrick     CI->setName("call");
5445e5dd7070Spatrick 
5446e5dd7070Spatrick   // Update largest vector width from the return type.
5447ec727ea7Spatrick   LargestVectorWidth =
5448*7a9b00ceSrobert       std::max(LargestVectorWidth, getMaxVectorWidth(CI->getType()));
5449e5dd7070Spatrick 
5450e5dd7070Spatrick   // Insert instrumentation or attach profile metadata at indirect call sites.
5451e5dd7070Spatrick   // For more details, see the comment before the definition of
5452e5dd7070Spatrick   // IPVK_IndirectCallTarget in InstrProfData.inc.
5453e5dd7070Spatrick   if (!CI->getCalledFunction())
5454e5dd7070Spatrick     PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
5455e5dd7070Spatrick                      CI, CalleePtr);
5456e5dd7070Spatrick 
5457e5dd7070Spatrick   // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
5458e5dd7070Spatrick   // optimizer it can aggressively ignore unwind edges.
5459e5dd7070Spatrick   if (CGM.getLangOpts().ObjCAutoRefCount)
5460e5dd7070Spatrick     AddObjCARCExceptionMetadata(CI);
5461e5dd7070Spatrick 
5462a0747c9fSpatrick   // Set tail call kind if necessary.
5463e5dd7070Spatrick   if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
5464e5dd7070Spatrick     if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
5465e5dd7070Spatrick       Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
5466a0747c9fSpatrick     else if (IsMustTail)
5467a0747c9fSpatrick       Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
5468e5dd7070Spatrick   }
5469e5dd7070Spatrick 
5470e5dd7070Spatrick   // Add metadata for calls to MSAllocator functions
5471e5dd7070Spatrick   if (getDebugInfo() && TargetDecl &&
5472e5dd7070Spatrick       TargetDecl->hasAttr<MSAllocatorAttr>())
5473ec727ea7Spatrick     getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy->getPointeeType(), Loc);
5474e5dd7070Spatrick 
5475*7a9b00ceSrobert   // Add metadata if calling an __attribute__((error(""))) or warning fn.
5476*7a9b00ceSrobert   if (TargetDecl && TargetDecl->hasAttr<ErrorAttr>()) {
5477*7a9b00ceSrobert     llvm::ConstantInt *Line =
5478*7a9b00ceSrobert         llvm::ConstantInt::get(Int32Ty, Loc.getRawEncoding());
5479*7a9b00ceSrobert     llvm::ConstantAsMetadata *MD = llvm::ConstantAsMetadata::get(Line);
5480*7a9b00ceSrobert     llvm::MDTuple *MDT = llvm::MDNode::get(getLLVMContext(), {MD});
5481*7a9b00ceSrobert     CI->setMetadata("srcloc", MDT);
5482*7a9b00ceSrobert   }
5483*7a9b00ceSrobert 
5484e5dd7070Spatrick   // 4. Finish the call.
5485e5dd7070Spatrick 
5486e5dd7070Spatrick   // If the call doesn't return, finish the basic block and clear the
5487e5dd7070Spatrick   // insertion point; this allows the rest of IRGen to discard
5488e5dd7070Spatrick   // unreachable code.
5489e5dd7070Spatrick   if (CI->doesNotReturn()) {
5490e5dd7070Spatrick     if (UnusedReturnSizePtr)
5491e5dd7070Spatrick       PopCleanupBlock();
5492e5dd7070Spatrick 
5493e5dd7070Spatrick     // Strip away the noreturn attribute to better diagnose unreachable UB.
5494e5dd7070Spatrick     if (SanOpts.has(SanitizerKind::Unreachable)) {
5495e5dd7070Spatrick       // Also remove from function since CallBase::hasFnAttr additionally checks
5496e5dd7070Spatrick       // attributes of the called function.
5497e5dd7070Spatrick       if (auto *F = CI->getCalledFunction())
5498e5dd7070Spatrick         F->removeFnAttr(llvm::Attribute::NoReturn);
5499*7a9b00ceSrobert       CI->removeFnAttr(llvm::Attribute::NoReturn);
5500e5dd7070Spatrick 
5501e5dd7070Spatrick       // Avoid incompatibility with ASan which relies on the `noreturn`
5502e5dd7070Spatrick       // attribute to insert handler calls.
5503e5dd7070Spatrick       if (SanOpts.hasOneOf(SanitizerKind::Address |
5504e5dd7070Spatrick                            SanitizerKind::KernelAddress)) {
5505e5dd7070Spatrick         SanitizerScope SanScope(this);
5506e5dd7070Spatrick         llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder);
5507e5dd7070Spatrick         Builder.SetInsertPoint(CI);
5508e5dd7070Spatrick         auto *FnType = llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
5509e5dd7070Spatrick         llvm::FunctionCallee Fn =
5510e5dd7070Spatrick             CGM.CreateRuntimeFunction(FnType, "__asan_handle_no_return");
5511e5dd7070Spatrick         EmitNounwindRuntimeCall(Fn);
5512e5dd7070Spatrick       }
5513e5dd7070Spatrick     }
5514e5dd7070Spatrick 
5515e5dd7070Spatrick     EmitUnreachable(Loc);
5516e5dd7070Spatrick     Builder.ClearInsertionPoint();
5517e5dd7070Spatrick 
5518e5dd7070Spatrick     // FIXME: For now, emit a dummy basic block because expr emitters in
5519e5dd7070Spatrick     // generally are not ready to handle emitting expressions at unreachable
5520e5dd7070Spatrick     // points.
5521e5dd7070Spatrick     EnsureInsertPoint();
5522e5dd7070Spatrick 
5523e5dd7070Spatrick     // Return a reasonable RValue.
5524e5dd7070Spatrick     return GetUndefRValue(RetTy);
5525e5dd7070Spatrick   }
5526e5dd7070Spatrick 
5527a0747c9fSpatrick   // If this is a musttail call, return immediately. We do not branch to the
5528a0747c9fSpatrick   // epilogue in this case.
5529a0747c9fSpatrick   if (IsMustTail) {
5530a0747c9fSpatrick     for (auto it = EHStack.find(CurrentCleanupScopeDepth); it != EHStack.end();
5531a0747c9fSpatrick          ++it) {
5532a0747c9fSpatrick       EHCleanupScope *Cleanup = dyn_cast<EHCleanupScope>(&*it);
5533a0747c9fSpatrick       if (!(Cleanup && Cleanup->getCleanup()->isRedundantBeforeReturn()))
5534a0747c9fSpatrick         CGM.ErrorUnsupported(MustTailCall, "tail call skipping over cleanups");
5535a0747c9fSpatrick     }
5536a0747c9fSpatrick     if (CI->getType()->isVoidTy())
5537a0747c9fSpatrick       Builder.CreateRetVoid();
5538a0747c9fSpatrick     else
5539a0747c9fSpatrick       Builder.CreateRet(CI);
5540a0747c9fSpatrick     Builder.ClearInsertionPoint();
5541a0747c9fSpatrick     EnsureInsertPoint();
5542a0747c9fSpatrick     return GetUndefRValue(RetTy);
5543a0747c9fSpatrick   }
5544a0747c9fSpatrick 
5545e5dd7070Spatrick   // Perform the swifterror writeback.
5546e5dd7070Spatrick   if (swiftErrorTemp.isValid()) {
5547e5dd7070Spatrick     llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
5548e5dd7070Spatrick     Builder.CreateStore(errorResult, swiftErrorArg);
5549e5dd7070Spatrick   }
5550e5dd7070Spatrick 
5551e5dd7070Spatrick   // Emit any call-associated writebacks immediately.  Arguably this
5552e5dd7070Spatrick   // should happen after any return-value munging.
5553e5dd7070Spatrick   if (CallArgs.hasWritebacks())
5554e5dd7070Spatrick     emitWritebacks(*this, CallArgs);
5555e5dd7070Spatrick 
5556e5dd7070Spatrick   // The stack cleanup for inalloca arguments has to run out of the normal
5557e5dd7070Spatrick   // lexical order, so deactivate it and run it manually here.
5558e5dd7070Spatrick   CallArgs.freeArgumentMemory(*this);
5559e5dd7070Spatrick 
5560e5dd7070Spatrick   // Extract the return value.
5561e5dd7070Spatrick   RValue Ret = [&] {
5562e5dd7070Spatrick     switch (RetAI.getKind()) {
5563e5dd7070Spatrick     case ABIArgInfo::CoerceAndExpand: {
5564e5dd7070Spatrick       auto coercionType = RetAI.getCoerceAndExpandType();
5565e5dd7070Spatrick 
5566e5dd7070Spatrick       Address addr = SRetPtr;
5567e5dd7070Spatrick       addr = Builder.CreateElementBitCast(addr, coercionType);
5568e5dd7070Spatrick 
5569e5dd7070Spatrick       assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
5570e5dd7070Spatrick       bool requiresExtract = isa<llvm::StructType>(CI->getType());
5571e5dd7070Spatrick 
5572e5dd7070Spatrick       unsigned unpaddedIndex = 0;
5573e5dd7070Spatrick       for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
5574e5dd7070Spatrick         llvm::Type *eltType = coercionType->getElementType(i);
5575e5dd7070Spatrick         if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
5576e5dd7070Spatrick         Address eltAddr = Builder.CreateStructGEP(addr, i);
5577e5dd7070Spatrick         llvm::Value *elt = CI;
5578e5dd7070Spatrick         if (requiresExtract)
5579e5dd7070Spatrick           elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
5580e5dd7070Spatrick         else
5581e5dd7070Spatrick           assert(unpaddedIndex == 0);
5582e5dd7070Spatrick         Builder.CreateStore(elt, eltAddr);
5583e5dd7070Spatrick       }
5584e5dd7070Spatrick       // FALLTHROUGH
5585*7a9b00ceSrobert       [[fallthrough]];
5586e5dd7070Spatrick     }
5587e5dd7070Spatrick 
5588e5dd7070Spatrick     case ABIArgInfo::InAlloca:
5589e5dd7070Spatrick     case ABIArgInfo::Indirect: {
5590e5dd7070Spatrick       RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
5591e5dd7070Spatrick       if (UnusedReturnSizePtr)
5592e5dd7070Spatrick         PopCleanupBlock();
5593e5dd7070Spatrick       return ret;
5594e5dd7070Spatrick     }
5595e5dd7070Spatrick 
5596e5dd7070Spatrick     case ABIArgInfo::Ignore:
5597e5dd7070Spatrick       // If we are ignoring an argument that had a result, make sure to
5598e5dd7070Spatrick       // construct the appropriate return value for our caller.
5599e5dd7070Spatrick       return GetUndefRValue(RetTy);
5600e5dd7070Spatrick 
5601e5dd7070Spatrick     case ABIArgInfo::Extend:
5602e5dd7070Spatrick     case ABIArgInfo::Direct: {
5603e5dd7070Spatrick       llvm::Type *RetIRTy = ConvertType(RetTy);
5604e5dd7070Spatrick       if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
5605e5dd7070Spatrick         switch (getEvaluationKind(RetTy)) {
5606e5dd7070Spatrick         case TEK_Complex: {
5607e5dd7070Spatrick           llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
5608e5dd7070Spatrick           llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
5609e5dd7070Spatrick           return RValue::getComplex(std::make_pair(Real, Imag));
5610e5dd7070Spatrick         }
5611e5dd7070Spatrick         case TEK_Aggregate: {
5612e5dd7070Spatrick           Address DestPtr = ReturnValue.getValue();
5613e5dd7070Spatrick           bool DestIsVolatile = ReturnValue.isVolatile();
5614e5dd7070Spatrick 
5615e5dd7070Spatrick           if (!DestPtr.isValid()) {
5616e5dd7070Spatrick             DestPtr = CreateMemTemp(RetTy, "agg.tmp");
5617e5dd7070Spatrick             DestIsVolatile = false;
5618e5dd7070Spatrick           }
5619ec727ea7Spatrick           EmitAggregateStore(CI, DestPtr, DestIsVolatile);
5620e5dd7070Spatrick           return RValue::getAggregate(DestPtr);
5621e5dd7070Spatrick         }
5622e5dd7070Spatrick         case TEK_Scalar: {
5623e5dd7070Spatrick           // If the argument doesn't match, perform a bitcast to coerce it.  This
5624e5dd7070Spatrick           // can happen due to trivial type mismatches.
5625e5dd7070Spatrick           llvm::Value *V = CI;
5626e5dd7070Spatrick           if (V->getType() != RetIRTy)
5627e5dd7070Spatrick             V = Builder.CreateBitCast(V, RetIRTy);
5628e5dd7070Spatrick           return RValue::get(V);
5629e5dd7070Spatrick         }
5630e5dd7070Spatrick         }
5631e5dd7070Spatrick         llvm_unreachable("bad evaluation kind");
5632e5dd7070Spatrick       }
5633e5dd7070Spatrick 
5634e5dd7070Spatrick       Address DestPtr = ReturnValue.getValue();
5635e5dd7070Spatrick       bool DestIsVolatile = ReturnValue.isVolatile();
5636e5dd7070Spatrick 
5637e5dd7070Spatrick       if (!DestPtr.isValid()) {
5638e5dd7070Spatrick         DestPtr = CreateMemTemp(RetTy, "coerce");
5639e5dd7070Spatrick         DestIsVolatile = false;
5640e5dd7070Spatrick       }
5641e5dd7070Spatrick 
5642e5dd7070Spatrick       // If the value is offset in memory, apply the offset now.
5643e5dd7070Spatrick       Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
5644e5dd7070Spatrick       CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
5645e5dd7070Spatrick 
5646e5dd7070Spatrick       return convertTempToRValue(DestPtr, RetTy, SourceLocation());
5647e5dd7070Spatrick     }
5648e5dd7070Spatrick 
5649e5dd7070Spatrick     case ABIArgInfo::Expand:
5650a0747c9fSpatrick     case ABIArgInfo::IndirectAliased:
5651e5dd7070Spatrick       llvm_unreachable("Invalid ABI kind for return argument");
5652e5dd7070Spatrick     }
5653e5dd7070Spatrick 
5654e5dd7070Spatrick     llvm_unreachable("Unhandled ABIArgInfo::Kind");
5655e5dd7070Spatrick   } ();
5656e5dd7070Spatrick 
5657e5dd7070Spatrick   // Emit the assume_aligned check on the return value.
5658e5dd7070Spatrick   if (Ret.isScalar() && TargetDecl) {
5659ec727ea7Spatrick     AssumeAlignedAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
5660ec727ea7Spatrick     AllocAlignAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
5661e5dd7070Spatrick   }
5662e5dd7070Spatrick 
5663e5dd7070Spatrick   // Explicitly call CallLifetimeEnd::Emit just to re-use the code even though
5664e5dd7070Spatrick   // we can't use the full cleanup mechanism.
5665e5dd7070Spatrick   for (CallLifetimeEnd &LifetimeEnd : CallLifetimeEndAfterCall)
5666e5dd7070Spatrick     LifetimeEnd.Emit(*this, /*Flags=*/{});
5667e5dd7070Spatrick 
5668ec727ea7Spatrick   if (!ReturnValue.isExternallyDestructed() &&
5669ec727ea7Spatrick       RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct)
5670ec727ea7Spatrick     pushDestroy(QualType::DK_nontrivial_c_struct, Ret.getAggregateAddress(),
5671ec727ea7Spatrick                 RetTy);
5672ec727ea7Spatrick 
5673e5dd7070Spatrick   return Ret;
5674e5dd7070Spatrick }
5675e5dd7070Spatrick 
prepareConcreteCallee(CodeGenFunction & CGF) const5676e5dd7070Spatrick CGCallee CGCallee::prepareConcreteCallee(CodeGenFunction &CGF) const {
5677e5dd7070Spatrick   if (isVirtual()) {
5678e5dd7070Spatrick     const CallExpr *CE = getVirtualCallExpr();
5679e5dd7070Spatrick     return CGF.CGM.getCXXABI().getVirtualFunctionPointer(
5680e5dd7070Spatrick         CGF, getVirtualMethodDecl(), getThisAddress(), getVirtualFunctionType(),
5681e5dd7070Spatrick         CE ? CE->getBeginLoc() : SourceLocation());
5682e5dd7070Spatrick   }
5683e5dd7070Spatrick 
5684e5dd7070Spatrick   return *this;
5685e5dd7070Spatrick }
5686e5dd7070Spatrick 
5687e5dd7070Spatrick /* VarArg handling */
5688e5dd7070Spatrick 
EmitVAArg(VAArgExpr * VE,Address & VAListAddr)5689e5dd7070Spatrick Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
5690e5dd7070Spatrick   VAListAddr = VE->isMicrosoftABI()
5691e5dd7070Spatrick                  ? EmitMSVAListRef(VE->getSubExpr())
5692e5dd7070Spatrick                  : EmitVAListRef(VE->getSubExpr());
5693e5dd7070Spatrick   QualType Ty = VE->getType();
5694e5dd7070Spatrick   if (VE->isMicrosoftABI())
5695e5dd7070Spatrick     return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
5696e5dd7070Spatrick   return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
5697e5dd7070Spatrick }
5698