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