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