xref: /freebsd-src/contrib/llvm-project/clang/lib/CodeGen/CGCall.cpp (revision 81ad626541db97eb356e2c1d4a20eb2a26a766ab)
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   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
1935     // Exceptions aren't supported in CUDA device code.
1936     FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1937   }
1938 
1939   for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) {
1940     StringRef Var, Value;
1941     std::tie(Var, Value) = Attr.split('=');
1942     FuncAttrs.addAttribute(Var, Value);
1943   }
1944 }
1945 
1946 void CodeGenModule::addDefaultFunctionDefinitionAttributes(llvm::Function &F) {
1947   llvm::AttrBuilder FuncAttrs(F.getContext());
1948   getDefaultFunctionAttributes(F.getName(), F.hasOptNone(),
1949                                /* AttrOnCallSite = */ false, FuncAttrs);
1950   // TODO: call GetCPUAndFeaturesAttributes?
1951   F.addFnAttrs(FuncAttrs);
1952 }
1953 
1954 void CodeGenModule::addDefaultFunctionDefinitionAttributes(
1955                                                    llvm::AttrBuilder &attrs) {
1956   getDefaultFunctionAttributes(/*function name*/ "", /*optnone*/ false,
1957                                /*for call*/ false, attrs);
1958   GetCPUAndFeaturesAttributes(GlobalDecl(), attrs);
1959 }
1960 
1961 static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs,
1962                                    const LangOptions &LangOpts,
1963                                    const NoBuiltinAttr *NBA = nullptr) {
1964   auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) {
1965     SmallString<32> AttributeName;
1966     AttributeName += "no-builtin-";
1967     AttributeName += BuiltinName;
1968     FuncAttrs.addAttribute(AttributeName);
1969   };
1970 
1971   // First, handle the language options passed through -fno-builtin.
1972   if (LangOpts.NoBuiltin) {
1973     // -fno-builtin disables them all.
1974     FuncAttrs.addAttribute("no-builtins");
1975     return;
1976   }
1977 
1978   // Then, add attributes for builtins specified through -fno-builtin-<name>.
1979   llvm::for_each(LangOpts.NoBuiltinFuncs, AddNoBuiltinAttr);
1980 
1981   // Now, let's check the __attribute__((no_builtin("...")) attribute added to
1982   // the source.
1983   if (!NBA)
1984     return;
1985 
1986   // If there is a wildcard in the builtin names specified through the
1987   // attribute, disable them all.
1988   if (llvm::is_contained(NBA->builtinNames(), "*")) {
1989     FuncAttrs.addAttribute("no-builtins");
1990     return;
1991   }
1992 
1993   // And last, add the rest of the builtin names.
1994   llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr);
1995 }
1996 
1997 static bool DetermineNoUndef(QualType QTy, CodeGenTypes &Types,
1998                              const llvm::DataLayout &DL, const ABIArgInfo &AI,
1999                              bool CheckCoerce = true) {
2000   llvm::Type *Ty = Types.ConvertTypeForMem(QTy);
2001   if (AI.getKind() == ABIArgInfo::Indirect)
2002     return true;
2003   if (AI.getKind() == ABIArgInfo::Extend)
2004     return true;
2005   if (!DL.typeSizeEqualsStoreSize(Ty))
2006     // TODO: This will result in a modest amount of values not marked noundef
2007     // when they could be. We care about values that *invisibly* contain undef
2008     // bits from the perspective of LLVM IR.
2009     return false;
2010   if (CheckCoerce && AI.canHaveCoerceToType()) {
2011     llvm::Type *CoerceTy = AI.getCoerceToType();
2012     if (llvm::TypeSize::isKnownGT(DL.getTypeSizeInBits(CoerceTy),
2013                                   DL.getTypeSizeInBits(Ty)))
2014       // If we're coercing to a type with a greater size than the canonical one,
2015       // we're introducing new undef bits.
2016       // Coercing to a type of smaller or equal size is ok, as we know that
2017       // there's no internal padding (typeSizeEqualsStoreSize).
2018       return false;
2019   }
2020   if (QTy->isBitIntType())
2021     return true;
2022   if (QTy->isReferenceType())
2023     return true;
2024   if (QTy->isNullPtrType())
2025     return false;
2026   if (QTy->isMemberPointerType())
2027     // TODO: Some member pointers are `noundef`, but it depends on the ABI. For
2028     // now, never mark them.
2029     return false;
2030   if (QTy->isScalarType()) {
2031     if (const ComplexType *Complex = dyn_cast<ComplexType>(QTy))
2032       return DetermineNoUndef(Complex->getElementType(), Types, DL, AI, false);
2033     return true;
2034   }
2035   if (const VectorType *Vector = dyn_cast<VectorType>(QTy))
2036     return DetermineNoUndef(Vector->getElementType(), Types, DL, AI, false);
2037   if (const MatrixType *Matrix = dyn_cast<MatrixType>(QTy))
2038     return DetermineNoUndef(Matrix->getElementType(), Types, DL, AI, false);
2039   if (const ArrayType *Array = dyn_cast<ArrayType>(QTy))
2040     return DetermineNoUndef(Array->getElementType(), Types, DL, AI, false);
2041 
2042   // TODO: Some structs may be `noundef`, in specific situations.
2043   return false;
2044 }
2045 
2046 /// Construct the IR attribute list of a function or call.
2047 ///
2048 /// When adding an attribute, please consider where it should be handled:
2049 ///
2050 ///   - getDefaultFunctionAttributes is for attributes that are essentially
2051 ///     part of the global target configuration (but perhaps can be
2052 ///     overridden on a per-function basis).  Adding attributes there
2053 ///     will cause them to also be set in frontends that build on Clang's
2054 ///     target-configuration logic, as well as for code defined in library
2055 ///     modules such as CUDA's libdevice.
2056 ///
2057 ///   - ConstructAttributeList builds on top of getDefaultFunctionAttributes
2058 ///     and adds declaration-specific, convention-specific, and
2059 ///     frontend-specific logic.  The last is of particular importance:
2060 ///     attributes that restrict how the frontend generates code must be
2061 ///     added here rather than getDefaultFunctionAttributes.
2062 ///
2063 void CodeGenModule::ConstructAttributeList(StringRef Name,
2064                                            const CGFunctionInfo &FI,
2065                                            CGCalleeInfo CalleeInfo,
2066                                            llvm::AttributeList &AttrList,
2067                                            unsigned &CallingConv,
2068                                            bool AttrOnCallSite, bool IsThunk) {
2069   llvm::AttrBuilder FuncAttrs(getLLVMContext());
2070   llvm::AttrBuilder RetAttrs(getLLVMContext());
2071 
2072   // Collect function IR attributes from the CC lowering.
2073   // We'll collect the paramete and result attributes later.
2074   CallingConv = FI.getEffectiveCallingConvention();
2075   if (FI.isNoReturn())
2076     FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2077   if (FI.isCmseNSCall())
2078     FuncAttrs.addAttribute("cmse_nonsecure_call");
2079 
2080   // Collect function IR attributes from the callee prototype if we have one.
2081   AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
2082                                      CalleeInfo.getCalleeFunctionProtoType());
2083 
2084   const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl();
2085 
2086   // Attach assumption attributes to the declaration. If this is a call
2087   // site, attach assumptions from the caller to the call as well.
2088   AddAttributesFromAssumes(FuncAttrs, TargetDecl);
2089 
2090   bool HasOptnone = false;
2091   // The NoBuiltinAttr attached to the target FunctionDecl.
2092   const NoBuiltinAttr *NBA = nullptr;
2093 
2094   // Collect function IR attributes based on declaration-specific
2095   // information.
2096   // FIXME: handle sseregparm someday...
2097   if (TargetDecl) {
2098     if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
2099       FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
2100     if (TargetDecl->hasAttr<NoThrowAttr>())
2101       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2102     if (TargetDecl->hasAttr<NoReturnAttr>())
2103       FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2104     if (TargetDecl->hasAttr<ColdAttr>())
2105       FuncAttrs.addAttribute(llvm::Attribute::Cold);
2106     if (TargetDecl->hasAttr<HotAttr>())
2107       FuncAttrs.addAttribute(llvm::Attribute::Hot);
2108     if (TargetDecl->hasAttr<NoDuplicateAttr>())
2109       FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
2110     if (TargetDecl->hasAttr<ConvergentAttr>())
2111       FuncAttrs.addAttribute(llvm::Attribute::Convergent);
2112 
2113     if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2114       AddAttributesFromFunctionProtoType(
2115           getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
2116       if (AttrOnCallSite && Fn->isReplaceableGlobalAllocationFunction()) {
2117         // A sane operator new returns a non-aliasing pointer.
2118         auto Kind = Fn->getDeclName().getCXXOverloadedOperator();
2119         if (getCodeGenOpts().AssumeSaneOperatorNew &&
2120             (Kind == OO_New || Kind == OO_Array_New))
2121           RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2122       }
2123       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
2124       const bool IsVirtualCall = MD && MD->isVirtual();
2125       // Don't use [[noreturn]], _Noreturn or [[no_builtin]] for a call to a
2126       // virtual function. These attributes are not inherited by overloads.
2127       if (!(AttrOnCallSite && IsVirtualCall)) {
2128         if (Fn->isNoReturn())
2129           FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2130         NBA = Fn->getAttr<NoBuiltinAttr>();
2131       }
2132       // Only place nomerge attribute on call sites, never functions. This
2133       // allows it to work on indirect virtual function calls.
2134       if (AttrOnCallSite && TargetDecl->hasAttr<NoMergeAttr>())
2135         FuncAttrs.addAttribute(llvm::Attribute::NoMerge);
2136     }
2137 
2138     // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
2139     if (TargetDecl->hasAttr<ConstAttr>()) {
2140       FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
2141       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2142       // gcc specifies that 'const' functions have greater restrictions than
2143       // 'pure' functions, so they also cannot have infinite loops.
2144       FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
2145     } else if (TargetDecl->hasAttr<PureAttr>()) {
2146       FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
2147       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2148       // gcc specifies that 'pure' functions cannot have infinite loops.
2149       FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
2150     } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
2151       FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
2152       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2153     }
2154     if (TargetDecl->hasAttr<RestrictAttr>())
2155       RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2156     if (TargetDecl->hasAttr<ReturnsNonNullAttr>() &&
2157         !CodeGenOpts.NullPointerIsValid)
2158       RetAttrs.addAttribute(llvm::Attribute::NonNull);
2159     if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
2160       FuncAttrs.addAttribute("no_caller_saved_registers");
2161     if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>())
2162       FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck);
2163     if (TargetDecl->hasAttr<LeafAttr>())
2164       FuncAttrs.addAttribute(llvm::Attribute::NoCallback);
2165 
2166     HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
2167     if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
2168       Optional<unsigned> NumElemsParam;
2169       if (AllocSize->getNumElemsParam().isValid())
2170         NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
2171       FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(),
2172                                  NumElemsParam);
2173     }
2174 
2175     if (TargetDecl->hasAttr<OpenCLKernelAttr>()) {
2176       if (getLangOpts().OpenCLVersion <= 120) {
2177         // OpenCL v1.2 Work groups are always uniform
2178         FuncAttrs.addAttribute("uniform-work-group-size", "true");
2179       } else {
2180         // OpenCL v2.0 Work groups may be whether uniform or not.
2181         // '-cl-uniform-work-group-size' compile option gets a hint
2182         // to the compiler that the global work-size be a multiple of
2183         // the work-group size specified to clEnqueueNDRangeKernel
2184         // (i.e. work groups are uniform).
2185         FuncAttrs.addAttribute("uniform-work-group-size",
2186                                llvm::toStringRef(CodeGenOpts.UniformWGSize));
2187       }
2188     }
2189   }
2190 
2191   // Attach "no-builtins" attributes to:
2192   // * call sites: both `nobuiltin` and "no-builtins" or "no-builtin-<name>".
2193   // * definitions: "no-builtins" or "no-builtin-<name>" only.
2194   // The attributes can come from:
2195   // * LangOpts: -ffreestanding, -fno-builtin, -fno-builtin-<name>
2196   // * FunctionDecl attributes: __attribute__((no_builtin(...)))
2197   addNoBuiltinAttributes(FuncAttrs, getLangOpts(), NBA);
2198 
2199   // Collect function IR attributes based on global settiings.
2200   getDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
2201 
2202   // Override some default IR attributes based on declaration-specific
2203   // information.
2204   if (TargetDecl) {
2205     if (TargetDecl->hasAttr<NoSpeculativeLoadHardeningAttr>())
2206       FuncAttrs.removeAttribute(llvm::Attribute::SpeculativeLoadHardening);
2207     if (TargetDecl->hasAttr<SpeculativeLoadHardeningAttr>())
2208       FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
2209     if (TargetDecl->hasAttr<NoSplitStackAttr>())
2210       FuncAttrs.removeAttribute("split-stack");
2211     if (TargetDecl->hasAttr<ZeroCallUsedRegsAttr>()) {
2212       // A function "__attribute__((...))" overrides the command-line flag.
2213       auto Kind =
2214           TargetDecl->getAttr<ZeroCallUsedRegsAttr>()->getZeroCallUsedRegs();
2215       FuncAttrs.removeAttribute("zero-call-used-regs");
2216       FuncAttrs.addAttribute(
2217           "zero-call-used-regs",
2218           ZeroCallUsedRegsAttr::ConvertZeroCallUsedRegsKindToStr(Kind));
2219     }
2220 
2221     // Add NonLazyBind attribute to function declarations when -fno-plt
2222     // is used.
2223     // FIXME: what if we just haven't processed the function definition
2224     // yet, or if it's an external definition like C99 inline?
2225     if (CodeGenOpts.NoPLT) {
2226       if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2227         if (!Fn->isDefined() && !AttrOnCallSite) {
2228           FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind);
2229         }
2230       }
2231     }
2232   }
2233 
2234   // Add "sample-profile-suffix-elision-policy" attribute for internal linkage
2235   // functions with -funique-internal-linkage-names.
2236   if (TargetDecl && CodeGenOpts.UniqueInternalLinkageNames) {
2237     if (isa<FunctionDecl>(TargetDecl)) {
2238       if (this->getFunctionLinkage(CalleeInfo.getCalleeDecl()) ==
2239           llvm::GlobalValue::InternalLinkage)
2240         FuncAttrs.addAttribute("sample-profile-suffix-elision-policy",
2241                                "selected");
2242     }
2243   }
2244 
2245   // Collect non-call-site function IR attributes from declaration-specific
2246   // information.
2247   if (!AttrOnCallSite) {
2248     if (TargetDecl && TargetDecl->hasAttr<CmseNSEntryAttr>())
2249       FuncAttrs.addAttribute("cmse_nonsecure_entry");
2250 
2251     // Whether tail calls are enabled.
2252     auto shouldDisableTailCalls = [&] {
2253       // Should this be honored in getDefaultFunctionAttributes?
2254       if (CodeGenOpts.DisableTailCalls)
2255         return true;
2256 
2257       if (!TargetDecl)
2258         return false;
2259 
2260       if (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
2261           TargetDecl->hasAttr<AnyX86InterruptAttr>())
2262         return true;
2263 
2264       if (CodeGenOpts.NoEscapingBlockTailCalls) {
2265         if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl))
2266           if (!BD->doesNotEscape())
2267             return true;
2268       }
2269 
2270       return false;
2271     };
2272     if (shouldDisableTailCalls())
2273       FuncAttrs.addAttribute("disable-tail-calls", "true");
2274 
2275     // CPU/feature overrides.  addDefaultFunctionDefinitionAttributes
2276     // handles these separately to set them based on the global defaults.
2277     GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs);
2278   }
2279 
2280   // Collect attributes from arguments and return values.
2281   ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
2282 
2283   QualType RetTy = FI.getReturnType();
2284   const ABIArgInfo &RetAI = FI.getReturnInfo();
2285   const llvm::DataLayout &DL = getDataLayout();
2286 
2287   // C++ explicitly makes returning undefined values UB. C's rule only applies
2288   // to used values, so we never mark them noundef for now.
2289   bool HasStrictReturn = getLangOpts().CPlusPlus;
2290   if (TargetDecl && HasStrictReturn) {
2291     if (const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(TargetDecl))
2292       HasStrictReturn &= !FDecl->isExternC();
2293     else if (const VarDecl *VDecl = dyn_cast<VarDecl>(TargetDecl))
2294       // Function pointer
2295       HasStrictReturn &= !VDecl->isExternC();
2296   }
2297 
2298   // We don't want to be too aggressive with the return checking, unless
2299   // it's explicit in the code opts or we're using an appropriate sanitizer.
2300   // Try to respect what the programmer intended.
2301   HasStrictReturn &= getCodeGenOpts().StrictReturn ||
2302                      !MayDropFunctionReturn(getContext(), RetTy) ||
2303                      getLangOpts().Sanitize.has(SanitizerKind::Memory) ||
2304                      getLangOpts().Sanitize.has(SanitizerKind::Return);
2305 
2306   // Determine if the return type could be partially undef
2307   if (CodeGenOpts.EnableNoundefAttrs && HasStrictReturn) {
2308     if (!RetTy->isVoidType() && RetAI.getKind() != ABIArgInfo::Indirect &&
2309         DetermineNoUndef(RetTy, getTypes(), DL, RetAI))
2310       RetAttrs.addAttribute(llvm::Attribute::NoUndef);
2311   }
2312 
2313   switch (RetAI.getKind()) {
2314   case ABIArgInfo::Extend:
2315     if (RetAI.isSignExt())
2316       RetAttrs.addAttribute(llvm::Attribute::SExt);
2317     else
2318       RetAttrs.addAttribute(llvm::Attribute::ZExt);
2319     LLVM_FALLTHROUGH;
2320   case ABIArgInfo::Direct:
2321     if (RetAI.getInReg())
2322       RetAttrs.addAttribute(llvm::Attribute::InReg);
2323     break;
2324   case ABIArgInfo::Ignore:
2325     break;
2326 
2327   case ABIArgInfo::InAlloca:
2328   case ABIArgInfo::Indirect: {
2329     // inalloca and sret disable readnone and readonly
2330     FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
2331       .removeAttribute(llvm::Attribute::ReadNone);
2332     break;
2333   }
2334 
2335   case ABIArgInfo::CoerceAndExpand:
2336     break;
2337 
2338   case ABIArgInfo::Expand:
2339   case ABIArgInfo::IndirectAliased:
2340     llvm_unreachable("Invalid ABI kind for return argument");
2341   }
2342 
2343   if (!IsThunk) {
2344     // FIXME: fix this properly, https://reviews.llvm.org/D100388
2345     if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
2346       QualType PTy = RefTy->getPointeeType();
2347       if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2348         RetAttrs.addDereferenceableAttr(
2349             getMinimumObjectSize(PTy).getQuantity());
2350       if (getContext().getTargetAddressSpace(PTy) == 0 &&
2351           !CodeGenOpts.NullPointerIsValid)
2352         RetAttrs.addAttribute(llvm::Attribute::NonNull);
2353       if (PTy->isObjectType()) {
2354         llvm::Align Alignment =
2355             getNaturalPointeeTypeAlignment(RetTy).getAsAlign();
2356         RetAttrs.addAlignmentAttr(Alignment);
2357       }
2358     }
2359   }
2360 
2361   bool hasUsedSRet = false;
2362   SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs());
2363 
2364   // Attach attributes to sret.
2365   if (IRFunctionArgs.hasSRetArg()) {
2366     llvm::AttrBuilder SRETAttrs(getLLVMContext());
2367     SRETAttrs.addStructRetAttr(getTypes().ConvertTypeForMem(RetTy));
2368     hasUsedSRet = true;
2369     if (RetAI.getInReg())
2370       SRETAttrs.addAttribute(llvm::Attribute::InReg);
2371     SRETAttrs.addAlignmentAttr(RetAI.getIndirectAlign().getQuantity());
2372     ArgAttrs[IRFunctionArgs.getSRetArgNo()] =
2373         llvm::AttributeSet::get(getLLVMContext(), SRETAttrs);
2374   }
2375 
2376   // Attach attributes to inalloca argument.
2377   if (IRFunctionArgs.hasInallocaArg()) {
2378     llvm::AttrBuilder Attrs(getLLVMContext());
2379     Attrs.addInAllocaAttr(FI.getArgStruct());
2380     ArgAttrs[IRFunctionArgs.getInallocaArgNo()] =
2381         llvm::AttributeSet::get(getLLVMContext(), Attrs);
2382   }
2383 
2384   // Apply `nonnull`, `dereferencable(N)` and `align N` to the `this` argument,
2385   // unless this is a thunk function.
2386   // FIXME: fix this properly, https://reviews.llvm.org/D100388
2387   if (FI.isInstanceMethod() && !IRFunctionArgs.hasInallocaArg() &&
2388       !FI.arg_begin()->type->isVoidPointerType() && !IsThunk) {
2389     auto IRArgs = IRFunctionArgs.getIRArgs(0);
2390 
2391     assert(IRArgs.second == 1 && "Expected only a single `this` pointer.");
2392 
2393     llvm::AttrBuilder Attrs(getLLVMContext());
2394 
2395     QualType ThisTy =
2396         FI.arg_begin()->type.castAs<PointerType>()->getPointeeType();
2397 
2398     if (!CodeGenOpts.NullPointerIsValid &&
2399         getContext().getTargetAddressSpace(FI.arg_begin()->type) == 0) {
2400       Attrs.addAttribute(llvm::Attribute::NonNull);
2401       Attrs.addDereferenceableAttr(getMinimumObjectSize(ThisTy).getQuantity());
2402     } else {
2403       // FIXME dereferenceable should be correct here, regardless of
2404       // NullPointerIsValid. However, dereferenceable currently does not always
2405       // respect NullPointerIsValid and may imply nonnull and break the program.
2406       // See https://reviews.llvm.org/D66618 for discussions.
2407       Attrs.addDereferenceableOrNullAttr(
2408           getMinimumObjectSize(
2409               FI.arg_begin()->type.castAs<PointerType>()->getPointeeType())
2410               .getQuantity());
2411     }
2412 
2413     llvm::Align Alignment =
2414         getNaturalTypeAlignment(ThisTy, /*BaseInfo=*/nullptr,
2415                                 /*TBAAInfo=*/nullptr, /*forPointeeType=*/true)
2416             .getAsAlign();
2417     Attrs.addAlignmentAttr(Alignment);
2418 
2419     ArgAttrs[IRArgs.first] = llvm::AttributeSet::get(getLLVMContext(), Attrs);
2420   }
2421 
2422   unsigned ArgNo = 0;
2423   for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
2424                                           E = FI.arg_end();
2425        I != E; ++I, ++ArgNo) {
2426     QualType ParamType = I->type;
2427     const ABIArgInfo &AI = I->info;
2428     llvm::AttrBuilder Attrs(getLLVMContext());
2429 
2430     // Add attribute for padding argument, if necessary.
2431     if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
2432       if (AI.getPaddingInReg()) {
2433         ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2434             llvm::AttributeSet::get(
2435                 getLLVMContext(),
2436                 llvm::AttrBuilder(getLLVMContext()).addAttribute(llvm::Attribute::InReg));
2437       }
2438     }
2439 
2440     // Decide whether the argument we're handling could be partially undef
2441     if (CodeGenOpts.EnableNoundefAttrs &&
2442         DetermineNoUndef(ParamType, getTypes(), DL, AI)) {
2443       Attrs.addAttribute(llvm::Attribute::NoUndef);
2444     }
2445 
2446     // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
2447     // have the corresponding parameter variable.  It doesn't make
2448     // sense to do it here because parameters are so messed up.
2449     switch (AI.getKind()) {
2450     case ABIArgInfo::Extend:
2451       if (AI.isSignExt())
2452         Attrs.addAttribute(llvm::Attribute::SExt);
2453       else
2454         Attrs.addAttribute(llvm::Attribute::ZExt);
2455       LLVM_FALLTHROUGH;
2456     case ABIArgInfo::Direct:
2457       if (ArgNo == 0 && FI.isChainCall())
2458         Attrs.addAttribute(llvm::Attribute::Nest);
2459       else if (AI.getInReg())
2460         Attrs.addAttribute(llvm::Attribute::InReg);
2461       Attrs.addStackAlignmentAttr(llvm::MaybeAlign(AI.getDirectAlign()));
2462       break;
2463 
2464     case ABIArgInfo::Indirect: {
2465       if (AI.getInReg())
2466         Attrs.addAttribute(llvm::Attribute::InReg);
2467 
2468       if (AI.getIndirectByVal())
2469         Attrs.addByValAttr(getTypes().ConvertTypeForMem(ParamType));
2470 
2471       auto *Decl = ParamType->getAsRecordDecl();
2472       if (CodeGenOpts.PassByValueIsNoAlias && Decl &&
2473           Decl->getArgPassingRestrictions() == RecordDecl::APK_CanPassInRegs)
2474         // When calling the function, the pointer passed in will be the only
2475         // reference to the underlying object. Mark it accordingly.
2476         Attrs.addAttribute(llvm::Attribute::NoAlias);
2477 
2478       // TODO: We could add the byref attribute if not byval, but it would
2479       // require updating many testcases.
2480 
2481       CharUnits Align = AI.getIndirectAlign();
2482 
2483       // In a byval argument, it is important that the required
2484       // alignment of the type is honored, as LLVM might be creating a
2485       // *new* stack object, and needs to know what alignment to give
2486       // it. (Sometimes it can deduce a sensible alignment on its own,
2487       // but not if clang decides it must emit a packed struct, or the
2488       // user specifies increased alignment requirements.)
2489       //
2490       // This is different from indirect *not* byval, where the object
2491       // exists already, and the align attribute is purely
2492       // informative.
2493       assert(!Align.isZero());
2494 
2495       // For now, only add this when we have a byval argument.
2496       // TODO: be less lazy about updating test cases.
2497       if (AI.getIndirectByVal())
2498         Attrs.addAlignmentAttr(Align.getQuantity());
2499 
2500       // byval disables readnone and readonly.
2501       FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
2502         .removeAttribute(llvm::Attribute::ReadNone);
2503 
2504       break;
2505     }
2506     case ABIArgInfo::IndirectAliased: {
2507       CharUnits Align = AI.getIndirectAlign();
2508       Attrs.addByRefAttr(getTypes().ConvertTypeForMem(ParamType));
2509       Attrs.addAlignmentAttr(Align.getQuantity());
2510       break;
2511     }
2512     case ABIArgInfo::Ignore:
2513     case ABIArgInfo::Expand:
2514     case ABIArgInfo::CoerceAndExpand:
2515       break;
2516 
2517     case ABIArgInfo::InAlloca:
2518       // inalloca disables readnone and readonly.
2519       FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
2520           .removeAttribute(llvm::Attribute::ReadNone);
2521       continue;
2522     }
2523 
2524     if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
2525       QualType PTy = RefTy->getPointeeType();
2526       if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2527         Attrs.addDereferenceableAttr(
2528             getMinimumObjectSize(PTy).getQuantity());
2529       if (getContext().getTargetAddressSpace(PTy) == 0 &&
2530           !CodeGenOpts.NullPointerIsValid)
2531         Attrs.addAttribute(llvm::Attribute::NonNull);
2532       if (PTy->isObjectType()) {
2533         llvm::Align Alignment =
2534             getNaturalPointeeTypeAlignment(ParamType).getAsAlign();
2535         Attrs.addAlignmentAttr(Alignment);
2536       }
2537     }
2538 
2539     // From OpenCL spec v3.0.10 section 6.3.5 Alignment of Types:
2540     // > For arguments to a __kernel function declared to be a pointer to a
2541     // > data type, the OpenCL compiler can assume that the pointee is always
2542     // > appropriately aligned as required by the data type.
2543     if (TargetDecl && TargetDecl->hasAttr<OpenCLKernelAttr>() &&
2544         ParamType->isPointerType()) {
2545       QualType PTy = ParamType->getPointeeType();
2546       if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2547         llvm::Align Alignment =
2548             getNaturalPointeeTypeAlignment(ParamType).getAsAlign();
2549         Attrs.addAlignmentAttr(Alignment);
2550       }
2551     }
2552 
2553     switch (FI.getExtParameterInfo(ArgNo).getABI()) {
2554     case ParameterABI::Ordinary:
2555       break;
2556 
2557     case ParameterABI::SwiftIndirectResult: {
2558       // Add 'sret' if we haven't already used it for something, but
2559       // only if the result is void.
2560       if (!hasUsedSRet && RetTy->isVoidType()) {
2561         Attrs.addStructRetAttr(getTypes().ConvertTypeForMem(ParamType));
2562         hasUsedSRet = true;
2563       }
2564 
2565       // Add 'noalias' in either case.
2566       Attrs.addAttribute(llvm::Attribute::NoAlias);
2567 
2568       // Add 'dereferenceable' and 'alignment'.
2569       auto PTy = ParamType->getPointeeType();
2570       if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2571         auto info = getContext().getTypeInfoInChars(PTy);
2572         Attrs.addDereferenceableAttr(info.Width.getQuantity());
2573         Attrs.addAlignmentAttr(info.Align.getAsAlign());
2574       }
2575       break;
2576     }
2577 
2578     case ParameterABI::SwiftErrorResult:
2579       Attrs.addAttribute(llvm::Attribute::SwiftError);
2580       break;
2581 
2582     case ParameterABI::SwiftContext:
2583       Attrs.addAttribute(llvm::Attribute::SwiftSelf);
2584       break;
2585 
2586     case ParameterABI::SwiftAsyncContext:
2587       Attrs.addAttribute(llvm::Attribute::SwiftAsync);
2588       break;
2589     }
2590 
2591     if (FI.getExtParameterInfo(ArgNo).isNoEscape())
2592       Attrs.addAttribute(llvm::Attribute::NoCapture);
2593 
2594     if (Attrs.hasAttributes()) {
2595       unsigned FirstIRArg, NumIRArgs;
2596       std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2597       for (unsigned i = 0; i < NumIRArgs; i++)
2598         ArgAttrs[FirstIRArg + i] = ArgAttrs[FirstIRArg + i].addAttributes(
2599             getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), Attrs));
2600     }
2601   }
2602   assert(ArgNo == FI.arg_size());
2603 
2604   AttrList = llvm::AttributeList::get(
2605       getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs),
2606       llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs);
2607 }
2608 
2609 /// An argument came in as a promoted argument; demote it back to its
2610 /// declared type.
2611 static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
2612                                          const VarDecl *var,
2613                                          llvm::Value *value) {
2614   llvm::Type *varType = CGF.ConvertType(var->getType());
2615 
2616   // This can happen with promotions that actually don't change the
2617   // underlying type, like the enum promotions.
2618   if (value->getType() == varType) return value;
2619 
2620   assert((varType->isIntegerTy() || varType->isFloatingPointTy())
2621          && "unexpected promotion type");
2622 
2623   if (isa<llvm::IntegerType>(varType))
2624     return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2625 
2626   return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2627 }
2628 
2629 /// Returns the attribute (either parameter attribute, or function
2630 /// attribute), which declares argument ArgNo to be non-null.
2631 static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2632                                          QualType ArgType, unsigned ArgNo) {
2633   // FIXME: __attribute__((nonnull)) can also be applied to:
2634   //   - references to pointers, where the pointee is known to be
2635   //     nonnull (apparently a Clang extension)
2636   //   - transparent unions containing pointers
2637   // In the former case, LLVM IR cannot represent the constraint. In
2638   // the latter case, we have no guarantee that the transparent union
2639   // is in fact passed as a pointer.
2640   if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2641     return nullptr;
2642   // First, check attribute on parameter itself.
2643   if (PVD) {
2644     if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2645       return ParmNNAttr;
2646   }
2647   // Check function attributes.
2648   if (!FD)
2649     return nullptr;
2650   for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
2651     if (NNAttr->isNonNull(ArgNo))
2652       return NNAttr;
2653   }
2654   return nullptr;
2655 }
2656 
2657 namespace {
2658   struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2659     Address Temp;
2660     Address Arg;
2661     CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
2662     void Emit(CodeGenFunction &CGF, Flags flags) override {
2663       llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2664       CGF.Builder.CreateStore(errorValue, Arg);
2665     }
2666   };
2667 }
2668 
2669 void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
2670                                          llvm::Function *Fn,
2671                                          const FunctionArgList &Args) {
2672   if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
2673     // Naked functions don't have prologues.
2674     return;
2675 
2676   // If this is an implicit-return-zero function, go ahead and
2677   // initialize the return value.  TODO: it might be nice to have
2678   // a more general mechanism for this that didn't require synthesized
2679   // return statements.
2680   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
2681     if (FD->hasImplicitReturnZero()) {
2682       QualType RetTy = FD->getReturnType().getUnqualifiedType();
2683       llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
2684       llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
2685       Builder.CreateStore(Zero, ReturnValue);
2686     }
2687   }
2688 
2689   // FIXME: We no longer need the types from FunctionArgList; lift up and
2690   // simplify.
2691 
2692   ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
2693   assert(Fn->arg_size() == IRFunctionArgs.totalIRArgs());
2694 
2695   // If we're using inalloca, all the memory arguments are GEPs off of the last
2696   // parameter, which is a pointer to the complete memory area.
2697   Address ArgStruct = Address::invalid();
2698   if (IRFunctionArgs.hasInallocaArg()) {
2699     ArgStruct = Address(Fn->getArg(IRFunctionArgs.getInallocaArgNo()),
2700                         FI.getArgStruct(), FI.getArgStructAlignment());
2701 
2702     assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
2703   }
2704 
2705   // Name the struct return parameter.
2706   if (IRFunctionArgs.hasSRetArg()) {
2707     auto AI = Fn->getArg(IRFunctionArgs.getSRetArgNo());
2708     AI->setName("agg.result");
2709     AI->addAttr(llvm::Attribute::NoAlias);
2710   }
2711 
2712   // Track if we received the parameter as a pointer (indirect, byval, or
2713   // inalloca).  If already have a pointer, EmitParmDecl doesn't need to copy it
2714   // into a local alloca for us.
2715   SmallVector<ParamValue, 16> ArgVals;
2716   ArgVals.reserve(Args.size());
2717 
2718   // Create a pointer value for every parameter declaration.  This usually
2719   // entails copying one or more LLVM IR arguments into an alloca.  Don't push
2720   // any cleanups or do anything that might unwind.  We do that separately, so
2721   // we can push the cleanups in the correct order for the ABI.
2722   assert(FI.arg_size() == Args.size() &&
2723          "Mismatch between function signature & arguments.");
2724   unsigned ArgNo = 0;
2725   CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
2726   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
2727        i != e; ++i, ++info_it, ++ArgNo) {
2728     const VarDecl *Arg = *i;
2729     const ABIArgInfo &ArgI = info_it->info;
2730 
2731     bool isPromoted =
2732       isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
2733     // We are converting from ABIArgInfo type to VarDecl type directly, unless
2734     // the parameter is promoted. In this case we convert to
2735     // CGFunctionInfo::ArgInfo type with subsequent argument demotion.
2736     QualType Ty = isPromoted ? info_it->type : Arg->getType();
2737     assert(hasScalarEvaluationKind(Ty) ==
2738            hasScalarEvaluationKind(Arg->getType()));
2739 
2740     unsigned FirstIRArg, NumIRArgs;
2741     std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2742 
2743     switch (ArgI.getKind()) {
2744     case ABIArgInfo::InAlloca: {
2745       assert(NumIRArgs == 0);
2746       auto FieldIndex = ArgI.getInAllocaFieldIndex();
2747       Address V =
2748           Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName());
2749       if (ArgI.getInAllocaIndirect())
2750         V = Address(Builder.CreateLoad(V), ConvertTypeForMem(Ty),
2751                     getContext().getTypeAlignInChars(Ty));
2752       ArgVals.push_back(ParamValue::forIndirect(V));
2753       break;
2754     }
2755 
2756     case ABIArgInfo::Indirect:
2757     case ABIArgInfo::IndirectAliased: {
2758       assert(NumIRArgs == 1);
2759       Address ParamAddr = Address(Fn->getArg(FirstIRArg), ConvertTypeForMem(Ty),
2760                                   ArgI.getIndirectAlign());
2761 
2762       if (!hasScalarEvaluationKind(Ty)) {
2763         // Aggregates and complex variables are accessed by reference. All we
2764         // need to do is realign the value, if requested. Also, if the address
2765         // may be aliased, copy it to ensure that the parameter variable is
2766         // mutable and has a unique adress, as C requires.
2767         Address V = ParamAddr;
2768         if (ArgI.getIndirectRealign() || ArgI.isIndirectAliased()) {
2769           Address AlignedTemp = CreateMemTemp(Ty, "coerce");
2770 
2771           // Copy from the incoming argument pointer to the temporary with the
2772           // appropriate alignment.
2773           //
2774           // FIXME: We should have a common utility for generating an aggregate
2775           // copy.
2776           CharUnits Size = getContext().getTypeSizeInChars(Ty);
2777           Builder.CreateMemCpy(
2778               AlignedTemp.getPointer(), AlignedTemp.getAlignment().getAsAlign(),
2779               ParamAddr.getPointer(), ParamAddr.getAlignment().getAsAlign(),
2780               llvm::ConstantInt::get(IntPtrTy, Size.getQuantity()));
2781           V = AlignedTemp;
2782         }
2783         ArgVals.push_back(ParamValue::forIndirect(V));
2784       } else {
2785         // Load scalar value from indirect argument.
2786         llvm::Value *V =
2787             EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc());
2788 
2789         if (isPromoted)
2790           V = emitArgumentDemotion(*this, Arg, V);
2791         ArgVals.push_back(ParamValue::forDirect(V));
2792       }
2793       break;
2794     }
2795 
2796     case ABIArgInfo::Extend:
2797     case ABIArgInfo::Direct: {
2798       auto AI = Fn->getArg(FirstIRArg);
2799       llvm::Type *LTy = ConvertType(Arg->getType());
2800 
2801       // Prepare parameter attributes. So far, only attributes for pointer
2802       // parameters are prepared. See
2803       // http://llvm.org/docs/LangRef.html#paramattrs.
2804       if (ArgI.getDirectOffset() == 0 && LTy->isPointerTy() &&
2805           ArgI.getCoerceToType()->isPointerTy()) {
2806         assert(NumIRArgs == 1);
2807 
2808         if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
2809           // Set `nonnull` attribute if any.
2810           if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
2811                              PVD->getFunctionScopeIndex()) &&
2812               !CGM.getCodeGenOpts().NullPointerIsValid)
2813             AI->addAttr(llvm::Attribute::NonNull);
2814 
2815           QualType OTy = PVD->getOriginalType();
2816           if (const auto *ArrTy =
2817               getContext().getAsConstantArrayType(OTy)) {
2818             // A C99 array parameter declaration with the static keyword also
2819             // indicates dereferenceability, and if the size is constant we can
2820             // use the dereferenceable attribute (which requires the size in
2821             // bytes).
2822             if (ArrTy->getSizeModifier() == ArrayType::Static) {
2823               QualType ETy = ArrTy->getElementType();
2824               llvm::Align Alignment =
2825                   CGM.getNaturalTypeAlignment(ETy).getAsAlign();
2826               AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(Alignment));
2827               uint64_t ArrSize = ArrTy->getSize().getZExtValue();
2828               if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
2829                   ArrSize) {
2830                 llvm::AttrBuilder Attrs(getLLVMContext());
2831                 Attrs.addDereferenceableAttr(
2832                     getContext().getTypeSizeInChars(ETy).getQuantity() *
2833                     ArrSize);
2834                 AI->addAttrs(Attrs);
2835               } else if (getContext().getTargetInfo().getNullPointerValue(
2836                              ETy.getAddressSpace()) == 0 &&
2837                          !CGM.getCodeGenOpts().NullPointerIsValid) {
2838                 AI->addAttr(llvm::Attribute::NonNull);
2839               }
2840             }
2841           } else if (const auto *ArrTy =
2842                      getContext().getAsVariableArrayType(OTy)) {
2843             // For C99 VLAs with the static keyword, we don't know the size so
2844             // we can't use the dereferenceable attribute, but in addrspace(0)
2845             // we know that it must be nonnull.
2846             if (ArrTy->getSizeModifier() == VariableArrayType::Static) {
2847               QualType ETy = ArrTy->getElementType();
2848               llvm::Align Alignment =
2849                   CGM.getNaturalTypeAlignment(ETy).getAsAlign();
2850               AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(Alignment));
2851               if (!getContext().getTargetAddressSpace(ETy) &&
2852                   !CGM.getCodeGenOpts().NullPointerIsValid)
2853                 AI->addAttr(llvm::Attribute::NonNull);
2854             }
2855           }
2856 
2857           // Set `align` attribute if any.
2858           const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
2859           if (!AVAttr)
2860             if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
2861               AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
2862           if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) {
2863             // If alignment-assumption sanitizer is enabled, we do *not* add
2864             // alignment attribute here, but emit normal alignment assumption,
2865             // so the UBSAN check could function.
2866             llvm::ConstantInt *AlignmentCI =
2867                 cast<llvm::ConstantInt>(EmitScalarExpr(AVAttr->getAlignment()));
2868             uint64_t AlignmentInt =
2869                 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment);
2870             if (AI->getParamAlign().valueOrOne() < AlignmentInt) {
2871               AI->removeAttr(llvm::Attribute::AttrKind::Alignment);
2872               AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(
2873                   llvm::Align(AlignmentInt)));
2874             }
2875           }
2876         }
2877 
2878         // Set 'noalias' if an argument type has the `restrict` qualifier.
2879         if (Arg->getType().isRestrictQualified())
2880           AI->addAttr(llvm::Attribute::NoAlias);
2881       }
2882 
2883       // Prepare the argument value. If we have the trivial case, handle it
2884       // with no muss and fuss.
2885       if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
2886           ArgI.getCoerceToType() == ConvertType(Ty) &&
2887           ArgI.getDirectOffset() == 0) {
2888         assert(NumIRArgs == 1);
2889 
2890         // LLVM expects swifterror parameters to be used in very restricted
2891         // ways.  Copy the value into a less-restricted temporary.
2892         llvm::Value *V = AI;
2893         if (FI.getExtParameterInfo(ArgNo).getABI()
2894               == ParameterABI::SwiftErrorResult) {
2895           QualType pointeeTy = Ty->getPointeeType();
2896           assert(pointeeTy->isPointerType());
2897           Address temp =
2898             CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
2899           Address arg(V, ConvertTypeForMem(pointeeTy),
2900                       getContext().getTypeAlignInChars(pointeeTy));
2901           llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
2902           Builder.CreateStore(incomingErrorValue, temp);
2903           V = temp.getPointer();
2904 
2905           // Push a cleanup to copy the value back at the end of the function.
2906           // The convention does not guarantee that the value will be written
2907           // back if the function exits with an unwind exception.
2908           EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
2909         }
2910 
2911         // Ensure the argument is the correct type.
2912         if (V->getType() != ArgI.getCoerceToType())
2913           V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
2914 
2915         if (isPromoted)
2916           V = emitArgumentDemotion(*this, Arg, V);
2917 
2918         // Because of merging of function types from multiple decls it is
2919         // possible for the type of an argument to not match the corresponding
2920         // type in the function type. Since we are codegening the callee
2921         // in here, add a cast to the argument type.
2922         llvm::Type *LTy = ConvertType(Arg->getType());
2923         if (V->getType() != LTy)
2924           V = Builder.CreateBitCast(V, LTy);
2925 
2926         ArgVals.push_back(ParamValue::forDirect(V));
2927         break;
2928       }
2929 
2930       // VLST arguments are coerced to VLATs at the function boundary for
2931       // ABI consistency. If this is a VLST that was coerced to
2932       // a VLAT at the function boundary and the types match up, use
2933       // llvm.vector.extract to convert back to the original VLST.
2934       if (auto *VecTyTo = dyn_cast<llvm::FixedVectorType>(ConvertType(Ty))) {
2935         llvm::Value *Coerced = Fn->getArg(FirstIRArg);
2936         if (auto *VecTyFrom =
2937                 dyn_cast<llvm::ScalableVectorType>(Coerced->getType())) {
2938           // If we are casting a scalable 16 x i1 predicate vector to a fixed i8
2939           // vector, bitcast the source and use a vector extract.
2940           auto PredType =
2941               llvm::ScalableVectorType::get(Builder.getInt1Ty(), 16);
2942           if (VecTyFrom == PredType &&
2943               VecTyTo->getElementType() == Builder.getInt8Ty()) {
2944             VecTyFrom = llvm::ScalableVectorType::get(Builder.getInt8Ty(), 2);
2945             Coerced = Builder.CreateBitCast(Coerced, VecTyFrom);
2946           }
2947           if (VecTyFrom->getElementType() == VecTyTo->getElementType()) {
2948             llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty);
2949 
2950             assert(NumIRArgs == 1);
2951             Coerced->setName(Arg->getName() + ".coerce");
2952             ArgVals.push_back(ParamValue::forDirect(Builder.CreateExtractVector(
2953                 VecTyTo, Coerced, Zero, "castFixedSve")));
2954             break;
2955           }
2956         }
2957       }
2958 
2959       Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
2960                                      Arg->getName());
2961 
2962       // Pointer to store into.
2963       Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
2964 
2965       // Fast-isel and the optimizer generally like scalar values better than
2966       // FCAs, so we flatten them if this is safe to do for this argument.
2967       llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
2968       if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
2969           STy->getNumElements() > 1) {
2970         uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
2971         llvm::Type *DstTy = Ptr.getElementType();
2972         uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
2973 
2974         Address AddrToStoreInto = Address::invalid();
2975         if (SrcSize <= DstSize) {
2976           AddrToStoreInto = Builder.CreateElementBitCast(Ptr, STy);
2977         } else {
2978           AddrToStoreInto =
2979             CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
2980         }
2981 
2982         assert(STy->getNumElements() == NumIRArgs);
2983         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2984           auto AI = Fn->getArg(FirstIRArg + i);
2985           AI->setName(Arg->getName() + ".coerce" + Twine(i));
2986           Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i);
2987           Builder.CreateStore(AI, EltPtr);
2988         }
2989 
2990         if (SrcSize > DstSize) {
2991           Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
2992         }
2993 
2994       } else {
2995         // Simple case, just do a coerced store of the argument into the alloca.
2996         assert(NumIRArgs == 1);
2997         auto AI = Fn->getArg(FirstIRArg);
2998         AI->setName(Arg->getName() + ".coerce");
2999         CreateCoercedStore(AI, Ptr, /*DstIsVolatile=*/false, *this);
3000       }
3001 
3002       // Match to what EmitParmDecl is expecting for this type.
3003       if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
3004         llvm::Value *V =
3005             EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc());
3006         if (isPromoted)
3007           V = emitArgumentDemotion(*this, Arg, V);
3008         ArgVals.push_back(ParamValue::forDirect(V));
3009       } else {
3010         ArgVals.push_back(ParamValue::forIndirect(Alloca));
3011       }
3012       break;
3013     }
3014 
3015     case ABIArgInfo::CoerceAndExpand: {
3016       // Reconstruct into a temporary.
3017       Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
3018       ArgVals.push_back(ParamValue::forIndirect(alloca));
3019 
3020       auto coercionType = ArgI.getCoerceAndExpandType();
3021       alloca = Builder.CreateElementBitCast(alloca, coercionType);
3022 
3023       unsigned argIndex = FirstIRArg;
3024       for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3025         llvm::Type *eltType = coercionType->getElementType(i);
3026         if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
3027           continue;
3028 
3029         auto eltAddr = Builder.CreateStructGEP(alloca, i);
3030         auto elt = Fn->getArg(argIndex++);
3031         Builder.CreateStore(elt, eltAddr);
3032       }
3033       assert(argIndex == FirstIRArg + NumIRArgs);
3034       break;
3035     }
3036 
3037     case ABIArgInfo::Expand: {
3038       // If this structure was expanded into multiple arguments then
3039       // we need to create a temporary and reconstruct it from the
3040       // arguments.
3041       Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
3042       LValue LV = MakeAddrLValue(Alloca, Ty);
3043       ArgVals.push_back(ParamValue::forIndirect(Alloca));
3044 
3045       auto FnArgIter = Fn->arg_begin() + FirstIRArg;
3046       ExpandTypeFromArgs(Ty, LV, FnArgIter);
3047       assert(FnArgIter == Fn->arg_begin() + FirstIRArg + NumIRArgs);
3048       for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
3049         auto AI = Fn->getArg(FirstIRArg + i);
3050         AI->setName(Arg->getName() + "." + Twine(i));
3051       }
3052       break;
3053     }
3054 
3055     case ABIArgInfo::Ignore:
3056       assert(NumIRArgs == 0);
3057       // Initialize the local variable appropriately.
3058       if (!hasScalarEvaluationKind(Ty)) {
3059         ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
3060       } else {
3061         llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
3062         ArgVals.push_back(ParamValue::forDirect(U));
3063       }
3064       break;
3065     }
3066   }
3067 
3068   if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3069     for (int I = Args.size() - 1; I >= 0; --I)
3070       EmitParmDecl(*Args[I], ArgVals[I], I + 1);
3071   } else {
3072     for (unsigned I = 0, E = Args.size(); I != E; ++I)
3073       EmitParmDecl(*Args[I], ArgVals[I], I + 1);
3074   }
3075 }
3076 
3077 static void eraseUnusedBitCasts(llvm::Instruction *insn) {
3078   while (insn->use_empty()) {
3079     llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
3080     if (!bitcast) return;
3081 
3082     // This is "safe" because we would have used a ConstantExpr otherwise.
3083     insn = cast<llvm::Instruction>(bitcast->getOperand(0));
3084     bitcast->eraseFromParent();
3085   }
3086 }
3087 
3088 /// Try to emit a fused autorelease of a return result.
3089 static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
3090                                                     llvm::Value *result) {
3091   // We must be immediately followed the cast.
3092   llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
3093   if (BB->empty()) return nullptr;
3094   if (&BB->back() != result) return nullptr;
3095 
3096   llvm::Type *resultType = result->getType();
3097 
3098   // result is in a BasicBlock and is therefore an Instruction.
3099   llvm::Instruction *generator = cast<llvm::Instruction>(result);
3100 
3101   SmallVector<llvm::Instruction *, 4> InstsToKill;
3102 
3103   // Look for:
3104   //  %generator = bitcast %type1* %generator2 to %type2*
3105   while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
3106     // We would have emitted this as a constant if the operand weren't
3107     // an Instruction.
3108     generator = cast<llvm::Instruction>(bitcast->getOperand(0));
3109 
3110     // Require the generator to be immediately followed by the cast.
3111     if (generator->getNextNode() != bitcast)
3112       return nullptr;
3113 
3114     InstsToKill.push_back(bitcast);
3115   }
3116 
3117   // Look for:
3118   //   %generator = call i8* @objc_retain(i8* %originalResult)
3119   // or
3120   //   %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
3121   llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
3122   if (!call) return nullptr;
3123 
3124   bool doRetainAutorelease;
3125 
3126   if (call->getCalledOperand() == CGF.CGM.getObjCEntrypoints().objc_retain) {
3127     doRetainAutorelease = true;
3128   } else if (call->getCalledOperand() ==
3129              CGF.CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue) {
3130     doRetainAutorelease = false;
3131 
3132     // If we emitted an assembly marker for this call (and the
3133     // ARCEntrypoints field should have been set if so), go looking
3134     // for that call.  If we can't find it, we can't do this
3135     // optimization.  But it should always be the immediately previous
3136     // instruction, unless we needed bitcasts around the call.
3137     if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
3138       llvm::Instruction *prev = call->getPrevNode();
3139       assert(prev);
3140       if (isa<llvm::BitCastInst>(prev)) {
3141         prev = prev->getPrevNode();
3142         assert(prev);
3143       }
3144       assert(isa<llvm::CallInst>(prev));
3145       assert(cast<llvm::CallInst>(prev)->getCalledOperand() ==
3146              CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
3147       InstsToKill.push_back(prev);
3148     }
3149   } else {
3150     return nullptr;
3151   }
3152 
3153   result = call->getArgOperand(0);
3154   InstsToKill.push_back(call);
3155 
3156   // Keep killing bitcasts, for sanity.  Note that we no longer care
3157   // about precise ordering as long as there's exactly one use.
3158   while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
3159     if (!bitcast->hasOneUse()) break;
3160     InstsToKill.push_back(bitcast);
3161     result = bitcast->getOperand(0);
3162   }
3163 
3164   // Delete all the unnecessary instructions, from latest to earliest.
3165   for (auto *I : InstsToKill)
3166     I->eraseFromParent();
3167 
3168   // Do the fused retain/autorelease if we were asked to.
3169   if (doRetainAutorelease)
3170     result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
3171 
3172   // Cast back to the result type.
3173   return CGF.Builder.CreateBitCast(result, resultType);
3174 }
3175 
3176 /// If this is a +1 of the value of an immutable 'self', remove it.
3177 static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
3178                                           llvm::Value *result) {
3179   // This is only applicable to a method with an immutable 'self'.
3180   const ObjCMethodDecl *method =
3181     dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
3182   if (!method) return nullptr;
3183   const VarDecl *self = method->getSelfDecl();
3184   if (!self->getType().isConstQualified()) return nullptr;
3185 
3186   // Look for a retain call.
3187   llvm::CallInst *retainCall =
3188     dyn_cast<llvm::CallInst>(result->stripPointerCasts());
3189   if (!retainCall || retainCall->getCalledOperand() !=
3190                          CGF.CGM.getObjCEntrypoints().objc_retain)
3191     return nullptr;
3192 
3193   // Look for an ordinary load of 'self'.
3194   llvm::Value *retainedValue = retainCall->getArgOperand(0);
3195   llvm::LoadInst *load =
3196     dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
3197   if (!load || load->isAtomic() || load->isVolatile() ||
3198       load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
3199     return nullptr;
3200 
3201   // Okay!  Burn it all down.  This relies for correctness on the
3202   // assumption that the retain is emitted as part of the return and
3203   // that thereafter everything is used "linearly".
3204   llvm::Type *resultType = result->getType();
3205   eraseUnusedBitCasts(cast<llvm::Instruction>(result));
3206   assert(retainCall->use_empty());
3207   retainCall->eraseFromParent();
3208   eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
3209 
3210   return CGF.Builder.CreateBitCast(load, resultType);
3211 }
3212 
3213 /// Emit an ARC autorelease of the result of a function.
3214 ///
3215 /// \return the value to actually return from the function
3216 static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
3217                                             llvm::Value *result) {
3218   // If we're returning 'self', kill the initial retain.  This is a
3219   // heuristic attempt to "encourage correctness" in the really unfortunate
3220   // case where we have a return of self during a dealloc and we desperately
3221   // need to avoid the possible autorelease.
3222   if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
3223     return self;
3224 
3225   // At -O0, try to emit a fused retain/autorelease.
3226   if (CGF.shouldUseFusedARCCalls())
3227     if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
3228       return fused;
3229 
3230   return CGF.EmitARCAutoreleaseReturnValue(result);
3231 }
3232 
3233 /// Heuristically search for a dominating store to the return-value slot.
3234 static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
3235   // Check if a User is a store which pointerOperand is the ReturnValue.
3236   // We are looking for stores to the ReturnValue, not for stores of the
3237   // ReturnValue to some other location.
3238   auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
3239     auto *SI = dyn_cast<llvm::StoreInst>(U);
3240     if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer() ||
3241         SI->getValueOperand()->getType() != CGF.ReturnValue.getElementType())
3242       return nullptr;
3243     // These aren't actually possible for non-coerced returns, and we
3244     // only care about non-coerced returns on this code path.
3245     assert(!SI->isAtomic() && !SI->isVolatile());
3246     return SI;
3247   };
3248   // If there are multiple uses of the return-value slot, just check
3249   // for something immediately preceding the IP.  Sometimes this can
3250   // happen with how we generate implicit-returns; it can also happen
3251   // with noreturn cleanups.
3252   if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
3253     llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
3254     if (IP->empty()) return nullptr;
3255 
3256     // Look at directly preceding instruction, skipping bitcasts and lifetime
3257     // markers.
3258     for (llvm::Instruction &I : make_range(IP->rbegin(), IP->rend())) {
3259       if (isa<llvm::BitCastInst>(&I))
3260         continue;
3261       if (auto *II = dyn_cast<llvm::IntrinsicInst>(&I))
3262         if (II->getIntrinsicID() == llvm::Intrinsic::lifetime_end)
3263           continue;
3264 
3265       return GetStoreIfValid(&I);
3266     }
3267     return nullptr;
3268   }
3269 
3270   llvm::StoreInst *store =
3271       GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
3272   if (!store) return nullptr;
3273 
3274   // Now do a first-and-dirty dominance check: just walk up the
3275   // single-predecessors chain from the current insertion point.
3276   llvm::BasicBlock *StoreBB = store->getParent();
3277   llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
3278   while (IP != StoreBB) {
3279     if (!(IP = IP->getSinglePredecessor()))
3280       return nullptr;
3281   }
3282 
3283   // Okay, the store's basic block dominates the insertion point; we
3284   // can do our thing.
3285   return store;
3286 }
3287 
3288 // Helper functions for EmitCMSEClearRecord
3289 
3290 // Set the bits corresponding to a field having width `BitWidth` and located at
3291 // offset `BitOffset` (from the least significant bit) within a storage unit of
3292 // `Bits.size()` bytes. Each element of `Bits` corresponds to one target byte.
3293 // Use little-endian layout, i.e.`Bits[0]` is the LSB.
3294 static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int BitOffset,
3295                         int BitWidth, int CharWidth) {
3296   assert(CharWidth <= 64);
3297   assert(static_cast<unsigned>(BitWidth) <= Bits.size() * CharWidth);
3298 
3299   int Pos = 0;
3300   if (BitOffset >= CharWidth) {
3301     Pos += BitOffset / CharWidth;
3302     BitOffset = BitOffset % CharWidth;
3303   }
3304 
3305   const uint64_t Used = (uint64_t(1) << CharWidth) - 1;
3306   if (BitOffset + BitWidth >= CharWidth) {
3307     Bits[Pos++] |= (Used << BitOffset) & Used;
3308     BitWidth -= CharWidth - BitOffset;
3309     BitOffset = 0;
3310   }
3311 
3312   while (BitWidth >= CharWidth) {
3313     Bits[Pos++] = Used;
3314     BitWidth -= CharWidth;
3315   }
3316 
3317   if (BitWidth > 0)
3318     Bits[Pos++] |= (Used >> (CharWidth - BitWidth)) << BitOffset;
3319 }
3320 
3321 // Set the bits corresponding to a field having width `BitWidth` and located at
3322 // offset `BitOffset` (from the least significant bit) within a storage unit of
3323 // `StorageSize` bytes, located at `StorageOffset` in `Bits`. Each element of
3324 // `Bits` corresponds to one target byte. Use target endian layout.
3325 static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int StorageOffset,
3326                         int StorageSize, int BitOffset, int BitWidth,
3327                         int CharWidth, bool BigEndian) {
3328 
3329   SmallVector<uint64_t, 8> TmpBits(StorageSize);
3330   setBitRange(TmpBits, BitOffset, BitWidth, CharWidth);
3331 
3332   if (BigEndian)
3333     std::reverse(TmpBits.begin(), TmpBits.end());
3334 
3335   for (uint64_t V : TmpBits)
3336     Bits[StorageOffset++] |= V;
3337 }
3338 
3339 static void setUsedBits(CodeGenModule &, QualType, int,
3340                         SmallVectorImpl<uint64_t> &);
3341 
3342 // Set the bits in `Bits`, which correspond to the value representations of
3343 // the actual members of the record type `RTy`. Note that this function does
3344 // not handle base classes, virtual tables, etc, since they cannot happen in
3345 // CMSE function arguments or return. The bit mask corresponds to the target
3346 // memory layout, i.e. it's endian dependent.
3347 static void setUsedBits(CodeGenModule &CGM, const RecordType *RTy, int Offset,
3348                         SmallVectorImpl<uint64_t> &Bits) {
3349   ASTContext &Context = CGM.getContext();
3350   int CharWidth = Context.getCharWidth();
3351   const RecordDecl *RD = RTy->getDecl()->getDefinition();
3352   const ASTRecordLayout &ASTLayout = Context.getASTRecordLayout(RD);
3353   const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(RD);
3354 
3355   int Idx = 0;
3356   for (auto I = RD->field_begin(), E = RD->field_end(); I != E; ++I, ++Idx) {
3357     const FieldDecl *F = *I;
3358 
3359     if (F->isUnnamedBitfield() || F->isZeroLengthBitField(Context) ||
3360         F->getType()->isIncompleteArrayType())
3361       continue;
3362 
3363     if (F->isBitField()) {
3364       const CGBitFieldInfo &BFI = Layout.getBitFieldInfo(F);
3365       setBitRange(Bits, Offset + BFI.StorageOffset.getQuantity(),
3366                   BFI.StorageSize / CharWidth, BFI.Offset,
3367                   BFI.Size, CharWidth,
3368                   CGM.getDataLayout().isBigEndian());
3369       continue;
3370     }
3371 
3372     setUsedBits(CGM, F->getType(),
3373                 Offset + ASTLayout.getFieldOffset(Idx) / CharWidth, Bits);
3374   }
3375 }
3376 
3377 // Set the bits in `Bits`, which correspond to the value representations of
3378 // the elements of an array type `ATy`.
3379 static void setUsedBits(CodeGenModule &CGM, const ConstantArrayType *ATy,
3380                         int Offset, SmallVectorImpl<uint64_t> &Bits) {
3381   const ASTContext &Context = CGM.getContext();
3382 
3383   QualType ETy = Context.getBaseElementType(ATy);
3384   int Size = Context.getTypeSizeInChars(ETy).getQuantity();
3385   SmallVector<uint64_t, 4> TmpBits(Size);
3386   setUsedBits(CGM, ETy, 0, TmpBits);
3387 
3388   for (int I = 0, N = Context.getConstantArrayElementCount(ATy); I < N; ++I) {
3389     auto Src = TmpBits.begin();
3390     auto Dst = Bits.begin() + Offset + I * Size;
3391     for (int J = 0; J < Size; ++J)
3392       *Dst++ |= *Src++;
3393   }
3394 }
3395 
3396 // Set the bits in `Bits`, which correspond to the value representations of
3397 // the type `QTy`.
3398 static void setUsedBits(CodeGenModule &CGM, QualType QTy, int Offset,
3399                         SmallVectorImpl<uint64_t> &Bits) {
3400   if (const auto *RTy = QTy->getAs<RecordType>())
3401     return setUsedBits(CGM, RTy, Offset, Bits);
3402 
3403   ASTContext &Context = CGM.getContext();
3404   if (const auto *ATy = Context.getAsConstantArrayType(QTy))
3405     return setUsedBits(CGM, ATy, Offset, Bits);
3406 
3407   int Size = Context.getTypeSizeInChars(QTy).getQuantity();
3408   if (Size <= 0)
3409     return;
3410 
3411   std::fill_n(Bits.begin() + Offset, Size,
3412               (uint64_t(1) << Context.getCharWidth()) - 1);
3413 }
3414 
3415 static uint64_t buildMultiCharMask(const SmallVectorImpl<uint64_t> &Bits,
3416                                    int Pos, int Size, int CharWidth,
3417                                    bool BigEndian) {
3418   assert(Size > 0);
3419   uint64_t Mask = 0;
3420   if (BigEndian) {
3421     for (auto P = Bits.begin() + Pos, E = Bits.begin() + Pos + Size; P != E;
3422          ++P)
3423       Mask = (Mask << CharWidth) | *P;
3424   } else {
3425     auto P = Bits.begin() + Pos + Size, End = Bits.begin() + Pos;
3426     do
3427       Mask = (Mask << CharWidth) | *--P;
3428     while (P != End);
3429   }
3430   return Mask;
3431 }
3432 
3433 // Emit code to clear the bits in a record, which aren't a part of any user
3434 // declared member, when the record is a function return.
3435 llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3436                                                   llvm::IntegerType *ITy,
3437                                                   QualType QTy) {
3438   assert(Src->getType() == ITy);
3439   assert(ITy->getScalarSizeInBits() <= 64);
3440 
3441   const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3442   int Size = DataLayout.getTypeStoreSize(ITy);
3443   SmallVector<uint64_t, 4> Bits(Size);
3444   setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
3445 
3446   int CharWidth = CGM.getContext().getCharWidth();
3447   uint64_t Mask =
3448       buildMultiCharMask(Bits, 0, Size, CharWidth, DataLayout.isBigEndian());
3449 
3450   return Builder.CreateAnd(Src, Mask, "cmse.clear");
3451 }
3452 
3453 // Emit code to clear the bits in a record, which aren't a part of any user
3454 // declared member, when the record is a function argument.
3455 llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3456                                                   llvm::ArrayType *ATy,
3457                                                   QualType QTy) {
3458   const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3459   int Size = DataLayout.getTypeStoreSize(ATy);
3460   SmallVector<uint64_t, 16> Bits(Size);
3461   setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
3462 
3463   // Clear each element of the LLVM array.
3464   int CharWidth = CGM.getContext().getCharWidth();
3465   int CharsPerElt =
3466       ATy->getArrayElementType()->getScalarSizeInBits() / CharWidth;
3467   int MaskIndex = 0;
3468   llvm::Value *R = llvm::PoisonValue::get(ATy);
3469   for (int I = 0, N = ATy->getArrayNumElements(); I != N; ++I) {
3470     uint64_t Mask = buildMultiCharMask(Bits, MaskIndex, CharsPerElt, CharWidth,
3471                                        DataLayout.isBigEndian());
3472     MaskIndex += CharsPerElt;
3473     llvm::Value *T0 = Builder.CreateExtractValue(Src, I);
3474     llvm::Value *T1 = Builder.CreateAnd(T0, Mask, "cmse.clear");
3475     R = Builder.CreateInsertValue(R, T1, I);
3476   }
3477 
3478   return R;
3479 }
3480 
3481 void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
3482                                          bool EmitRetDbgLoc,
3483                                          SourceLocation EndLoc) {
3484   if (FI.isNoReturn()) {
3485     // Noreturn functions don't return.
3486     EmitUnreachable(EndLoc);
3487     return;
3488   }
3489 
3490   if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
3491     // Naked functions don't have epilogues.
3492     Builder.CreateUnreachable();
3493     return;
3494   }
3495 
3496   // Functions with no result always return void.
3497   if (!ReturnValue.isValid()) {
3498     Builder.CreateRetVoid();
3499     return;
3500   }
3501 
3502   llvm::DebugLoc RetDbgLoc;
3503   llvm::Value *RV = nullptr;
3504   QualType RetTy = FI.getReturnType();
3505   const ABIArgInfo &RetAI = FI.getReturnInfo();
3506 
3507   switch (RetAI.getKind()) {
3508   case ABIArgInfo::InAlloca:
3509     // Aggregrates get evaluated directly into the destination.  Sometimes we
3510     // need to return the sret value in a register, though.
3511     assert(hasAggregateEvaluationKind(RetTy));
3512     if (RetAI.getInAllocaSRet()) {
3513       llvm::Function::arg_iterator EI = CurFn->arg_end();
3514       --EI;
3515       llvm::Value *ArgStruct = &*EI;
3516       llvm::Value *SRet = Builder.CreateStructGEP(
3517           FI.getArgStruct(), ArgStruct, RetAI.getInAllocaFieldIndex());
3518       llvm::Type *Ty =
3519           cast<llvm::GetElementPtrInst>(SRet)->getResultElementType();
3520       RV = Builder.CreateAlignedLoad(Ty, SRet, getPointerAlign(), "sret");
3521     }
3522     break;
3523 
3524   case ABIArgInfo::Indirect: {
3525     auto AI = CurFn->arg_begin();
3526     if (RetAI.isSRetAfterThis())
3527       ++AI;
3528     switch (getEvaluationKind(RetTy)) {
3529     case TEK_Complex: {
3530       ComplexPairTy RT =
3531         EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
3532       EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
3533                          /*isInit*/ true);
3534       break;
3535     }
3536     case TEK_Aggregate:
3537       // Do nothing; aggregrates get evaluated directly into the destination.
3538       break;
3539     case TEK_Scalar: {
3540       LValueBaseInfo BaseInfo;
3541       TBAAAccessInfo TBAAInfo;
3542       CharUnits Alignment =
3543           CGM.getNaturalTypeAlignment(RetTy, &BaseInfo, &TBAAInfo);
3544       Address ArgAddr(&*AI, ConvertType(RetTy), Alignment);
3545       LValue ArgVal =
3546           LValue::MakeAddr(ArgAddr, RetTy, getContext(), BaseInfo, TBAAInfo);
3547       EmitStoreOfScalar(
3548           Builder.CreateLoad(ReturnValue), ArgVal, /*isInit*/ true);
3549       break;
3550     }
3551     }
3552     break;
3553   }
3554 
3555   case ABIArgInfo::Extend:
3556   case ABIArgInfo::Direct:
3557     if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
3558         RetAI.getDirectOffset() == 0) {
3559       // The internal return value temp always will have pointer-to-return-type
3560       // type, just do a load.
3561 
3562       // If there is a dominating store to ReturnValue, we can elide
3563       // the load, zap the store, and usually zap the alloca.
3564       if (llvm::StoreInst *SI =
3565               findDominatingStoreToReturnValue(*this)) {
3566         // Reuse the debug location from the store unless there is
3567         // cleanup code to be emitted between the store and return
3568         // instruction.
3569         if (EmitRetDbgLoc && !AutoreleaseResult)
3570           RetDbgLoc = SI->getDebugLoc();
3571         // Get the stored value and nuke the now-dead store.
3572         RV = SI->getValueOperand();
3573         SI->eraseFromParent();
3574 
3575       // Otherwise, we have to do a simple load.
3576       } else {
3577         RV = Builder.CreateLoad(ReturnValue);
3578       }
3579     } else {
3580       // If the value is offset in memory, apply the offset now.
3581       Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
3582 
3583       RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
3584     }
3585 
3586     // In ARC, end functions that return a retainable type with a call
3587     // to objc_autoreleaseReturnValue.
3588     if (AutoreleaseResult) {
3589 #ifndef NDEBUG
3590       // Type::isObjCRetainabletype has to be called on a QualType that hasn't
3591       // been stripped of the typedefs, so we cannot use RetTy here. Get the
3592       // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
3593       // CurCodeDecl or BlockInfo.
3594       QualType RT;
3595 
3596       if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
3597         RT = FD->getReturnType();
3598       else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
3599         RT = MD->getReturnType();
3600       else if (isa<BlockDecl>(CurCodeDecl))
3601         RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
3602       else
3603         llvm_unreachable("Unexpected function/method type");
3604 
3605       assert(getLangOpts().ObjCAutoRefCount &&
3606              !FI.isReturnsRetained() &&
3607              RT->isObjCRetainableType());
3608 #endif
3609       RV = emitAutoreleaseOfResult(*this, RV);
3610     }
3611 
3612     break;
3613 
3614   case ABIArgInfo::Ignore:
3615     break;
3616 
3617   case ABIArgInfo::CoerceAndExpand: {
3618     auto coercionType = RetAI.getCoerceAndExpandType();
3619 
3620     // Load all of the coerced elements out into results.
3621     llvm::SmallVector<llvm::Value*, 4> results;
3622     Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
3623     for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3624       auto coercedEltType = coercionType->getElementType(i);
3625       if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
3626         continue;
3627 
3628       auto eltAddr = Builder.CreateStructGEP(addr, i);
3629       auto elt = Builder.CreateLoad(eltAddr);
3630       results.push_back(elt);
3631     }
3632 
3633     // If we have one result, it's the single direct result type.
3634     if (results.size() == 1) {
3635       RV = results[0];
3636 
3637     // Otherwise, we need to make a first-class aggregate.
3638     } else {
3639       // Construct a return type that lacks padding elements.
3640       llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
3641 
3642       RV = llvm::PoisonValue::get(returnType);
3643       for (unsigned i = 0, e = results.size(); i != e; ++i) {
3644         RV = Builder.CreateInsertValue(RV, results[i], i);
3645       }
3646     }
3647     break;
3648   }
3649   case ABIArgInfo::Expand:
3650   case ABIArgInfo::IndirectAliased:
3651     llvm_unreachable("Invalid ABI kind for return argument");
3652   }
3653 
3654   llvm::Instruction *Ret;
3655   if (RV) {
3656     if (CurFuncDecl && CurFuncDecl->hasAttr<CmseNSEntryAttr>()) {
3657       // For certain return types, clear padding bits, as they may reveal
3658       // sensitive information.
3659       // Small struct/union types are passed as integers.
3660       auto *ITy = dyn_cast<llvm::IntegerType>(RV->getType());
3661       if (ITy != nullptr && isa<RecordType>(RetTy.getCanonicalType()))
3662         RV = EmitCMSEClearRecord(RV, ITy, RetTy);
3663     }
3664     EmitReturnValueCheck(RV);
3665     Ret = Builder.CreateRet(RV);
3666   } else {
3667     Ret = Builder.CreateRetVoid();
3668   }
3669 
3670   if (RetDbgLoc)
3671     Ret->setDebugLoc(std::move(RetDbgLoc));
3672 }
3673 
3674 void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) {
3675   // A current decl may not be available when emitting vtable thunks.
3676   if (!CurCodeDecl)
3677     return;
3678 
3679   // If the return block isn't reachable, neither is this check, so don't emit
3680   // it.
3681   if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty())
3682     return;
3683 
3684   ReturnsNonNullAttr *RetNNAttr = nullptr;
3685   if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
3686     RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
3687 
3688   if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
3689     return;
3690 
3691   // Prefer the returns_nonnull attribute if it's present.
3692   SourceLocation AttrLoc;
3693   SanitizerMask CheckKind;
3694   SanitizerHandler Handler;
3695   if (RetNNAttr) {
3696     assert(!requiresReturnValueNullabilityCheck() &&
3697            "Cannot check nullability and the nonnull attribute");
3698     AttrLoc = RetNNAttr->getLocation();
3699     CheckKind = SanitizerKind::ReturnsNonnullAttribute;
3700     Handler = SanitizerHandler::NonnullReturn;
3701   } else {
3702     if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl))
3703       if (auto *TSI = DD->getTypeSourceInfo())
3704         if (auto FTL = TSI->getTypeLoc().getAsAdjusted<FunctionTypeLoc>())
3705           AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
3706     CheckKind = SanitizerKind::NullabilityReturn;
3707     Handler = SanitizerHandler::NullabilityReturn;
3708   }
3709 
3710   SanitizerScope SanScope(this);
3711 
3712   // Make sure the "return" source location is valid. If we're checking a
3713   // nullability annotation, make sure the preconditions for the check are met.
3714   llvm::BasicBlock *Check = createBasicBlock("nullcheck");
3715   llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck");
3716   llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load");
3717   llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr);
3718   if (requiresReturnValueNullabilityCheck())
3719     CanNullCheck =
3720         Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition);
3721   Builder.CreateCondBr(CanNullCheck, Check, NoCheck);
3722   EmitBlock(Check);
3723 
3724   // Now do the null check.
3725   llvm::Value *Cond = Builder.CreateIsNotNull(RV);
3726   llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)};
3727   llvm::Value *DynamicData[] = {SLocPtr};
3728   EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData);
3729 
3730   EmitBlock(NoCheck);
3731 
3732 #ifndef NDEBUG
3733   // The return location should not be used after the check has been emitted.
3734   ReturnLocation = Address::invalid();
3735 #endif
3736 }
3737 
3738 static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
3739   const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
3740   return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
3741 }
3742 
3743 static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
3744                                           QualType Ty) {
3745   // FIXME: Generate IR in one pass, rather than going back and fixing up these
3746   // placeholders.
3747   llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
3748   llvm::Type *IRPtrTy = IRTy->getPointerTo();
3749   llvm::Value *Placeholder = llvm::PoisonValue::get(IRPtrTy->getPointerTo());
3750 
3751   // FIXME: When we generate this IR in one pass, we shouldn't need
3752   // this win32-specific alignment hack.
3753   CharUnits Align = CharUnits::fromQuantity(4);
3754   Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
3755 
3756   return AggValueSlot::forAddr(Address(Placeholder, IRTy, Align),
3757                                Ty.getQualifiers(),
3758                                AggValueSlot::IsNotDestructed,
3759                                AggValueSlot::DoesNotNeedGCBarriers,
3760                                AggValueSlot::IsNotAliased,
3761                                AggValueSlot::DoesNotOverlap);
3762 }
3763 
3764 void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
3765                                           const VarDecl *param,
3766                                           SourceLocation loc) {
3767   // StartFunction converted the ABI-lowered parameter(s) into a
3768   // local alloca.  We need to turn that into an r-value suitable
3769   // for EmitCall.
3770   Address local = GetAddrOfLocalVar(param);
3771 
3772   QualType type = param->getType();
3773 
3774   if (isInAllocaArgument(CGM.getCXXABI(), type)) {
3775     CGM.ErrorUnsupported(param, "forwarded non-trivially copyable parameter");
3776   }
3777 
3778   // GetAddrOfLocalVar returns a pointer-to-pointer for references,
3779   // but the argument needs to be the original pointer.
3780   if (type->isReferenceType()) {
3781     args.add(RValue::get(Builder.CreateLoad(local)), type);
3782 
3783   // In ARC, move out of consumed arguments so that the release cleanup
3784   // entered by StartFunction doesn't cause an over-release.  This isn't
3785   // optimal -O0 code generation, but it should get cleaned up when
3786   // optimization is enabled.  This also assumes that delegate calls are
3787   // performed exactly once for a set of arguments, but that should be safe.
3788   } else if (getLangOpts().ObjCAutoRefCount &&
3789              param->hasAttr<NSConsumedAttr>() &&
3790              type->isObjCRetainableType()) {
3791     llvm::Value *ptr = Builder.CreateLoad(local);
3792     auto null =
3793       llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
3794     Builder.CreateStore(null, local);
3795     args.add(RValue::get(ptr), type);
3796 
3797   // For the most part, we just need to load the alloca, except that
3798   // aggregate r-values are actually pointers to temporaries.
3799   } else {
3800     args.add(convertTempToRValue(local, type, loc), type);
3801   }
3802 
3803   // Deactivate the cleanup for the callee-destructed param that was pushed.
3804   if (type->isRecordType() && !CurFuncIsThunk &&
3805       type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee() &&
3806       param->needsDestruction(getContext())) {
3807     EHScopeStack::stable_iterator cleanup =
3808         CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param));
3809     assert(cleanup.isValid() &&
3810            "cleanup for callee-destructed param not recorded");
3811     // This unreachable is a temporary marker which will be removed later.
3812     llvm::Instruction *isActive = Builder.CreateUnreachable();
3813     args.addArgCleanupDeactivation(cleanup, isActive);
3814   }
3815 }
3816 
3817 static bool isProvablyNull(llvm::Value *addr) {
3818   return isa<llvm::ConstantPointerNull>(addr);
3819 }
3820 
3821 /// Emit the actual writing-back of a writeback.
3822 static void emitWriteback(CodeGenFunction &CGF,
3823                           const CallArgList::Writeback &writeback) {
3824   const LValue &srcLV = writeback.Source;
3825   Address srcAddr = srcLV.getAddress(CGF);
3826   assert(!isProvablyNull(srcAddr.getPointer()) &&
3827          "shouldn't have writeback for provably null argument");
3828 
3829   llvm::BasicBlock *contBB = nullptr;
3830 
3831   // If the argument wasn't provably non-null, we need to null check
3832   // before doing the store.
3833   bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
3834                                               CGF.CGM.getDataLayout());
3835   if (!provablyNonNull) {
3836     llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
3837     contBB = CGF.createBasicBlock("icr.done");
3838 
3839     llvm::Value *isNull =
3840       CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
3841     CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
3842     CGF.EmitBlock(writebackBB);
3843   }
3844 
3845   // Load the value to writeback.
3846   llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
3847 
3848   // Cast it back, in case we're writing an id to a Foo* or something.
3849   value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
3850                                     "icr.writeback-cast");
3851 
3852   // Perform the writeback.
3853 
3854   // If we have a "to use" value, it's something we need to emit a use
3855   // of.  This has to be carefully threaded in: if it's done after the
3856   // release it's potentially undefined behavior (and the optimizer
3857   // will ignore it), and if it happens before the retain then the
3858   // optimizer could move the release there.
3859   if (writeback.ToUse) {
3860     assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
3861 
3862     // Retain the new value.  No need to block-copy here:  the block's
3863     // being passed up the stack.
3864     value = CGF.EmitARCRetainNonBlock(value);
3865 
3866     // Emit the intrinsic use here.
3867     CGF.EmitARCIntrinsicUse(writeback.ToUse);
3868 
3869     // Load the old value (primitively).
3870     llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
3871 
3872     // Put the new value in place (primitively).
3873     CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
3874 
3875     // Release the old value.
3876     CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
3877 
3878   // Otherwise, we can just do a normal lvalue store.
3879   } else {
3880     CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
3881   }
3882 
3883   // Jump to the continuation block.
3884   if (!provablyNonNull)
3885     CGF.EmitBlock(contBB);
3886 }
3887 
3888 static void emitWritebacks(CodeGenFunction &CGF,
3889                            const CallArgList &args) {
3890   for (const auto &I : args.writebacks())
3891     emitWriteback(CGF, I);
3892 }
3893 
3894 static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
3895                                             const CallArgList &CallArgs) {
3896   ArrayRef<CallArgList::CallArgCleanup> Cleanups =
3897     CallArgs.getCleanupsToDeactivate();
3898   // Iterate in reverse to increase the likelihood of popping the cleanup.
3899   for (const auto &I : llvm::reverse(Cleanups)) {
3900     CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
3901     I.IsActiveIP->eraseFromParent();
3902   }
3903 }
3904 
3905 static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
3906   if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
3907     if (uop->getOpcode() == UO_AddrOf)
3908       return uop->getSubExpr();
3909   return nullptr;
3910 }
3911 
3912 /// Emit an argument that's being passed call-by-writeback.  That is,
3913 /// we are passing the address of an __autoreleased temporary; it
3914 /// might be copy-initialized with the current value of the given
3915 /// address, but it will definitely be copied out of after the call.
3916 static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
3917                              const ObjCIndirectCopyRestoreExpr *CRE) {
3918   LValue srcLV;
3919 
3920   // Make an optimistic effort to emit the address as an l-value.
3921   // This can fail if the argument expression is more complicated.
3922   if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
3923     srcLV = CGF.EmitLValue(lvExpr);
3924 
3925   // Otherwise, just emit it as a scalar.
3926   } else {
3927     Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
3928 
3929     QualType srcAddrType =
3930       CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
3931     srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
3932   }
3933   Address srcAddr = srcLV.getAddress(CGF);
3934 
3935   // The dest and src types don't necessarily match in LLVM terms
3936   // because of the crazy ObjC compatibility rules.
3937 
3938   llvm::PointerType *destType =
3939       cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
3940   llvm::Type *destElemType =
3941       CGF.ConvertTypeForMem(CRE->getType()->getPointeeType());
3942 
3943   // If the address is a constant null, just pass the appropriate null.
3944   if (isProvablyNull(srcAddr.getPointer())) {
3945     args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
3946              CRE->getType());
3947     return;
3948   }
3949 
3950   // Create the temporary.
3951   Address temp =
3952       CGF.CreateTempAlloca(destElemType, CGF.getPointerAlign(), "icr.temp");
3953   // Loading an l-value can introduce a cleanup if the l-value is __weak,
3954   // and that cleanup will be conditional if we can't prove that the l-value
3955   // isn't null, so we need to register a dominating point so that the cleanups
3956   // system will make valid IR.
3957   CodeGenFunction::ConditionalEvaluation condEval(CGF);
3958 
3959   // Zero-initialize it if we're not doing a copy-initialization.
3960   bool shouldCopy = CRE->shouldCopy();
3961   if (!shouldCopy) {
3962     llvm::Value *null =
3963         llvm::ConstantPointerNull::get(cast<llvm::PointerType>(destElemType));
3964     CGF.Builder.CreateStore(null, temp);
3965   }
3966 
3967   llvm::BasicBlock *contBB = nullptr;
3968   llvm::BasicBlock *originBB = nullptr;
3969 
3970   // If the address is *not* known to be non-null, we need to switch.
3971   llvm::Value *finalArgument;
3972 
3973   bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
3974                                               CGF.CGM.getDataLayout());
3975   if (provablyNonNull) {
3976     finalArgument = temp.getPointer();
3977   } else {
3978     llvm::Value *isNull =
3979       CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
3980 
3981     finalArgument = CGF.Builder.CreateSelect(isNull,
3982                                    llvm::ConstantPointerNull::get(destType),
3983                                              temp.getPointer(), "icr.argument");
3984 
3985     // If we need to copy, then the load has to be conditional, which
3986     // means we need control flow.
3987     if (shouldCopy) {
3988       originBB = CGF.Builder.GetInsertBlock();
3989       contBB = CGF.createBasicBlock("icr.cont");
3990       llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
3991       CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
3992       CGF.EmitBlock(copyBB);
3993       condEval.begin(CGF);
3994     }
3995   }
3996 
3997   llvm::Value *valueToUse = nullptr;
3998 
3999   // Perform a copy if necessary.
4000   if (shouldCopy) {
4001     RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
4002     assert(srcRV.isScalar());
4003 
4004     llvm::Value *src = srcRV.getScalarVal();
4005     src = CGF.Builder.CreateBitCast(src, destElemType, "icr.cast");
4006 
4007     // Use an ordinary store, not a store-to-lvalue.
4008     CGF.Builder.CreateStore(src, temp);
4009 
4010     // If optimization is enabled, and the value was held in a
4011     // __strong variable, we need to tell the optimizer that this
4012     // value has to stay alive until we're doing the store back.
4013     // This is because the temporary is effectively unretained,
4014     // and so otherwise we can violate the high-level semantics.
4015     if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
4016         srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
4017       valueToUse = src;
4018     }
4019   }
4020 
4021   // Finish the control flow if we needed it.
4022   if (shouldCopy && !provablyNonNull) {
4023     llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
4024     CGF.EmitBlock(contBB);
4025 
4026     // Make a phi for the value to intrinsically use.
4027     if (valueToUse) {
4028       llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
4029                                                       "icr.to-use");
4030       phiToUse->addIncoming(valueToUse, copyBB);
4031       phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
4032                             originBB);
4033       valueToUse = phiToUse;
4034     }
4035 
4036     condEval.end(CGF);
4037   }
4038 
4039   args.addWriteback(srcLV, temp, valueToUse);
4040   args.add(RValue::get(finalArgument), CRE->getType());
4041 }
4042 
4043 void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
4044   assert(!StackBase);
4045 
4046   // Save the stack.
4047   llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
4048   StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
4049 }
4050 
4051 void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
4052   if (StackBase) {
4053     // Restore the stack after the call.
4054     llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
4055     CGF.Builder.CreateCall(F, StackBase);
4056   }
4057 }
4058 
4059 void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
4060                                           SourceLocation ArgLoc,
4061                                           AbstractCallee AC,
4062                                           unsigned ParmNum) {
4063   if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
4064                          SanOpts.has(SanitizerKind::NullabilityArg)))
4065     return;
4066 
4067   // The param decl may be missing in a variadic function.
4068   auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr;
4069   unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
4070 
4071   // Prefer the nonnull attribute if it's present.
4072   const NonNullAttr *NNAttr = nullptr;
4073   if (SanOpts.has(SanitizerKind::NonnullAttribute))
4074     NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
4075 
4076   bool CanCheckNullability = false;
4077   if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD) {
4078     auto Nullability = PVD->getType()->getNullability(getContext());
4079     CanCheckNullability = Nullability &&
4080                           *Nullability == NullabilityKind::NonNull &&
4081                           PVD->getTypeSourceInfo();
4082   }
4083 
4084   if (!NNAttr && !CanCheckNullability)
4085     return;
4086 
4087   SourceLocation AttrLoc;
4088   SanitizerMask CheckKind;
4089   SanitizerHandler Handler;
4090   if (NNAttr) {
4091     AttrLoc = NNAttr->getLocation();
4092     CheckKind = SanitizerKind::NonnullAttribute;
4093     Handler = SanitizerHandler::NonnullArg;
4094   } else {
4095     AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
4096     CheckKind = SanitizerKind::NullabilityArg;
4097     Handler = SanitizerHandler::NullabilityArg;
4098   }
4099 
4100   SanitizerScope SanScope(this);
4101   llvm::Value *Cond = EmitNonNullRValueCheck(RV, ArgType);
4102   llvm::Constant *StaticData[] = {
4103       EmitCheckSourceLocation(ArgLoc), EmitCheckSourceLocation(AttrLoc),
4104       llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
4105   };
4106   EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, None);
4107 }
4108 
4109 // Check if the call is going to use the inalloca convention. This needs to
4110 // agree with CGFunctionInfo::usesInAlloca. The CGFunctionInfo is arranged
4111 // later, so we can't check it directly.
4112 static bool hasInAllocaArgs(CodeGenModule &CGM, CallingConv ExplicitCC,
4113                             ArrayRef<QualType> ArgTypes) {
4114   // The Swift calling conventions don't go through the target-specific
4115   // argument classification, they never use inalloca.
4116   // TODO: Consider limiting inalloca use to only calling conventions supported
4117   // by MSVC.
4118   if (ExplicitCC == CC_Swift || ExplicitCC == CC_SwiftAsync)
4119     return false;
4120   if (!CGM.getTarget().getCXXABI().isMicrosoft())
4121     return false;
4122   return llvm::any_of(ArgTypes, [&](QualType Ty) {
4123     return isInAllocaArgument(CGM.getCXXABI(), Ty);
4124   });
4125 }
4126 
4127 #ifndef NDEBUG
4128 // Determine whether the given argument is an Objective-C method
4129 // that may have type parameters in its signature.
4130 static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
4131   const DeclContext *dc = method->getDeclContext();
4132   if (const ObjCInterfaceDecl *classDecl = dyn_cast<ObjCInterfaceDecl>(dc)) {
4133     return classDecl->getTypeParamListAsWritten();
4134   }
4135 
4136   if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
4137     return catDecl->getTypeParamList();
4138   }
4139 
4140   return false;
4141 }
4142 #endif
4143 
4144 /// EmitCallArgs - Emit call arguments for a function.
4145 void CodeGenFunction::EmitCallArgs(
4146     CallArgList &Args, PrototypeWrapper Prototype,
4147     llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
4148     AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
4149   SmallVector<QualType, 16> ArgTypes;
4150 
4151   assert((ParamsToSkip == 0 || Prototype.P) &&
4152          "Can't skip parameters if type info is not provided");
4153 
4154   // This variable only captures *explicitly* written conventions, not those
4155   // applied by default via command line flags or target defaults, such as
4156   // thiscall, aapcs, stdcall via -mrtd, etc. Computing that correctly would
4157   // require knowing if this is a C++ instance method or being able to see
4158   // unprototyped FunctionTypes.
4159   CallingConv ExplicitCC = CC_C;
4160 
4161   // First, if a prototype was provided, use those argument types.
4162   bool IsVariadic = false;
4163   if (Prototype.P) {
4164     const auto *MD = Prototype.P.dyn_cast<const ObjCMethodDecl *>();
4165     if (MD) {
4166       IsVariadic = MD->isVariadic();
4167       ExplicitCC = getCallingConventionForDecl(
4168           MD, CGM.getTarget().getTriple().isOSWindows());
4169       ArgTypes.assign(MD->param_type_begin() + ParamsToSkip,
4170                       MD->param_type_end());
4171     } else {
4172       const auto *FPT = Prototype.P.get<const FunctionProtoType *>();
4173       IsVariadic = FPT->isVariadic();
4174       ExplicitCC = FPT->getExtInfo().getCC();
4175       ArgTypes.assign(FPT->param_type_begin() + ParamsToSkip,
4176                       FPT->param_type_end());
4177     }
4178 
4179 #ifndef NDEBUG
4180     // Check that the prototyped types match the argument expression types.
4181     bool isGenericMethod = MD && isObjCMethodWithTypeParams(MD);
4182     CallExpr::const_arg_iterator Arg = ArgRange.begin();
4183     for (QualType Ty : ArgTypes) {
4184       assert(Arg != ArgRange.end() && "Running over edge of argument list!");
4185       assert(
4186           (isGenericMethod || Ty->isVariablyModifiedType() ||
4187            Ty.getNonReferenceType()->isObjCRetainableType() ||
4188            getContext()
4189                    .getCanonicalType(Ty.getNonReferenceType())
4190                    .getTypePtr() ==
4191                getContext().getCanonicalType((*Arg)->getType()).getTypePtr()) &&
4192           "type mismatch in call argument!");
4193       ++Arg;
4194     }
4195 
4196     // Either we've emitted all the call args, or we have a call to variadic
4197     // function.
4198     assert((Arg == ArgRange.end() || IsVariadic) &&
4199            "Extra arguments in non-variadic function!");
4200 #endif
4201   }
4202 
4203   // If we still have any arguments, emit them using the type of the argument.
4204   for (auto *A : llvm::drop_begin(ArgRange, ArgTypes.size()))
4205     ArgTypes.push_back(IsVariadic ? getVarArgType(A) : A->getType());
4206   assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
4207 
4208   // We must evaluate arguments from right to left in the MS C++ ABI,
4209   // because arguments are destroyed left to right in the callee. As a special
4210   // case, there are certain language constructs that require left-to-right
4211   // evaluation, and in those cases we consider the evaluation order requirement
4212   // to trump the "destruction order is reverse construction order" guarantee.
4213   bool LeftToRight =
4214       CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
4215           ? Order == EvaluationOrder::ForceLeftToRight
4216           : Order != EvaluationOrder::ForceRightToLeft;
4217 
4218   auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
4219                                          RValue EmittedArg) {
4220     if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
4221       return;
4222     auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
4223     if (PS == nullptr)
4224       return;
4225 
4226     const auto &Context = getContext();
4227     auto SizeTy = Context.getSizeType();
4228     auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
4229     assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?");
4230     llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
4231                                                      EmittedArg.getScalarVal(),
4232                                                      PS->isDynamic());
4233     Args.add(RValue::get(V), SizeTy);
4234     // If we're emitting args in reverse, be sure to do so with
4235     // pass_object_size, as well.
4236     if (!LeftToRight)
4237       std::swap(Args.back(), *(&Args.back() - 1));
4238   };
4239 
4240   // Insert a stack save if we're going to need any inalloca args.
4241   if (hasInAllocaArgs(CGM, ExplicitCC, ArgTypes)) {
4242     assert(getTarget().getTriple().getArch() == llvm::Triple::x86 &&
4243            "inalloca only supported on x86");
4244     Args.allocateArgumentMemory(*this);
4245   }
4246 
4247   // Evaluate each argument in the appropriate order.
4248   size_t CallArgsStart = Args.size();
4249   for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
4250     unsigned Idx = LeftToRight ? I : E - I - 1;
4251     CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
4252     unsigned InitialArgSize = Args.size();
4253     // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of
4254     // the argument and parameter match or the objc method is parameterized.
4255     assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) ||
4256             getContext().hasSameUnqualifiedType((*Arg)->getType(),
4257                                                 ArgTypes[Idx]) ||
4258             (isa<ObjCMethodDecl>(AC.getDecl()) &&
4259              isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) &&
4260            "Argument and parameter types don't match");
4261     EmitCallArg(Args, *Arg, ArgTypes[Idx]);
4262     // In particular, we depend on it being the last arg in Args, and the
4263     // objectsize bits depend on there only being one arg if !LeftToRight.
4264     assert(InitialArgSize + 1 == Args.size() &&
4265            "The code below depends on only adding one arg per EmitCallArg");
4266     (void)InitialArgSize;
4267     // Since pointer argument are never emitted as LValue, it is safe to emit
4268     // non-null argument check for r-value only.
4269     if (!Args.back().hasLValue()) {
4270       RValue RVArg = Args.back().getKnownRValue();
4271       EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
4272                           ParamsToSkip + Idx);
4273       // @llvm.objectsize should never have side-effects and shouldn't need
4274       // destruction/cleanups, so we can safely "emit" it after its arg,
4275       // regardless of right-to-leftness
4276       MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
4277     }
4278   }
4279 
4280   if (!LeftToRight) {
4281     // Un-reverse the arguments we just evaluated so they match up with the LLVM
4282     // IR function.
4283     std::reverse(Args.begin() + CallArgsStart, Args.end());
4284   }
4285 }
4286 
4287 namespace {
4288 
4289 struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
4290   DestroyUnpassedArg(Address Addr, QualType Ty)
4291       : Addr(Addr), Ty(Ty) {}
4292 
4293   Address Addr;
4294   QualType Ty;
4295 
4296   void Emit(CodeGenFunction &CGF, Flags flags) override {
4297     QualType::DestructionKind DtorKind = Ty.isDestructedType();
4298     if (DtorKind == QualType::DK_cxx_destructor) {
4299       const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
4300       assert(!Dtor->isTrivial());
4301       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
4302                                 /*Delegating=*/false, Addr, Ty);
4303     } else {
4304       CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty));
4305     }
4306   }
4307 };
4308 
4309 struct DisableDebugLocationUpdates {
4310   CodeGenFunction &CGF;
4311   bool disabledDebugInfo;
4312   DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
4313     if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
4314       CGF.disableDebugInfo();
4315   }
4316   ~DisableDebugLocationUpdates() {
4317     if (disabledDebugInfo)
4318       CGF.enableDebugInfo();
4319   }
4320 };
4321 
4322 } // end anonymous namespace
4323 
4324 RValue CallArg::getRValue(CodeGenFunction &CGF) const {
4325   if (!HasLV)
4326     return RV;
4327   LValue Copy = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty), Ty);
4328   CGF.EmitAggregateCopy(Copy, LV, Ty, AggValueSlot::DoesNotOverlap,
4329                         LV.isVolatile());
4330   IsUsed = true;
4331   return RValue::getAggregate(Copy.getAddress(CGF));
4332 }
4333 
4334 void CallArg::copyInto(CodeGenFunction &CGF, Address Addr) const {
4335   LValue Dst = CGF.MakeAddrLValue(Addr, Ty);
4336   if (!HasLV && RV.isScalar())
4337     CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*isInit=*/true);
4338   else if (!HasLV && RV.isComplex())
4339     CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true);
4340   else {
4341     auto Addr = HasLV ? LV.getAddress(CGF) : RV.getAggregateAddress();
4342     LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty);
4343     // We assume that call args are never copied into subobjects.
4344     CGF.EmitAggregateCopy(Dst, SrcLV, Ty, AggValueSlot::DoesNotOverlap,
4345                           HasLV ? LV.isVolatileQualified()
4346                                 : RV.isVolatileQualified());
4347   }
4348   IsUsed = true;
4349 }
4350 
4351 void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
4352                                   QualType type) {
4353   DisableDebugLocationUpdates Dis(*this, E);
4354   if (const ObjCIndirectCopyRestoreExpr *CRE
4355         = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
4356     assert(getLangOpts().ObjCAutoRefCount);
4357     return emitWritebackArg(*this, args, CRE);
4358   }
4359 
4360   assert(type->isReferenceType() == E->isGLValue() &&
4361          "reference binding to unmaterialized r-value!");
4362 
4363   if (E->isGLValue()) {
4364     assert(E->getObjectKind() == OK_Ordinary);
4365     return args.add(EmitReferenceBindingToExpr(E), type);
4366   }
4367 
4368   bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
4369 
4370   // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
4371   // However, we still have to push an EH-only cleanup in case we unwind before
4372   // we make it to the call.
4373   if (type->isRecordType() &&
4374       type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
4375     // If we're using inalloca, use the argument memory.  Otherwise, use a
4376     // temporary.
4377     AggValueSlot Slot = args.isUsingInAlloca()
4378         ? createPlaceholderSlot(*this, type) : CreateAggTemp(type, "agg.tmp");
4379 
4380     bool DestroyedInCallee = true, NeedsEHCleanup = true;
4381     if (const auto *RD = type->getAsCXXRecordDecl())
4382       DestroyedInCallee = RD->hasNonTrivialDestructor();
4383     else
4384       NeedsEHCleanup = needsEHCleanup(type.isDestructedType());
4385 
4386     if (DestroyedInCallee)
4387       Slot.setExternallyDestructed();
4388 
4389     EmitAggExpr(E, Slot);
4390     RValue RV = Slot.asRValue();
4391     args.add(RV, type);
4392 
4393     if (DestroyedInCallee && NeedsEHCleanup) {
4394       // Create a no-op GEP between the placeholder and the cleanup so we can
4395       // RAUW it successfully.  It also serves as a marker of the first
4396       // instruction where the cleanup is active.
4397       pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
4398                                               type);
4399       // This unreachable is a temporary marker which will be removed later.
4400       llvm::Instruction *IsActive = Builder.CreateUnreachable();
4401       args.addArgCleanupDeactivation(EHStack.stable_begin(), IsActive);
4402     }
4403     return;
4404   }
4405 
4406   if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
4407       cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
4408     LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
4409     assert(L.isSimple());
4410     args.addUncopiedAggregate(L, type);
4411     return;
4412   }
4413 
4414   args.add(EmitAnyExprToTemp(E), type);
4415 }
4416 
4417 QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
4418   // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
4419   // implicitly widens null pointer constants that are arguments to varargs
4420   // functions to pointer-sized ints.
4421   if (!getTarget().getTriple().isOSWindows())
4422     return Arg->getType();
4423 
4424   if (Arg->getType()->isIntegerType() &&
4425       getContext().getTypeSize(Arg->getType()) <
4426           getContext().getTargetInfo().getPointerWidth(0) &&
4427       Arg->isNullPointerConstant(getContext(),
4428                                  Expr::NPC_ValueDependentIsNotNull)) {
4429     return getContext().getIntPtrType();
4430   }
4431 
4432   return Arg->getType();
4433 }
4434 
4435 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4436 // optimizer it can aggressively ignore unwind edges.
4437 void
4438 CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
4439   if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
4440       !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
4441     Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
4442                       CGM.getNoObjCARCExceptionsMetadata());
4443 }
4444 
4445 /// Emits a call to the given no-arguments nounwind runtime function.
4446 llvm::CallInst *
4447 CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4448                                          const llvm::Twine &name) {
4449   return EmitNounwindRuntimeCall(callee, None, name);
4450 }
4451 
4452 /// Emits a call to the given nounwind runtime function.
4453 llvm::CallInst *
4454 CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4455                                          ArrayRef<llvm::Value *> args,
4456                                          const llvm::Twine &name) {
4457   llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
4458   call->setDoesNotThrow();
4459   return call;
4460 }
4461 
4462 /// Emits a simple call (never an invoke) to the given no-arguments
4463 /// runtime function.
4464 llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
4465                                                  const llvm::Twine &name) {
4466   return EmitRuntimeCall(callee, None, name);
4467 }
4468 
4469 // Calls which may throw must have operand bundles indicating which funclet
4470 // they are nested within.
4471 SmallVector<llvm::OperandBundleDef, 1>
4472 CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) {
4473   SmallVector<llvm::OperandBundleDef, 1> BundleList;
4474   // There is no need for a funclet operand bundle if we aren't inside a
4475   // funclet.
4476   if (!CurrentFuncletPad)
4477     return BundleList;
4478 
4479   // Skip intrinsics which cannot throw.
4480   auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
4481   if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
4482     return BundleList;
4483 
4484   BundleList.emplace_back("funclet", CurrentFuncletPad);
4485   return BundleList;
4486 }
4487 
4488 /// Emits a simple call (never an invoke) to the given runtime function.
4489 llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
4490                                                  ArrayRef<llvm::Value *> args,
4491                                                  const llvm::Twine &name) {
4492   llvm::CallInst *call = Builder.CreateCall(
4493       callee, args, getBundlesForFunclet(callee.getCallee()), name);
4494   call->setCallingConv(getRuntimeCC());
4495   return call;
4496 }
4497 
4498 /// Emits a call or invoke to the given noreturn runtime function.
4499 void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(
4500     llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) {
4501   SmallVector<llvm::OperandBundleDef, 1> BundleList =
4502       getBundlesForFunclet(callee.getCallee());
4503 
4504   if (getInvokeDest()) {
4505     llvm::InvokeInst *invoke =
4506       Builder.CreateInvoke(callee,
4507                            getUnreachableBlock(),
4508                            getInvokeDest(),
4509                            args,
4510                            BundleList);
4511     invoke->setDoesNotReturn();
4512     invoke->setCallingConv(getRuntimeCC());
4513   } else {
4514     llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
4515     call->setDoesNotReturn();
4516     call->setCallingConv(getRuntimeCC());
4517     Builder.CreateUnreachable();
4518   }
4519 }
4520 
4521 /// Emits a call or invoke instruction to the given nullary runtime function.
4522 llvm::CallBase *
4523 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4524                                          const Twine &name) {
4525   return EmitRuntimeCallOrInvoke(callee, None, name);
4526 }
4527 
4528 /// Emits a call or invoke instruction to the given runtime function.
4529 llvm::CallBase *
4530 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4531                                          ArrayRef<llvm::Value *> args,
4532                                          const Twine &name) {
4533   llvm::CallBase *call = EmitCallOrInvoke(callee, args, name);
4534   call->setCallingConv(getRuntimeCC());
4535   return call;
4536 }
4537 
4538 /// Emits a call or invoke instruction to the given function, depending
4539 /// on the current state of the EH stack.
4540 llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee,
4541                                                   ArrayRef<llvm::Value *> Args,
4542                                                   const Twine &Name) {
4543   llvm::BasicBlock *InvokeDest = getInvokeDest();
4544   SmallVector<llvm::OperandBundleDef, 1> BundleList =
4545       getBundlesForFunclet(Callee.getCallee());
4546 
4547   llvm::CallBase *Inst;
4548   if (!InvokeDest)
4549     Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
4550   else {
4551     llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
4552     Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
4553                                 Name);
4554     EmitBlock(ContBB);
4555   }
4556 
4557   // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4558   // optimizer it can aggressively ignore unwind edges.
4559   if (CGM.getLangOpts().ObjCAutoRefCount)
4560     AddObjCARCExceptionMetadata(Inst);
4561 
4562   return Inst;
4563 }
4564 
4565 void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
4566                                                   llvm::Value *New) {
4567   DeferredReplacements.push_back(
4568       std::make_pair(llvm::WeakTrackingVH(Old), New));
4569 }
4570 
4571 namespace {
4572 
4573 /// Specify given \p NewAlign as the alignment of return value attribute. If
4574 /// such attribute already exists, re-set it to the maximal one of two options.
4575 LLVM_NODISCARD llvm::AttributeList
4576 maybeRaiseRetAlignmentAttribute(llvm::LLVMContext &Ctx,
4577                                 const llvm::AttributeList &Attrs,
4578                                 llvm::Align NewAlign) {
4579   llvm::Align CurAlign = Attrs.getRetAlignment().valueOrOne();
4580   if (CurAlign >= NewAlign)
4581     return Attrs;
4582   llvm::Attribute AlignAttr = llvm::Attribute::getWithAlignment(Ctx, NewAlign);
4583   return Attrs.removeRetAttribute(Ctx, llvm::Attribute::AttrKind::Alignment)
4584       .addRetAttribute(Ctx, AlignAttr);
4585 }
4586 
4587 template <typename AlignedAttrTy> class AbstractAssumeAlignedAttrEmitter {
4588 protected:
4589   CodeGenFunction &CGF;
4590 
4591   /// We do nothing if this is, or becomes, nullptr.
4592   const AlignedAttrTy *AA = nullptr;
4593 
4594   llvm::Value *Alignment = nullptr;      // May or may not be a constant.
4595   llvm::ConstantInt *OffsetCI = nullptr; // Constant, hopefully zero.
4596 
4597   AbstractAssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
4598       : CGF(CGF_) {
4599     if (!FuncDecl)
4600       return;
4601     AA = FuncDecl->getAttr<AlignedAttrTy>();
4602   }
4603 
4604 public:
4605   /// If we can, materialize the alignment as an attribute on return value.
4606   LLVM_NODISCARD llvm::AttributeList
4607   TryEmitAsCallSiteAttribute(const llvm::AttributeList &Attrs) {
4608     if (!AA || OffsetCI || CGF.SanOpts.has(SanitizerKind::Alignment))
4609       return Attrs;
4610     const auto *AlignmentCI = dyn_cast<llvm::ConstantInt>(Alignment);
4611     if (!AlignmentCI)
4612       return Attrs;
4613     // We may legitimately have non-power-of-2 alignment here.
4614     // If so, this is UB land, emit it via `@llvm.assume` instead.
4615     if (!AlignmentCI->getValue().isPowerOf2())
4616       return Attrs;
4617     llvm::AttributeList NewAttrs = maybeRaiseRetAlignmentAttribute(
4618         CGF.getLLVMContext(), Attrs,
4619         llvm::Align(
4620             AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment)));
4621     AA = nullptr; // We're done. Disallow doing anything else.
4622     return NewAttrs;
4623   }
4624 
4625   /// Emit alignment assumption.
4626   /// This is a general fallback that we take if either there is an offset,
4627   /// or the alignment is variable or we are sanitizing for alignment.
4628   void EmitAsAnAssumption(SourceLocation Loc, QualType RetTy, RValue &Ret) {
4629     if (!AA)
4630       return;
4631     CGF.emitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc,
4632                                 AA->getLocation(), Alignment, OffsetCI);
4633     AA = nullptr; // We're done. Disallow doing anything else.
4634   }
4635 };
4636 
4637 /// Helper data structure to emit `AssumeAlignedAttr`.
4638 class AssumeAlignedAttrEmitter final
4639     : public AbstractAssumeAlignedAttrEmitter<AssumeAlignedAttr> {
4640 public:
4641   AssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
4642       : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
4643     if (!AA)
4644       return;
4645     // It is guaranteed that the alignment/offset are constants.
4646     Alignment = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AA->getAlignment()));
4647     if (Expr *Offset = AA->getOffset()) {
4648       OffsetCI = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(Offset));
4649       if (OffsetCI->isNullValue()) // Canonicalize zero offset to no offset.
4650         OffsetCI = nullptr;
4651     }
4652   }
4653 };
4654 
4655 /// Helper data structure to emit `AllocAlignAttr`.
4656 class AllocAlignAttrEmitter final
4657     : public AbstractAssumeAlignedAttrEmitter<AllocAlignAttr> {
4658 public:
4659   AllocAlignAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl,
4660                         const CallArgList &CallArgs)
4661       : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
4662     if (!AA)
4663       return;
4664     // Alignment may or may not be a constant, and that is okay.
4665     Alignment = CallArgs[AA->getParamIndex().getLLVMIndex()]
4666                     .getRValue(CGF)
4667                     .getScalarVal();
4668   }
4669 };
4670 
4671 } // namespace
4672 
4673 static unsigned getMaxVectorWidth(const llvm::Type *Ty) {
4674   if (auto *VT = dyn_cast<llvm::VectorType>(Ty))
4675     return VT->getPrimitiveSizeInBits().getKnownMinSize();
4676   if (auto *AT = dyn_cast<llvm::ArrayType>(Ty))
4677     return getMaxVectorWidth(AT->getElementType());
4678 
4679   unsigned MaxVectorWidth = 0;
4680   if (auto *ST = dyn_cast<llvm::StructType>(Ty))
4681     for (auto *I : ST->elements())
4682       MaxVectorWidth = std::max(MaxVectorWidth, getMaxVectorWidth(I));
4683   return MaxVectorWidth;
4684 }
4685 
4686 RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
4687                                  const CGCallee &Callee,
4688                                  ReturnValueSlot ReturnValue,
4689                                  const CallArgList &CallArgs,
4690                                  llvm::CallBase **callOrInvoke, bool IsMustTail,
4691                                  SourceLocation Loc) {
4692   // FIXME: We no longer need the types from CallArgs; lift up and simplify.
4693 
4694   assert(Callee.isOrdinary() || Callee.isVirtual());
4695 
4696   // Handle struct-return functions by passing a pointer to the
4697   // location that we would like to return into.
4698   QualType RetTy = CallInfo.getReturnType();
4699   const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
4700 
4701   llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
4702 
4703   const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
4704   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
4705     // We can only guarantee that a function is called from the correct
4706     // context/function based on the appropriate target attributes,
4707     // so only check in the case where we have both always_inline and target
4708     // since otherwise we could be making a conditional call after a check for
4709     // the proper cpu features (and it won't cause code generation issues due to
4710     // function based code generation).
4711     if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4712         TargetDecl->hasAttr<TargetAttr>())
4713       checkTargetFeatures(Loc, FD);
4714 
4715     // Some architectures (such as x86-64) have the ABI changed based on
4716     // attribute-target/features. Give them a chance to diagnose.
4717     CGM.getTargetCodeGenInfo().checkFunctionCallABI(
4718         CGM, Loc, dyn_cast_or_null<FunctionDecl>(CurCodeDecl), FD, CallArgs);
4719   }
4720 
4721 #ifndef NDEBUG
4722   if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) {
4723     // For an inalloca varargs function, we don't expect CallInfo to match the
4724     // function pointer's type, because the inalloca struct a will have extra
4725     // fields in it for the varargs parameters.  Code later in this function
4726     // bitcasts the function pointer to the type derived from CallInfo.
4727     //
4728     // In other cases, we assert that the types match up (until pointers stop
4729     // having pointee types).
4730     if (Callee.isVirtual())
4731       assert(IRFuncTy == Callee.getVirtualFunctionType());
4732     else {
4733       llvm::PointerType *PtrTy =
4734           llvm::cast<llvm::PointerType>(Callee.getFunctionPointer()->getType());
4735       assert(PtrTy->isOpaqueOrPointeeTypeMatches(IRFuncTy));
4736     }
4737   }
4738 #endif
4739 
4740   // 1. Set up the arguments.
4741 
4742   // If we're using inalloca, insert the allocation after the stack save.
4743   // FIXME: Do this earlier rather than hacking it in here!
4744   Address ArgMemory = Address::invalid();
4745   if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
4746     const llvm::DataLayout &DL = CGM.getDataLayout();
4747     llvm::Instruction *IP = CallArgs.getStackBase();
4748     llvm::AllocaInst *AI;
4749     if (IP) {
4750       IP = IP->getNextNode();
4751       AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(),
4752                                 "argmem", IP);
4753     } else {
4754       AI = CreateTempAlloca(ArgStruct, "argmem");
4755     }
4756     auto Align = CallInfo.getArgStructAlignment();
4757     AI->setAlignment(Align.getAsAlign());
4758     AI->setUsedWithInAlloca(true);
4759     assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
4760     ArgMemory = Address(AI, ArgStruct, Align);
4761   }
4762 
4763   ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
4764   SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
4765 
4766   // If the call returns a temporary with struct return, create a temporary
4767   // alloca to hold the result, unless one is given to us.
4768   Address SRetPtr = Address::invalid();
4769   Address SRetAlloca = Address::invalid();
4770   llvm::Value *UnusedReturnSizePtr = nullptr;
4771   if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
4772     if (!ReturnValue.isNull()) {
4773       SRetPtr = ReturnValue.getValue();
4774     } else {
4775       SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca);
4776       if (HaveInsertPoint() && ReturnValue.isUnused()) {
4777         llvm::TypeSize size =
4778             CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
4779         UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer());
4780       }
4781     }
4782     if (IRFunctionArgs.hasSRetArg()) {
4783       IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
4784     } else if (RetAI.isInAlloca()) {
4785       Address Addr =
4786           Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
4787       Builder.CreateStore(SRetPtr.getPointer(), Addr);
4788     }
4789   }
4790 
4791   Address swiftErrorTemp = Address::invalid();
4792   Address swiftErrorArg = Address::invalid();
4793 
4794   // When passing arguments using temporary allocas, we need to add the
4795   // appropriate lifetime markers. This vector keeps track of all the lifetime
4796   // markers that need to be ended right after the call.
4797   SmallVector<CallLifetimeEnd, 2> CallLifetimeEndAfterCall;
4798 
4799   // Translate all of the arguments as necessary to match the IR lowering.
4800   assert(CallInfo.arg_size() == CallArgs.size() &&
4801          "Mismatch between function signature & arguments.");
4802   unsigned ArgNo = 0;
4803   CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
4804   for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
4805        I != E; ++I, ++info_it, ++ArgNo) {
4806     const ABIArgInfo &ArgInfo = info_it->info;
4807 
4808     // Insert a padding argument to ensure proper alignment.
4809     if (IRFunctionArgs.hasPaddingArg(ArgNo))
4810       IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
4811           llvm::UndefValue::get(ArgInfo.getPaddingType());
4812 
4813     unsigned FirstIRArg, NumIRArgs;
4814     std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
4815 
4816     switch (ArgInfo.getKind()) {
4817     case ABIArgInfo::InAlloca: {
4818       assert(NumIRArgs == 0);
4819       assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
4820       if (I->isAggregate()) {
4821         Address Addr = I->hasLValue()
4822                            ? I->getKnownLValue().getAddress(*this)
4823                            : I->getKnownRValue().getAggregateAddress();
4824         llvm::Instruction *Placeholder =
4825             cast<llvm::Instruction>(Addr.getPointer());
4826 
4827         if (!ArgInfo.getInAllocaIndirect()) {
4828           // Replace the placeholder with the appropriate argument slot GEP.
4829           CGBuilderTy::InsertPoint IP = Builder.saveIP();
4830           Builder.SetInsertPoint(Placeholder);
4831           Addr = Builder.CreateStructGEP(ArgMemory,
4832                                          ArgInfo.getInAllocaFieldIndex());
4833           Builder.restoreIP(IP);
4834         } else {
4835           // For indirect things such as overaligned structs, replace the
4836           // placeholder with a regular aggregate temporary alloca. Store the
4837           // address of this alloca into the struct.
4838           Addr = CreateMemTemp(info_it->type, "inalloca.indirect.tmp");
4839           Address ArgSlot = Builder.CreateStructGEP(
4840               ArgMemory, ArgInfo.getInAllocaFieldIndex());
4841           Builder.CreateStore(Addr.getPointer(), ArgSlot);
4842         }
4843         deferPlaceholderReplacement(Placeholder, Addr.getPointer());
4844       } else if (ArgInfo.getInAllocaIndirect()) {
4845         // Make a temporary alloca and store the address of it into the argument
4846         // struct.
4847         Address Addr = CreateMemTempWithoutCast(
4848             I->Ty, getContext().getTypeAlignInChars(I->Ty),
4849             "indirect-arg-temp");
4850         I->copyInto(*this, Addr);
4851         Address ArgSlot =
4852             Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
4853         Builder.CreateStore(Addr.getPointer(), ArgSlot);
4854       } else {
4855         // Store the RValue into the argument struct.
4856         Address Addr =
4857             Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
4858         // There are some cases where a trivial bitcast is not avoidable.  The
4859         // definition of a type later in a translation unit may change it's type
4860         // from {}* to (%struct.foo*)*.
4861         Addr = Builder.CreateElementBitCast(Addr, ConvertTypeForMem(I->Ty));
4862         I->copyInto(*this, Addr);
4863       }
4864       break;
4865     }
4866 
4867     case ABIArgInfo::Indirect:
4868     case ABIArgInfo::IndirectAliased: {
4869       assert(NumIRArgs == 1);
4870       if (!I->isAggregate()) {
4871         // Make a temporary alloca to pass the argument.
4872         Address Addr = CreateMemTempWithoutCast(
4873             I->Ty, ArgInfo.getIndirectAlign(), "indirect-arg-temp");
4874         IRCallArgs[FirstIRArg] = Addr.getPointer();
4875 
4876         I->copyInto(*this, Addr);
4877       } else {
4878         // We want to avoid creating an unnecessary temporary+copy here;
4879         // however, we need one in three cases:
4880         // 1. If the argument is not byval, and we are required to copy the
4881         //    source.  (This case doesn't occur on any common architecture.)
4882         // 2. If the argument is byval, RV is not sufficiently aligned, and
4883         //    we cannot force it to be sufficiently aligned.
4884         // 3. If the argument is byval, but RV is not located in default
4885         //    or alloca address space.
4886         Address Addr = I->hasLValue()
4887                            ? I->getKnownLValue().getAddress(*this)
4888                            : I->getKnownRValue().getAggregateAddress();
4889         llvm::Value *V = Addr.getPointer();
4890         CharUnits Align = ArgInfo.getIndirectAlign();
4891         const llvm::DataLayout *TD = &CGM.getDataLayout();
4892 
4893         assert((FirstIRArg >= IRFuncTy->getNumParams() ||
4894                 IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() ==
4895                     TD->getAllocaAddrSpace()) &&
4896                "indirect argument must be in alloca address space");
4897 
4898         bool NeedCopy = false;
4899 
4900         if (Addr.getAlignment() < Align &&
4901             llvm::getOrEnforceKnownAlignment(V, Align.getAsAlign(), *TD) <
4902                 Align.getAsAlign()) {
4903           NeedCopy = true;
4904         } else if (I->hasLValue()) {
4905           auto LV = I->getKnownLValue();
4906           auto AS = LV.getAddressSpace();
4907 
4908           if (!ArgInfo.getIndirectByVal() ||
4909               (LV.getAlignment() < getContext().getTypeAlignInChars(I->Ty))) {
4910             NeedCopy = true;
4911           }
4912           if (!getLangOpts().OpenCL) {
4913             if ((ArgInfo.getIndirectByVal() &&
4914                 (AS != LangAS::Default &&
4915                  AS != CGM.getASTAllocaAddressSpace()))) {
4916               NeedCopy = true;
4917             }
4918           }
4919           // For OpenCL even if RV is located in default or alloca address space
4920           // we don't want to perform address space cast for it.
4921           else if ((ArgInfo.getIndirectByVal() &&
4922                     Addr.getType()->getAddressSpace() != IRFuncTy->
4923                       getParamType(FirstIRArg)->getPointerAddressSpace())) {
4924             NeedCopy = true;
4925           }
4926         }
4927 
4928         if (NeedCopy) {
4929           // Create an aligned temporary, and copy to it.
4930           Address AI = CreateMemTempWithoutCast(
4931               I->Ty, ArgInfo.getIndirectAlign(), "byval-temp");
4932           IRCallArgs[FirstIRArg] = AI.getPointer();
4933 
4934           // Emit lifetime markers for the temporary alloca.
4935           llvm::TypeSize ByvalTempElementSize =
4936               CGM.getDataLayout().getTypeAllocSize(AI.getElementType());
4937           llvm::Value *LifetimeSize =
4938               EmitLifetimeStart(ByvalTempElementSize, AI.getPointer());
4939 
4940           // Add cleanup code to emit the end lifetime marker after the call.
4941           if (LifetimeSize) // In case we disabled lifetime markers.
4942             CallLifetimeEndAfterCall.emplace_back(AI, LifetimeSize);
4943 
4944           // Generate the copy.
4945           I->copyInto(*this, AI);
4946         } else {
4947           // Skip the extra memcpy call.
4948           auto *T = llvm::PointerType::getWithSamePointeeType(
4949               cast<llvm::PointerType>(V->getType()),
4950               CGM.getDataLayout().getAllocaAddrSpace());
4951           IRCallArgs[FirstIRArg] = getTargetHooks().performAddrSpaceCast(
4952               *this, V, LangAS::Default, CGM.getASTAllocaAddressSpace(), T,
4953               true);
4954         }
4955       }
4956       break;
4957     }
4958 
4959     case ABIArgInfo::Ignore:
4960       assert(NumIRArgs == 0);
4961       break;
4962 
4963     case ABIArgInfo::Extend:
4964     case ABIArgInfo::Direct: {
4965       if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
4966           ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
4967           ArgInfo.getDirectOffset() == 0) {
4968         assert(NumIRArgs == 1);
4969         llvm::Value *V;
4970         if (!I->isAggregate())
4971           V = I->getKnownRValue().getScalarVal();
4972         else
4973           V = Builder.CreateLoad(
4974               I->hasLValue() ? I->getKnownLValue().getAddress(*this)
4975                              : I->getKnownRValue().getAggregateAddress());
4976 
4977         // Implement swifterror by copying into a new swifterror argument.
4978         // We'll write back in the normal path out of the call.
4979         if (CallInfo.getExtParameterInfo(ArgNo).getABI()
4980               == ParameterABI::SwiftErrorResult) {
4981           assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
4982 
4983           QualType pointeeTy = I->Ty->getPointeeType();
4984           swiftErrorArg = Address(V, ConvertTypeForMem(pointeeTy),
4985                                   getContext().getTypeAlignInChars(pointeeTy));
4986 
4987           swiftErrorTemp =
4988             CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
4989           V = swiftErrorTemp.getPointer();
4990           cast<llvm::AllocaInst>(V)->setSwiftError(true);
4991 
4992           llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
4993           Builder.CreateStore(errorValue, swiftErrorTemp);
4994         }
4995 
4996         // We might have to widen integers, but we should never truncate.
4997         if (ArgInfo.getCoerceToType() != V->getType() &&
4998             V->getType()->isIntegerTy())
4999           V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
5000 
5001         // If the argument doesn't match, perform a bitcast to coerce it.  This
5002         // can happen due to trivial type mismatches.
5003         if (FirstIRArg < IRFuncTy->getNumParams() &&
5004             V->getType() != IRFuncTy->getParamType(FirstIRArg))
5005           V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
5006 
5007         IRCallArgs[FirstIRArg] = V;
5008         break;
5009       }
5010 
5011       // FIXME: Avoid the conversion through memory if possible.
5012       Address Src = Address::invalid();
5013       if (!I->isAggregate()) {
5014         Src = CreateMemTemp(I->Ty, "coerce");
5015         I->copyInto(*this, Src);
5016       } else {
5017         Src = I->hasLValue() ? I->getKnownLValue().getAddress(*this)
5018                              : I->getKnownRValue().getAggregateAddress();
5019       }
5020 
5021       // If the value is offset in memory, apply the offset now.
5022       Src = emitAddressAtOffset(*this, Src, ArgInfo);
5023 
5024       // Fast-isel and the optimizer generally like scalar values better than
5025       // FCAs, so we flatten them if this is safe to do for this argument.
5026       llvm::StructType *STy =
5027             dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
5028       if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
5029         llvm::Type *SrcTy = Src.getElementType();
5030         uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
5031         uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
5032 
5033         // If the source type is smaller than the destination type of the
5034         // coerce-to logic, copy the source value into a temp alloca the size
5035         // of the destination type to allow loading all of it. The bits past
5036         // the source value are left undef.
5037         if (SrcSize < DstSize) {
5038           Address TempAlloca
5039             = CreateTempAlloca(STy, Src.getAlignment(),
5040                                Src.getName() + ".coerce");
5041           Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
5042           Src = TempAlloca;
5043         } else {
5044           Src = Builder.CreateElementBitCast(Src, STy);
5045         }
5046 
5047         assert(NumIRArgs == STy->getNumElements());
5048         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
5049           Address EltPtr = Builder.CreateStructGEP(Src, i);
5050           llvm::Value *LI = Builder.CreateLoad(EltPtr);
5051           IRCallArgs[FirstIRArg + i] = LI;
5052         }
5053       } else {
5054         // In the simple case, just pass the coerced loaded value.
5055         assert(NumIRArgs == 1);
5056         llvm::Value *Load =
5057             CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
5058 
5059         if (CallInfo.isCmseNSCall()) {
5060           // For certain parameter types, clear padding bits, as they may reveal
5061           // sensitive information.
5062           // Small struct/union types are passed as integer arrays.
5063           auto *ATy = dyn_cast<llvm::ArrayType>(Load->getType());
5064           if (ATy != nullptr && isa<RecordType>(I->Ty.getCanonicalType()))
5065             Load = EmitCMSEClearRecord(Load, ATy, I->Ty);
5066         }
5067         IRCallArgs[FirstIRArg] = Load;
5068       }
5069 
5070       break;
5071     }
5072 
5073     case ABIArgInfo::CoerceAndExpand: {
5074       auto coercionType = ArgInfo.getCoerceAndExpandType();
5075       auto layout = CGM.getDataLayout().getStructLayout(coercionType);
5076 
5077       llvm::Value *tempSize = nullptr;
5078       Address addr = Address::invalid();
5079       Address AllocaAddr = Address::invalid();
5080       if (I->isAggregate()) {
5081         addr = I->hasLValue() ? I->getKnownLValue().getAddress(*this)
5082                               : I->getKnownRValue().getAggregateAddress();
5083 
5084       } else {
5085         RValue RV = I->getKnownRValue();
5086         assert(RV.isScalar()); // complex should always just be direct
5087 
5088         llvm::Type *scalarType = RV.getScalarVal()->getType();
5089         auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
5090         auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType);
5091 
5092         // Materialize to a temporary.
5093         addr =
5094             CreateTempAlloca(RV.getScalarVal()->getType(),
5095                              CharUnits::fromQuantity(std::max(
5096                                  layout->getAlignment().value(), scalarAlign)),
5097                              "tmp",
5098                              /*ArraySize=*/nullptr, &AllocaAddr);
5099         tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer());
5100 
5101         Builder.CreateStore(RV.getScalarVal(), addr);
5102       }
5103 
5104       addr = Builder.CreateElementBitCast(addr, coercionType);
5105 
5106       unsigned IRArgPos = FirstIRArg;
5107       for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
5108         llvm::Type *eltType = coercionType->getElementType(i);
5109         if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
5110         Address eltAddr = Builder.CreateStructGEP(addr, i);
5111         llvm::Value *elt = Builder.CreateLoad(eltAddr);
5112         IRCallArgs[IRArgPos++] = elt;
5113       }
5114       assert(IRArgPos == FirstIRArg + NumIRArgs);
5115 
5116       if (tempSize) {
5117         EmitLifetimeEnd(tempSize, AllocaAddr.getPointer());
5118       }
5119 
5120       break;
5121     }
5122 
5123     case ABIArgInfo::Expand: {
5124       unsigned IRArgPos = FirstIRArg;
5125       ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos);
5126       assert(IRArgPos == FirstIRArg + NumIRArgs);
5127       break;
5128     }
5129     }
5130   }
5131 
5132   const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this);
5133   llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer();
5134 
5135   // If we're using inalloca, set up that argument.
5136   if (ArgMemory.isValid()) {
5137     llvm::Value *Arg = ArgMemory.getPointer();
5138     if (CallInfo.isVariadic()) {
5139       // When passing non-POD arguments by value to variadic functions, we will
5140       // end up with a variadic prototype and an inalloca call site.  In such
5141       // cases, we can't do any parameter mismatch checks.  Give up and bitcast
5142       // the callee.
5143       unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace();
5144       CalleePtr =
5145           Builder.CreateBitCast(CalleePtr, IRFuncTy->getPointerTo(CalleeAS));
5146     } else {
5147       llvm::Type *LastParamTy =
5148           IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
5149       if (Arg->getType() != LastParamTy) {
5150 #ifndef NDEBUG
5151         // Assert that these structs have equivalent element types.
5152         llvm::StructType *FullTy = CallInfo.getArgStruct();
5153         if (!LastParamTy->isOpaquePointerTy()) {
5154           llvm::StructType *DeclaredTy = cast<llvm::StructType>(
5155               LastParamTy->getNonOpaquePointerElementType());
5156           assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
5157           for (auto DI = DeclaredTy->element_begin(),
5158                     DE = DeclaredTy->element_end(),
5159                     FI = FullTy->element_begin();
5160                DI != DE; ++DI, ++FI)
5161             assert(*DI == *FI);
5162         }
5163 #endif
5164         Arg = Builder.CreateBitCast(Arg, LastParamTy);
5165       }
5166     }
5167     assert(IRFunctionArgs.hasInallocaArg());
5168     IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
5169   }
5170 
5171   // 2. Prepare the function pointer.
5172 
5173   // If the callee is a bitcast of a non-variadic function to have a
5174   // variadic function pointer type, check to see if we can remove the
5175   // bitcast.  This comes up with unprototyped functions.
5176   //
5177   // This makes the IR nicer, but more importantly it ensures that we
5178   // can inline the function at -O0 if it is marked always_inline.
5179   auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT,
5180                                    llvm::Value *Ptr) -> llvm::Function * {
5181     if (!CalleeFT->isVarArg())
5182       return nullptr;
5183 
5184     // Get underlying value if it's a bitcast
5185     if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) {
5186       if (CE->getOpcode() == llvm::Instruction::BitCast)
5187         Ptr = CE->getOperand(0);
5188     }
5189 
5190     llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr);
5191     if (!OrigFn)
5192       return nullptr;
5193 
5194     llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
5195 
5196     // If the original type is variadic, or if any of the component types
5197     // disagree, we cannot remove the cast.
5198     if (OrigFT->isVarArg() ||
5199         OrigFT->getNumParams() != CalleeFT->getNumParams() ||
5200         OrigFT->getReturnType() != CalleeFT->getReturnType())
5201       return nullptr;
5202 
5203     for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
5204       if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
5205         return nullptr;
5206 
5207     return OrigFn;
5208   };
5209 
5210   if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) {
5211     CalleePtr = OrigFn;
5212     IRFuncTy = OrigFn->getFunctionType();
5213   }
5214 
5215   // 3. Perform the actual call.
5216 
5217   // Deactivate any cleanups that we're supposed to do immediately before
5218   // the call.
5219   if (!CallArgs.getCleanupsToDeactivate().empty())
5220     deactivateArgCleanupsBeforeCall(*this, CallArgs);
5221 
5222   // Assert that the arguments we computed match up.  The IR verifier
5223   // will catch this, but this is a common enough source of problems
5224   // during IRGen changes that it's way better for debugging to catch
5225   // it ourselves here.
5226 #ifndef NDEBUG
5227   assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
5228   for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
5229     // Inalloca argument can have different type.
5230     if (IRFunctionArgs.hasInallocaArg() &&
5231         i == IRFunctionArgs.getInallocaArgNo())
5232       continue;
5233     if (i < IRFuncTy->getNumParams())
5234       assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
5235   }
5236 #endif
5237 
5238   // Update the largest vector width if any arguments have vector types.
5239   for (unsigned i = 0; i < IRCallArgs.size(); ++i)
5240     LargestVectorWidth = std::max(LargestVectorWidth,
5241                                   getMaxVectorWidth(IRCallArgs[i]->getType()));
5242 
5243   // Compute the calling convention and attributes.
5244   unsigned CallingConv;
5245   llvm::AttributeList Attrs;
5246   CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
5247                              Callee.getAbstractInfo(), Attrs, CallingConv,
5248                              /*AttrOnCallSite=*/true,
5249                              /*IsThunk=*/false);
5250 
5251   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
5252     if (FD->hasAttr<StrictFPAttr>())
5253       // All calls within a strictfp function are marked strictfp
5254       Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::StrictFP);
5255 
5256   // Add call-site nomerge attribute if exists.
5257   if (InNoMergeAttributedStmt)
5258     Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoMerge);
5259 
5260   // Add call-site noinline attribute if exists.
5261   if (InNoInlineAttributedStmt)
5262     Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoInline);
5263 
5264   // Add call-site always_inline attribute if exists.
5265   if (InAlwaysInlineAttributedStmt)
5266     Attrs =
5267         Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::AlwaysInline);
5268 
5269   // Apply some call-site-specific attributes.
5270   // TODO: work this into building the attribute set.
5271 
5272   // Apply always_inline to all calls within flatten functions.
5273   // FIXME: should this really take priority over __try, below?
5274   if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
5275       !InNoInlineAttributedStmt &&
5276       !(TargetDecl && TargetDecl->hasAttr<NoInlineAttr>())) {
5277     Attrs =
5278         Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::AlwaysInline);
5279   }
5280 
5281   // Disable inlining inside SEH __try blocks.
5282   if (isSEHTryScope()) {
5283     Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoInline);
5284   }
5285 
5286   // Decide whether to use a call or an invoke.
5287   bool CannotThrow;
5288   if (currentFunctionUsesSEHTry()) {
5289     // SEH cares about asynchronous exceptions, so everything can "throw."
5290     CannotThrow = false;
5291   } else if (isCleanupPadScope() &&
5292              EHPersonality::get(*this).isMSVCXXPersonality()) {
5293     // The MSVC++ personality will implicitly terminate the program if an
5294     // exception is thrown during a cleanup outside of a try/catch.
5295     // We don't need to model anything in IR to get this behavior.
5296     CannotThrow = true;
5297   } else {
5298     // Otherwise, nounwind call sites will never throw.
5299     CannotThrow = Attrs.hasFnAttr(llvm::Attribute::NoUnwind);
5300 
5301     if (auto *FPtr = dyn_cast<llvm::Function>(CalleePtr))
5302       if (FPtr->hasFnAttribute(llvm::Attribute::NoUnwind))
5303         CannotThrow = true;
5304   }
5305 
5306   // If we made a temporary, be sure to clean up after ourselves. Note that we
5307   // can't depend on being inside of an ExprWithCleanups, so we need to manually
5308   // pop this cleanup later on. Being eager about this is OK, since this
5309   // temporary is 'invisible' outside of the callee.
5310   if (UnusedReturnSizePtr)
5311     pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca,
5312                                          UnusedReturnSizePtr);
5313 
5314   llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
5315 
5316   SmallVector<llvm::OperandBundleDef, 1> BundleList =
5317       getBundlesForFunclet(CalleePtr);
5318 
5319   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
5320     if (FD->hasAttr<StrictFPAttr>())
5321       // All calls within a strictfp function are marked strictfp
5322       Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::StrictFP);
5323 
5324   AssumeAlignedAttrEmitter AssumeAlignedAttrEmitter(*this, TargetDecl);
5325   Attrs = AssumeAlignedAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
5326 
5327   AllocAlignAttrEmitter AllocAlignAttrEmitter(*this, TargetDecl, CallArgs);
5328   Attrs = AllocAlignAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
5329 
5330   // Emit the actual call/invoke instruction.
5331   llvm::CallBase *CI;
5332   if (!InvokeDest) {
5333     CI = Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList);
5334   } else {
5335     llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
5336     CI = Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs,
5337                               BundleList);
5338     EmitBlock(Cont);
5339   }
5340   if (callOrInvoke)
5341     *callOrInvoke = CI;
5342 
5343   // If this is within a function that has the guard(nocf) attribute and is an
5344   // indirect call, add the "guard_nocf" attribute to this call to indicate that
5345   // Control Flow Guard checks should not be added, even if the call is inlined.
5346   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
5347     if (const auto *A = FD->getAttr<CFGuardAttr>()) {
5348       if (A->getGuard() == CFGuardAttr::GuardArg::nocf && !CI->getCalledFunction())
5349         Attrs = Attrs.addFnAttribute(getLLVMContext(), "guard_nocf");
5350     }
5351   }
5352 
5353   // Apply the attributes and calling convention.
5354   CI->setAttributes(Attrs);
5355   CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
5356 
5357   // Apply various metadata.
5358 
5359   if (!CI->getType()->isVoidTy())
5360     CI->setName("call");
5361 
5362   // Update largest vector width from the return type.
5363   LargestVectorWidth =
5364       std::max(LargestVectorWidth, getMaxVectorWidth(CI->getType()));
5365 
5366   // Insert instrumentation or attach profile metadata at indirect call sites.
5367   // For more details, see the comment before the definition of
5368   // IPVK_IndirectCallTarget in InstrProfData.inc.
5369   if (!CI->getCalledFunction())
5370     PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
5371                      CI, CalleePtr);
5372 
5373   // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
5374   // optimizer it can aggressively ignore unwind edges.
5375   if (CGM.getLangOpts().ObjCAutoRefCount)
5376     AddObjCARCExceptionMetadata(CI);
5377 
5378   // Set tail call kind if necessary.
5379   if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
5380     if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
5381       Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
5382     else if (IsMustTail)
5383       Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
5384   }
5385 
5386   // Add metadata for calls to MSAllocator functions
5387   if (getDebugInfo() && TargetDecl &&
5388       TargetDecl->hasAttr<MSAllocatorAttr>())
5389     getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy->getPointeeType(), Loc);
5390 
5391   // Add metadata if calling an __attribute__((error(""))) or warning fn.
5392   if (TargetDecl && TargetDecl->hasAttr<ErrorAttr>()) {
5393     llvm::ConstantInt *Line =
5394         llvm::ConstantInt::get(Int32Ty, Loc.getRawEncoding());
5395     llvm::ConstantAsMetadata *MD = llvm::ConstantAsMetadata::get(Line);
5396     llvm::MDTuple *MDT = llvm::MDNode::get(getLLVMContext(), {MD});
5397     CI->setMetadata("srcloc", MDT);
5398   }
5399 
5400   // 4. Finish the call.
5401 
5402   // If the call doesn't return, finish the basic block and clear the
5403   // insertion point; this allows the rest of IRGen to discard
5404   // unreachable code.
5405   if (CI->doesNotReturn()) {
5406     if (UnusedReturnSizePtr)
5407       PopCleanupBlock();
5408 
5409     // Strip away the noreturn attribute to better diagnose unreachable UB.
5410     if (SanOpts.has(SanitizerKind::Unreachable)) {
5411       // Also remove from function since CallBase::hasFnAttr additionally checks
5412       // attributes of the called function.
5413       if (auto *F = CI->getCalledFunction())
5414         F->removeFnAttr(llvm::Attribute::NoReturn);
5415       CI->removeFnAttr(llvm::Attribute::NoReturn);
5416 
5417       // Avoid incompatibility with ASan which relies on the `noreturn`
5418       // attribute to insert handler calls.
5419       if (SanOpts.hasOneOf(SanitizerKind::Address |
5420                            SanitizerKind::KernelAddress)) {
5421         SanitizerScope SanScope(this);
5422         llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder);
5423         Builder.SetInsertPoint(CI);
5424         auto *FnType = llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
5425         llvm::FunctionCallee Fn =
5426             CGM.CreateRuntimeFunction(FnType, "__asan_handle_no_return");
5427         EmitNounwindRuntimeCall(Fn);
5428       }
5429     }
5430 
5431     EmitUnreachable(Loc);
5432     Builder.ClearInsertionPoint();
5433 
5434     // FIXME: For now, emit a dummy basic block because expr emitters in
5435     // generally are not ready to handle emitting expressions at unreachable
5436     // points.
5437     EnsureInsertPoint();
5438 
5439     // Return a reasonable RValue.
5440     return GetUndefRValue(RetTy);
5441   }
5442 
5443   // If this is a musttail call, return immediately. We do not branch to the
5444   // epilogue in this case.
5445   if (IsMustTail) {
5446     for (auto it = EHStack.find(CurrentCleanupScopeDepth); it != EHStack.end();
5447          ++it) {
5448       EHCleanupScope *Cleanup = dyn_cast<EHCleanupScope>(&*it);
5449       if (!(Cleanup && Cleanup->getCleanup()->isRedundantBeforeReturn()))
5450         CGM.ErrorUnsupported(MustTailCall, "tail call skipping over cleanups");
5451     }
5452     if (CI->getType()->isVoidTy())
5453       Builder.CreateRetVoid();
5454     else
5455       Builder.CreateRet(CI);
5456     Builder.ClearInsertionPoint();
5457     EnsureInsertPoint();
5458     return GetUndefRValue(RetTy);
5459   }
5460 
5461   // Perform the swifterror writeback.
5462   if (swiftErrorTemp.isValid()) {
5463     llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
5464     Builder.CreateStore(errorResult, swiftErrorArg);
5465   }
5466 
5467   // Emit any call-associated writebacks immediately.  Arguably this
5468   // should happen after any return-value munging.
5469   if (CallArgs.hasWritebacks())
5470     emitWritebacks(*this, CallArgs);
5471 
5472   // The stack cleanup for inalloca arguments has to run out of the normal
5473   // lexical order, so deactivate it and run it manually here.
5474   CallArgs.freeArgumentMemory(*this);
5475 
5476   // Extract the return value.
5477   RValue Ret = [&] {
5478     switch (RetAI.getKind()) {
5479     case ABIArgInfo::CoerceAndExpand: {
5480       auto coercionType = RetAI.getCoerceAndExpandType();
5481 
5482       Address addr = SRetPtr;
5483       addr = Builder.CreateElementBitCast(addr, coercionType);
5484 
5485       assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
5486       bool requiresExtract = isa<llvm::StructType>(CI->getType());
5487 
5488       unsigned unpaddedIndex = 0;
5489       for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
5490         llvm::Type *eltType = coercionType->getElementType(i);
5491         if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
5492         Address eltAddr = Builder.CreateStructGEP(addr, i);
5493         llvm::Value *elt = CI;
5494         if (requiresExtract)
5495           elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
5496         else
5497           assert(unpaddedIndex == 0);
5498         Builder.CreateStore(elt, eltAddr);
5499       }
5500       // FALLTHROUGH
5501       LLVM_FALLTHROUGH;
5502     }
5503 
5504     case ABIArgInfo::InAlloca:
5505     case ABIArgInfo::Indirect: {
5506       RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
5507       if (UnusedReturnSizePtr)
5508         PopCleanupBlock();
5509       return ret;
5510     }
5511 
5512     case ABIArgInfo::Ignore:
5513       // If we are ignoring an argument that had a result, make sure to
5514       // construct the appropriate return value for our caller.
5515       return GetUndefRValue(RetTy);
5516 
5517     case ABIArgInfo::Extend:
5518     case ABIArgInfo::Direct: {
5519       llvm::Type *RetIRTy = ConvertType(RetTy);
5520       if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
5521         switch (getEvaluationKind(RetTy)) {
5522         case TEK_Complex: {
5523           llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
5524           llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
5525           return RValue::getComplex(std::make_pair(Real, Imag));
5526         }
5527         case TEK_Aggregate: {
5528           Address DestPtr = ReturnValue.getValue();
5529           bool DestIsVolatile = ReturnValue.isVolatile();
5530 
5531           if (!DestPtr.isValid()) {
5532             DestPtr = CreateMemTemp(RetTy, "agg.tmp");
5533             DestIsVolatile = false;
5534           }
5535           EmitAggregateStore(CI, DestPtr, DestIsVolatile);
5536           return RValue::getAggregate(DestPtr);
5537         }
5538         case TEK_Scalar: {
5539           // If the argument doesn't match, perform a bitcast to coerce it.  This
5540           // can happen due to trivial type mismatches.
5541           llvm::Value *V = CI;
5542           if (V->getType() != RetIRTy)
5543             V = Builder.CreateBitCast(V, RetIRTy);
5544           return RValue::get(V);
5545         }
5546         }
5547         llvm_unreachable("bad evaluation kind");
5548       }
5549 
5550       Address DestPtr = ReturnValue.getValue();
5551       bool DestIsVolatile = ReturnValue.isVolatile();
5552 
5553       if (!DestPtr.isValid()) {
5554         DestPtr = CreateMemTemp(RetTy, "coerce");
5555         DestIsVolatile = false;
5556       }
5557 
5558       // If the value is offset in memory, apply the offset now.
5559       Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
5560       CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
5561 
5562       return convertTempToRValue(DestPtr, RetTy, SourceLocation());
5563     }
5564 
5565     case ABIArgInfo::Expand:
5566     case ABIArgInfo::IndirectAliased:
5567       llvm_unreachable("Invalid ABI kind for return argument");
5568     }
5569 
5570     llvm_unreachable("Unhandled ABIArgInfo::Kind");
5571   } ();
5572 
5573   // Emit the assume_aligned check on the return value.
5574   if (Ret.isScalar() && TargetDecl) {
5575     AssumeAlignedAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
5576     AllocAlignAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
5577   }
5578 
5579   // Explicitly call CallLifetimeEnd::Emit just to re-use the code even though
5580   // we can't use the full cleanup mechanism.
5581   for (CallLifetimeEnd &LifetimeEnd : CallLifetimeEndAfterCall)
5582     LifetimeEnd.Emit(*this, /*Flags=*/{});
5583 
5584   if (!ReturnValue.isExternallyDestructed() &&
5585       RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct)
5586     pushDestroy(QualType::DK_nontrivial_c_struct, Ret.getAggregateAddress(),
5587                 RetTy);
5588 
5589   return Ret;
5590 }
5591 
5592 CGCallee CGCallee::prepareConcreteCallee(CodeGenFunction &CGF) const {
5593   if (isVirtual()) {
5594     const CallExpr *CE = getVirtualCallExpr();
5595     return CGF.CGM.getCXXABI().getVirtualFunctionPointer(
5596         CGF, getVirtualMethodDecl(), getThisAddress(), getVirtualFunctionType(),
5597         CE ? CE->getBeginLoc() : SourceLocation());
5598   }
5599 
5600   return *this;
5601 }
5602 
5603 /* VarArg handling */
5604 
5605 Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
5606   VAListAddr = VE->isMicrosoftABI()
5607                  ? EmitMSVAListRef(VE->getSubExpr())
5608                  : EmitVAListRef(VE->getSubExpr());
5609   QualType Ty = VE->getType();
5610   if (VE->isMicrosoftABI())
5611     return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
5612   return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
5613 }
5614