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