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