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