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