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