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