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