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