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