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