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