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