Bug Summary

File:tools/clang/lib/CodeGen/CGCall.cpp
Warning:line 2295, column 33
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CGCall.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn337490/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-7~svn337490/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn337490/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn337490/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn337490/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/lib/gcc/x86_64-linux-gnu/8/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn337490/build-llvm/tools/clang/lib/CodeGen -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-07-20-043646-20380-1 -x c++ /build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp -faddrsig
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 "CGBlocks.h"
18#include "CGCXXABI.h"
19#include "CGCleanup.h"
20#include "CodeGenFunction.h"
21#include "CodeGenModule.h"
22#include "TargetInfo.h"
23#include "clang/AST/Decl.h"
24#include "clang/AST/DeclCXX.h"
25#include "clang/AST/DeclObjC.h"
26#include "clang/Basic/TargetBuiltins.h"
27#include "clang/Basic/TargetInfo.h"
28#include "clang/CodeGen/CGFunctionInfo.h"
29#include "clang/CodeGen/SwiftCallingConv.h"
30#include "clang/Frontend/CodeGenOptions.h"
31#include "llvm/ADT/StringExtras.h"
32#include "llvm/Transforms/Utils/Local.h"
33#include "llvm/Analysis/ValueTracking.h"
34#include "llvm/IR/Attributes.h"
35#include "llvm/IR/CallSite.h"
36#include "llvm/IR/CallingConv.h"
37#include "llvm/IR/DataLayout.h"
38#include "llvm/IR/InlineAsm.h"
39#include "llvm/IR/IntrinsicInst.h"
40#include "llvm/IR/Intrinsics.h"
41using namespace clang;
42using namespace CodeGen;
43
44/***/
45
46unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC) {
47 switch (CC) {
48 default: return llvm::CallingConv::C;
49 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
50 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
51 case CC_X86RegCall: return llvm::CallingConv::X86_RegCall;
52 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
53 case CC_Win64: return llvm::CallingConv::Win64;
54 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
55 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
56 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
57 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
58 // TODO: Add support for __pascal to LLVM.
59 case CC_X86Pascal: return llvm::CallingConv::C;
60 // TODO: Add support for __vectorcall to LLVM.
61 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
62 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
63 case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv();
64 case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
65 case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
66 case CC_Swift: return llvm::CallingConv::Swift;
67 }
68}
69
70/// Derives the 'this' type for codegen purposes, i.e. ignoring method
71/// qualification.
72/// FIXME: address space qualification?
73static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
74 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
75 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
76}
77
78/// Returns the canonical formal type of the given C++ method.
79static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
80 return MD->getType()->getCanonicalTypeUnqualified()
81 .getAs<FunctionProtoType>();
82}
83
84/// Returns the "extra-canonicalized" return type, which discards
85/// qualifiers on the return type. Codegen doesn't care about them,
86/// and it makes ABI code a little easier to be able to assume that
87/// all parameter and return types are top-level unqualified.
88static CanQualType GetReturnType(QualType RetTy) {
89 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
90}
91
92/// Arrange the argument and result information for a value of the given
93/// unprototyped freestanding function type.
94const CGFunctionInfo &
95CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
96 // When translating an unprototyped function type, always use a
97 // variadic type.
98 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
99 /*instanceMethod=*/false,
100 /*chainCall=*/false, None,
101 FTNP->getExtInfo(), {}, RequiredArgs(0));
102}
103
104static void addExtParameterInfosForCall(
105 llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
106 const FunctionProtoType *proto,
107 unsigned prefixArgs,
108 unsigned totalArgs) {
109 assert(proto->hasExtParameterInfos())(static_cast <bool> (proto->hasExtParameterInfos()) ?
void (0) : __assert_fail ("proto->hasExtParameterInfos()"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 109, __extension__ __PRETTY_FUNCTION__))
;
110 assert(paramInfos.size() <= prefixArgs)(static_cast <bool> (paramInfos.size() <= prefixArgs
) ? void (0) : __assert_fail ("paramInfos.size() <= prefixArgs"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 110, __extension__ __PRETTY_FUNCTION__))
;
111 assert(proto->getNumParams() + prefixArgs <= totalArgs)(static_cast <bool> (proto->getNumParams() + prefixArgs
<= totalArgs) ? void (0) : __assert_fail ("proto->getNumParams() + prefixArgs <= totalArgs"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 111, __extension__ __PRETTY_FUNCTION__))
;
112
113 paramInfos.reserve(totalArgs);
114
115 // Add default infos for any prefix args that don't already have infos.
116 paramInfos.resize(prefixArgs);
117
118 // Add infos for the prototype.
119 for (const auto &ParamInfo : proto->getExtParameterInfos()) {
120 paramInfos.push_back(ParamInfo);
121 // pass_object_size params have no parameter info.
122 if (ParamInfo.hasPassObjectSize())
123 paramInfos.emplace_back();
124 }
125
126 assert(paramInfos.size() <= totalArgs &&(static_cast <bool> (paramInfos.size() <= totalArgs &&
"Did we forget to insert pass_object_size args?") ? void (0)
: __assert_fail ("paramInfos.size() <= totalArgs && \"Did we forget to insert pass_object_size args?\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 127, __extension__ __PRETTY_FUNCTION__))
127 "Did we forget to insert pass_object_size args?")(static_cast <bool> (paramInfos.size() <= totalArgs &&
"Did we forget to insert pass_object_size args?") ? void (0)
: __assert_fail ("paramInfos.size() <= totalArgs && \"Did we forget to insert pass_object_size args?\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 127, __extension__ __PRETTY_FUNCTION__))
;
128 // Add default infos for the variadic and/or suffix arguments.
129 paramInfos.resize(totalArgs);
130}
131
132/// Adds the formal parameters in FPT to the given prefix. If any parameter in
133/// FPT has pass_object_size attrs, then we'll add parameters for those, too.
134static void appendParameterTypes(const CodeGenTypes &CGT,
135 SmallVectorImpl<CanQualType> &prefix,
136 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
137 CanQual<FunctionProtoType> FPT) {
138 // Fast path: don't touch param info if we don't need to.
139 if (!FPT->hasExtParameterInfos()) {
140 assert(paramInfos.empty() &&(static_cast <bool> (paramInfos.empty() && "We have paramInfos, but the prototype doesn't?"
) ? void (0) : __assert_fail ("paramInfos.empty() && \"We have paramInfos, but the prototype doesn't?\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 141, __extension__ __PRETTY_FUNCTION__))
141 "We have paramInfos, but the prototype doesn't?")(static_cast <bool> (paramInfos.empty() && "We have paramInfos, but the prototype doesn't?"
) ? void (0) : __assert_fail ("paramInfos.empty() && \"We have paramInfos, but the prototype doesn't?\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 141, __extension__ __PRETTY_FUNCTION__))
;
142 prefix.append(FPT->param_type_begin(), FPT->param_type_end());
143 return;
144 }
145
146 unsigned PrefixSize = prefix.size();
147 // In the vast majority of cases, we'll have precisely FPT->getNumParams()
148 // parameters; the only thing that can change this is the presence of
149 // pass_object_size. So, we preallocate for the common case.
150 prefix.reserve(prefix.size() + FPT->getNumParams());
151
152 auto ExtInfos = FPT->getExtParameterInfos();
153 assert(ExtInfos.size() == FPT->getNumParams())(static_cast <bool> (ExtInfos.size() == FPT->getNumParams
()) ? void (0) : __assert_fail ("ExtInfos.size() == FPT->getNumParams()"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 153, __extension__ __PRETTY_FUNCTION__))
;
154 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
155 prefix.push_back(FPT->getParamType(I));
156 if (ExtInfos[I].hasPassObjectSize())
157 prefix.push_back(CGT.getContext().getSizeType());
158 }
159
160 addExtParameterInfosForCall(paramInfos, FPT.getTypePtr(), PrefixSize,
161 prefix.size());
162}
163
164/// Arrange the LLVM function layout for a value of the given function
165/// type, on top of any implicit parameters already stored.
166static const CGFunctionInfo &
167arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
168 SmallVectorImpl<CanQualType> &prefix,
169 CanQual<FunctionProtoType> FTP,
170 const FunctionDecl *FD) {
171 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
172 RequiredArgs Required =
173 RequiredArgs::forPrototypePlus(FTP, prefix.size(), FD);
174 // FIXME: Kill copy.
175 appendParameterTypes(CGT, prefix, paramInfos, FTP);
176 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
177
178 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
179 /*chainCall=*/false, prefix,
180 FTP->getExtInfo(), paramInfos,
181 Required);
182}
183
184/// Arrange the argument and result information for a value of the
185/// given freestanding function type.
186const CGFunctionInfo &
187CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP,
188 const FunctionDecl *FD) {
189 SmallVector<CanQualType, 16> argTypes;
190 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
191 FTP, FD);
192}
193
194static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
195 // Set the appropriate calling convention for the Function.
196 if (D->hasAttr<StdCallAttr>())
197 return CC_X86StdCall;
198
199 if (D->hasAttr<FastCallAttr>())
200 return CC_X86FastCall;
201
202 if (D->hasAttr<RegCallAttr>())
203 return CC_X86RegCall;
204
205 if (D->hasAttr<ThisCallAttr>())
206 return CC_X86ThisCall;
207
208 if (D->hasAttr<VectorCallAttr>())
209 return CC_X86VectorCall;
210
211 if (D->hasAttr<PascalAttr>())
212 return CC_X86Pascal;
213
214 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
215 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
216
217 if (D->hasAttr<IntelOclBiccAttr>())
218 return CC_IntelOclBicc;
219
220 if (D->hasAttr<MSABIAttr>())
221 return IsWindows ? CC_C : CC_Win64;
222
223 if (D->hasAttr<SysVABIAttr>())
224 return IsWindows ? CC_X86_64SysV : CC_C;
225
226 if (D->hasAttr<PreserveMostAttr>())
227 return CC_PreserveMost;
228
229 if (D->hasAttr<PreserveAllAttr>())
230 return CC_PreserveAll;
231
232 return CC_C;
233}
234
235/// Arrange the argument and result information for a call to an
236/// unknown C++ non-static member function of the given abstract type.
237/// (Zero value of RD means we don't have any meaningful "this" argument type,
238/// so fall back to a generic pointer type).
239/// The member function must be an ordinary function, i.e. not a
240/// constructor or destructor.
241const CGFunctionInfo &
242CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
243 const FunctionProtoType *FTP,
244 const CXXMethodDecl *MD) {
245 SmallVector<CanQualType, 16> argTypes;
246
247 // Add the 'this' pointer.
248 if (RD)
249 argTypes.push_back(GetThisType(Context, RD));
250 else
251 argTypes.push_back(Context.VoidPtrTy);
252
253 return ::arrangeLLVMFunctionInfo(
254 *this, true, argTypes,
255 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>(), MD);
256}
257
258/// Set calling convention for CUDA/HIP kernel.
259static void setCUDAKernelCallingConvention(CanQualType &FTy, CodeGenModule &CGM,
260 const FunctionDecl *FD) {
261 if (FD->hasAttr<CUDAGlobalAttr>()) {
262 const FunctionType *FT = FTy->getAs<FunctionType>();
263 CGM.getTargetCodeGenInfo().setCUDAKernelCallingConvention(FT);
264 FTy = FT->getCanonicalTypeUnqualified();
265 }
266}
267
268/// Arrange the argument and result information for a declaration or
269/// definition of the given C++ non-static member function. The
270/// member function must be an ordinary function, i.e. not a
271/// constructor or destructor.
272const CGFunctionInfo &
273CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
274 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!")(static_cast <bool> (!isa<CXXConstructorDecl>(MD)
&& "wrong method for constructors!") ? void (0) : __assert_fail
("!isa<CXXConstructorDecl>(MD) && \"wrong method for constructors!\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 274, __extension__ __PRETTY_FUNCTION__))
;
275 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!")(static_cast <bool> (!isa<CXXDestructorDecl>(MD) &&
"wrong method for destructors!") ? void (0) : __assert_fail (
"!isa<CXXDestructorDecl>(MD) && \"wrong method for destructors!\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 275, __extension__ __PRETTY_FUNCTION__))
;
276
277 CanQualType FT = GetFormalType(MD).getAs<Type>();
278 setCUDAKernelCallingConvention(FT, CGM, MD);
279 auto prototype = FT.getAs<FunctionProtoType>();
280
281 if (MD->isInstance()) {
282 // The abstract case is perfectly fine.
283 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
284 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
285 }
286
287 return arrangeFreeFunctionType(prototype, MD);
288}
289
290bool CodeGenTypes::inheritingCtorHasParams(
291 const InheritedConstructor &Inherited, CXXCtorType Type) {
292 // Parameters are unnecessary if we're constructing a base class subobject
293 // and the inherited constructor lives in a virtual base.
294 return Type == Ctor_Complete ||
295 !Inherited.getShadowDecl()->constructsVirtualBase() ||
296 !Target.getCXXABI().hasConstructorVariants();
297 }
298
299const CGFunctionInfo &
300CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
301 StructorType Type) {
302
303 SmallVector<CanQualType, 16> argTypes;
304 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
305 argTypes.push_back(GetThisType(Context, MD->getParent()));
306
307 bool PassParams = true;
308
309 GlobalDecl GD;
310 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
311 GD = GlobalDecl(CD, toCXXCtorType(Type));
312
313 // A base class inheriting constructor doesn't get forwarded arguments
314 // needed to construct a virtual base (or base class thereof).
315 if (auto Inherited = CD->getInheritedConstructor())
316 PassParams = inheritingCtorHasParams(Inherited, toCXXCtorType(Type));
317 } else {
318 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
319 GD = GlobalDecl(DD, toCXXDtorType(Type));
320 }
321
322 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
323
324 // Add the formal parameters.
325 if (PassParams)
326 appendParameterTypes(*this, argTypes, paramInfos, FTP);
327
328 CGCXXABI::AddedStructorArgs AddedArgs =
329 TheCXXABI.buildStructorSignature(MD, Type, argTypes);
330 if (!paramInfos.empty()) {
331 // Note: prefix implies after the first param.
332 if (AddedArgs.Prefix)
333 paramInfos.insert(paramInfos.begin() + 1, AddedArgs.Prefix,
334 FunctionProtoType::ExtParameterInfo{});
335 if (AddedArgs.Suffix)
336 paramInfos.append(AddedArgs.Suffix,
337 FunctionProtoType::ExtParameterInfo{});
338 }
339
340 RequiredArgs required =
341 (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
342 : RequiredArgs::All);
343
344 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
345 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
346 ? argTypes.front()
347 : TheCXXABI.hasMostDerivedReturn(GD)
348 ? CGM.getContext().VoidPtrTy
349 : Context.VoidTy;
350 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
351 /*chainCall=*/false, argTypes, extInfo,
352 paramInfos, required);
353}
354
355static SmallVector<CanQualType, 16>
356getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
357 SmallVector<CanQualType, 16> argTypes;
358 for (auto &arg : args)
359 argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
360 return argTypes;
361}
362
363static SmallVector<CanQualType, 16>
364getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
365 SmallVector<CanQualType, 16> argTypes;
366 for (auto &arg : args)
367 argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
368 return argTypes;
369}
370
371static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
372getExtParameterInfosForCall(const FunctionProtoType *proto,
373 unsigned prefixArgs, unsigned totalArgs) {
374 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
375 if (proto->hasExtParameterInfos()) {
376 addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
377 }
378 return result;
379}
380
381/// Arrange a call to a C++ method, passing the given arguments.
382///
383/// ExtraPrefixArgs is the number of ABI-specific args passed after the `this`
384/// parameter.
385/// ExtraSuffixArgs is the number of ABI-specific args passed at the end of
386/// args.
387/// PassProtoArgs indicates whether `args` has args for the parameters in the
388/// given CXXConstructorDecl.
389const CGFunctionInfo &
390CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
391 const CXXConstructorDecl *D,
392 CXXCtorType CtorKind,
393 unsigned ExtraPrefixArgs,
394 unsigned ExtraSuffixArgs,
395 bool PassProtoArgs) {
396 // FIXME: Kill copy.
397 SmallVector<CanQualType, 16> ArgTypes;
398 for (const auto &Arg : args)
399 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
400
401 // +1 for implicit this, which should always be args[0].
402 unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs;
403
404 CanQual<FunctionProtoType> FPT = GetFormalType(D);
405 RequiredArgs Required =
406 RequiredArgs::forPrototypePlus(FPT, TotalPrefixArgs + ExtraSuffixArgs, D);
407 GlobalDecl GD(D, CtorKind);
408 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
409 ? ArgTypes.front()
410 : TheCXXABI.hasMostDerivedReturn(GD)
411 ? CGM.getContext().VoidPtrTy
412 : Context.VoidTy;
413
414 FunctionType::ExtInfo Info = FPT->getExtInfo();
415 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> ParamInfos;
416 // If the prototype args are elided, we should only have ABI-specific args,
417 // which never have param info.
418 if (PassProtoArgs && FPT->hasExtParameterInfos()) {
419 // ABI-specific suffix arguments are treated the same as variadic arguments.
420 addExtParameterInfosForCall(ParamInfos, FPT.getTypePtr(), TotalPrefixArgs,
421 ArgTypes.size());
422 }
423 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
424 /*chainCall=*/false, ArgTypes, Info,
425 ParamInfos, Required);
426}
427
428/// Arrange the argument and result information for the declaration or
429/// definition of the given function.
430const CGFunctionInfo &
431CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
432 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
433 if (MD->isInstance())
434 return arrangeCXXMethodDeclaration(MD);
435
436 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
437
438 assert(isa<FunctionType>(FTy))(static_cast <bool> (isa<FunctionType>(FTy)) ? void
(0) : __assert_fail ("isa<FunctionType>(FTy)", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 438, __extension__ __PRETTY_FUNCTION__))
;
439 setCUDAKernelCallingConvention(FTy, CGM, FD);
440
441 // When declaring a function without a prototype, always use a
442 // non-variadic type.
443 if (CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>()) {
444 return arrangeLLVMFunctionInfo(
445 noProto->getReturnType(), /*instanceMethod=*/false,
446 /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All);
447 }
448
449 return arrangeFreeFunctionType(FTy.castAs<FunctionProtoType>(), FD);
450}
451
452/// Arrange the argument and result information for the declaration or
453/// definition of an Objective-C method.
454const CGFunctionInfo &
455CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
456 // It happens that this is the same as a call with no optional
457 // arguments, except also using the formal 'self' type.
458 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
459}
460
461/// Arrange the argument and result information for the function type
462/// through which to perform a send to the given Objective-C method,
463/// using the given receiver type. The receiver type is not always
464/// the 'self' type of the method or even an Objective-C pointer type.
465/// This is *not* the right method for actually performing such a
466/// message send, due to the possibility of optional arguments.
467const CGFunctionInfo &
468CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
469 QualType receiverType) {
470 SmallVector<CanQualType, 16> argTys;
471 SmallVector<FunctionProtoType::ExtParameterInfo, 4> extParamInfos(2);
472 argTys.push_back(Context.getCanonicalParamType(receiverType));
473 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
474 // FIXME: Kill copy?
475 for (const auto *I : MD->parameters()) {
476 argTys.push_back(Context.getCanonicalParamType(I->getType()));
477 auto extParamInfo = FunctionProtoType::ExtParameterInfo().withIsNoEscape(
478 I->hasAttr<NoEscapeAttr>());
479 extParamInfos.push_back(extParamInfo);
480 }
481
482 FunctionType::ExtInfo einfo;
483 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
484 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
485
486 if (getContext().getLangOpts().ObjCAutoRefCount &&
487 MD->hasAttr<NSReturnsRetainedAttr>())
488 einfo = einfo.withProducesResult(true);
489
490 RequiredArgs required =
491 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
492
493 return arrangeLLVMFunctionInfo(
494 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
495 /*chainCall=*/false, argTys, einfo, extParamInfos, required);
496}
497
498const CGFunctionInfo &
499CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
500 const CallArgList &args) {
501 auto argTypes = getArgTypesForCall(Context, args);
502 FunctionType::ExtInfo einfo;
503
504 return arrangeLLVMFunctionInfo(
505 GetReturnType(returnType), /*instanceMethod=*/false,
506 /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
507}
508
509const CGFunctionInfo &
510CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
511 // FIXME: Do we need to handle ObjCMethodDecl?
512 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
513
514 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
515 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
516
517 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
518 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
519
520 return arrangeFunctionDeclaration(FD);
521}
522
523/// Arrange a thunk that takes 'this' as the first parameter followed by
524/// varargs. Return a void pointer, regardless of the actual return type.
525/// The body of the thunk will end in a musttail call to a function of the
526/// correct type, and the caller will bitcast the function to the correct
527/// prototype.
528const CGFunctionInfo &
529CodeGenTypes::arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD) {
530 assert(MD->isVirtual() && "only methods have thunks")(static_cast <bool> (MD->isVirtual() && "only methods have thunks"
) ? void (0) : __assert_fail ("MD->isVirtual() && \"only methods have thunks\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 530, __extension__ __PRETTY_FUNCTION__))
;
531 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
532 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
533 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
534 /*chainCall=*/false, ArgTys,
535 FTP->getExtInfo(), {}, RequiredArgs(1));
536}
537
538const CGFunctionInfo &
539CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
540 CXXCtorType CT) {
541 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure)(static_cast <bool> (CT == Ctor_CopyingClosure || CT ==
Ctor_DefaultClosure) ? void (0) : __assert_fail ("CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 541, __extension__ __PRETTY_FUNCTION__))
;
542
543 CanQual<FunctionProtoType> FTP = GetFormalType(CD);
544 SmallVector<CanQualType, 2> ArgTys;
545 const CXXRecordDecl *RD = CD->getParent();
546 ArgTys.push_back(GetThisType(Context, RD));
547 if (CT == Ctor_CopyingClosure)
548 ArgTys.push_back(*FTP->param_type_begin());
549 if (RD->getNumVBases() > 0)
550 ArgTys.push_back(Context.IntTy);
551 CallingConv CC = Context.getDefaultCallingConvention(
552 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
553 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
554 /*chainCall=*/false, ArgTys,
555 FunctionType::ExtInfo(CC), {},
556 RequiredArgs::All);
557}
558
559/// Arrange a call as unto a free function, except possibly with an
560/// additional number of formal parameters considered required.
561static const CGFunctionInfo &
562arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
563 CodeGenModule &CGM,
564 const CallArgList &args,
565 const FunctionType *fnType,
566 unsigned numExtraRequiredArgs,
567 bool chainCall) {
568 assert(args.size() >= numExtraRequiredArgs)(static_cast <bool> (args.size() >= numExtraRequiredArgs
) ? void (0) : __assert_fail ("args.size() >= numExtraRequiredArgs"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 568, __extension__ __PRETTY_FUNCTION__))
;
569
570 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
571
572 // In most cases, there are no optional arguments.
573 RequiredArgs required = RequiredArgs::All;
574
575 // If we have a variadic prototype, the required arguments are the
576 // extra prefix plus the arguments in the prototype.
577 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
578 if (proto->isVariadic())
579 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
580
581 if (proto->hasExtParameterInfos())
582 addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
583 args.size());
584
585 // If we don't have a prototype at all, but we're supposed to
586 // explicitly use the variadic convention for unprototyped calls,
587 // treat all of the arguments as required but preserve the nominal
588 // possibility of variadics.
589 } else if (CGM.getTargetCodeGenInfo()
590 .isNoProtoCallVariadic(args,
591 cast<FunctionNoProtoType>(fnType))) {
592 required = RequiredArgs(args.size());
593 }
594
595 // FIXME: Kill copy.
596 SmallVector<CanQualType, 16> argTypes;
597 for (const auto &arg : args)
598 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
599 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
600 /*instanceMethod=*/false, chainCall,
601 argTypes, fnType->getExtInfo(), paramInfos,
602 required);
603}
604
605/// Figure out the rules for calling a function with the given formal
606/// type using the given arguments. The arguments are necessary
607/// because the function might be unprototyped, in which case it's
608/// target-dependent in crazy ways.
609const CGFunctionInfo &
610CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
611 const FunctionType *fnType,
612 bool chainCall) {
613 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
614 chainCall ? 1 : 0, chainCall);
615}
616
617/// A block function is essentially a free function with an
618/// extra implicit argument.
619const CGFunctionInfo &
620CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
621 const FunctionType *fnType) {
622 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
623 /*chainCall=*/false);
624}
625
626const CGFunctionInfo &
627CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
628 const FunctionArgList &params) {
629 auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
630 auto argTypes = getArgTypesForDeclaration(Context, params);
631
632 return arrangeLLVMFunctionInfo(
633 GetReturnType(proto->getReturnType()),
634 /*instanceMethod*/ false, /*chainCall*/ false, argTypes,
635 proto->getExtInfo(), paramInfos,
636 RequiredArgs::forPrototypePlus(proto, 1, nullptr));
637}
638
639const CGFunctionInfo &
640CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
641 const CallArgList &args) {
642 // FIXME: Kill copy.
643 SmallVector<CanQualType, 16> argTypes;
644 for (const auto &Arg : args)
645 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
646 return arrangeLLVMFunctionInfo(
647 GetReturnType(resultType), /*instanceMethod=*/false,
648 /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
649 /*paramInfos=*/ {}, RequiredArgs::All);
650}
651
652const CGFunctionInfo &
653CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
654 const FunctionArgList &args) {
655 auto argTypes = getArgTypesForDeclaration(Context, args);
656
657 return arrangeLLVMFunctionInfo(
658 GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
659 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
660}
661
662const CGFunctionInfo &
663CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
664 ArrayRef<CanQualType> argTypes) {
665 return arrangeLLVMFunctionInfo(
666 resultType, /*instanceMethod=*/false, /*chainCall=*/false,
667 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
668}
669
670/// Arrange a call to a C++ method, passing the given arguments.
671///
672/// numPrefixArgs is the number of ABI-specific prefix arguments we have. It
673/// does not count `this`.
674const CGFunctionInfo &
675CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
676 const FunctionProtoType *proto,
677 RequiredArgs required,
678 unsigned numPrefixArgs) {
679 assert(numPrefixArgs + 1 <= args.size() &&(static_cast <bool> (numPrefixArgs + 1 <= args.size(
) && "Emitting a call with less args than the required prefix?"
) ? void (0) : __assert_fail ("numPrefixArgs + 1 <= args.size() && \"Emitting a call with less args than the required prefix?\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 680, __extension__ __PRETTY_FUNCTION__))
680 "Emitting a call with less args than the required prefix?")(static_cast <bool> (numPrefixArgs + 1 <= args.size(
) && "Emitting a call with less args than the required prefix?"
) ? void (0) : __assert_fail ("numPrefixArgs + 1 <= args.size() && \"Emitting a call with less args than the required prefix?\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 680, __extension__ __PRETTY_FUNCTION__))
;
681 // Add one to account for `this`. It's a bit awkward here, but we don't count
682 // `this` in similar places elsewhere.
683 auto paramInfos =
684 getExtParameterInfosForCall(proto, numPrefixArgs + 1, args.size());
685
686 // FIXME: Kill copy.
687 auto argTypes = getArgTypesForCall(Context, args);
688
689 FunctionType::ExtInfo info = proto->getExtInfo();
690 return arrangeLLVMFunctionInfo(
691 GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
692 /*chainCall=*/false, argTypes, info, paramInfos, required);
693}
694
695const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
696 return arrangeLLVMFunctionInfo(
697 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
698 None, FunctionType::ExtInfo(), {}, RequiredArgs::All);
699}
700
701const CGFunctionInfo &
702CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
703 const CallArgList &args) {
704 assert(signature.arg_size() <= args.size())(static_cast <bool> (signature.arg_size() <= args.size
()) ? void (0) : __assert_fail ("signature.arg_size() <= args.size()"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 704, __extension__ __PRETTY_FUNCTION__))
;
705 if (signature.arg_size() == args.size())
706 return signature;
707
708 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
709 auto sigParamInfos = signature.getExtParameterInfos();
710 if (!sigParamInfos.empty()) {
711 paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
712 paramInfos.resize(args.size());
713 }
714
715 auto argTypes = getArgTypesForCall(Context, args);
716
717 assert(signature.getRequiredArgs().allowsOptionalArgs())(static_cast <bool> (signature.getRequiredArgs().allowsOptionalArgs
()) ? void (0) : __assert_fail ("signature.getRequiredArgs().allowsOptionalArgs()"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 717, __extension__ __PRETTY_FUNCTION__))
;
718 return arrangeLLVMFunctionInfo(signature.getReturnType(),
719 signature.isInstanceMethod(),
720 signature.isChainCall(),
721 argTypes,
722 signature.getExtInfo(),
723 paramInfos,
724 signature.getRequiredArgs());
725}
726
727namespace clang {
728namespace CodeGen {
729void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI);
730}
731}
732
733/// Arrange the argument and result information for an abstract value
734/// of a given function type. This is the method which all of the
735/// above functions ultimately defer to.
736const CGFunctionInfo &
737CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
738 bool instanceMethod,
739 bool chainCall,
740 ArrayRef<CanQualType> argTypes,
741 FunctionType::ExtInfo info,
742 ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
743 RequiredArgs required) {
744 assert(std::all_of(argTypes.begin(), argTypes.end(),(static_cast <bool> (std::all_of(argTypes.begin(), argTypes
.end(), [](CanQualType T) { return T.isCanonicalAsParam(); })
) ? void (0) : __assert_fail ("std::all_of(argTypes.begin(), argTypes.end(), [](CanQualType T) { return T.isCanonicalAsParam(); })"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 745, __extension__ __PRETTY_FUNCTION__))
745 [](CanQualType T) { return T.isCanonicalAsParam(); }))(static_cast <bool> (std::all_of(argTypes.begin(), argTypes
.end(), [](CanQualType T) { return T.isCanonicalAsParam(); })
) ? void (0) : __assert_fail ("std::all_of(argTypes.begin(), argTypes.end(), [](CanQualType T) { return T.isCanonicalAsParam(); })"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 745, __extension__ __PRETTY_FUNCTION__))
;
746
747 // Lookup or create unique function info.
748 llvm::FoldingSetNodeID ID;
749 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
750 required, resultType, argTypes);
751
752 void *insertPos = nullptr;
753 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
754 if (FI)
755 return *FI;
756
757 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
758
759 // Construct the function info. We co-allocate the ArgInfos.
760 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
761 paramInfos, resultType, argTypes, required);
762 FunctionInfos.InsertNode(FI, insertPos);
763
764 bool inserted = FunctionsBeingProcessed.insert(FI).second;
765 (void)inserted;
766 assert(inserted && "Recursively being processed?")(static_cast <bool> (inserted && "Recursively being processed?"
) ? void (0) : __assert_fail ("inserted && \"Recursively being processed?\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 766, __extension__ __PRETTY_FUNCTION__))
;
767
768 // Compute ABI information.
769 if (CC == llvm::CallingConv::SPIR_KERNEL) {
770 // Force target independent argument handling for the host visible
771 // kernel functions.
772 computeSPIRKernelABIInfo(CGM, *FI);
773 } else if (info.getCC() == CC_Swift) {
774 swiftcall::computeABIInfo(CGM, *FI);
775 } else {
776 getABIInfo().computeInfo(*FI);
777 }
778
779 // Loop over all of the computed argument and return value info. If any of
780 // them are direct or extend without a specified coerce type, specify the
781 // default now.
782 ABIArgInfo &retInfo = FI->getReturnInfo();
783 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
784 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
785
786 for (auto &I : FI->arguments())
787 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
788 I.info.setCoerceToType(ConvertType(I.type));
789
790 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
791 assert(erased && "Not in set?")(static_cast <bool> (erased && "Not in set?") ?
void (0) : __assert_fail ("erased && \"Not in set?\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 791, __extension__ __PRETTY_FUNCTION__))
;
792
793 return *FI;
794}
795
796CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
797 bool instanceMethod,
798 bool chainCall,
799 const FunctionType::ExtInfo &info,
800 ArrayRef<ExtParameterInfo> paramInfos,
801 CanQualType resultType,
802 ArrayRef<CanQualType> argTypes,
803 RequiredArgs required) {
804 assert(paramInfos.empty() || paramInfos.size() == argTypes.size())(static_cast <bool> (paramInfos.empty() || paramInfos.size
() == argTypes.size()) ? void (0) : __assert_fail ("paramInfos.empty() || paramInfos.size() == argTypes.size()"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 804, __extension__ __PRETTY_FUNCTION__))
;
805
806 void *buffer =
807 operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
808 argTypes.size() + 1, paramInfos.size()));
809
810 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
811 FI->CallingConvention = llvmCC;
812 FI->EffectiveCallingConvention = llvmCC;
813 FI->ASTCallingConvention = info.getCC();
814 FI->InstanceMethod = instanceMethod;
815 FI->ChainCall = chainCall;
816 FI->NoReturn = info.getNoReturn();
817 FI->ReturnsRetained = info.getProducesResult();
818 FI->NoCallerSavedRegs = info.getNoCallerSavedRegs();
819 FI->NoCfCheck = info.getNoCfCheck();
820 FI->Required = required;
821 FI->HasRegParm = info.getHasRegParm();
822 FI->RegParm = info.getRegParm();
823 FI->ArgStruct = nullptr;
824 FI->ArgStructAlign = 0;
825 FI->NumArgs = argTypes.size();
826 FI->HasExtParameterInfos = !paramInfos.empty();
827 FI->getArgsBuffer()[0].type = resultType;
828 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
829 FI->getArgsBuffer()[i + 1].type = argTypes[i];
830 for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
831 FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
832 return FI;
833}
834
835/***/
836
837namespace {
838// ABIArgInfo::Expand implementation.
839
840// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
841struct TypeExpansion {
842 enum TypeExpansionKind {
843 // Elements of constant arrays are expanded recursively.
844 TEK_ConstantArray,
845 // Record fields are expanded recursively (but if record is a union, only
846 // the field with the largest size is expanded).
847 TEK_Record,
848 // For complex types, real and imaginary parts are expanded recursively.
849 TEK_Complex,
850 // All other types are not expandable.
851 TEK_None
852 };
853
854 const TypeExpansionKind Kind;
855
856 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
857 virtual ~TypeExpansion() {}
858};
859
860struct ConstantArrayExpansion : TypeExpansion {
861 QualType EltTy;
862 uint64_t NumElts;
863
864 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
865 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
866 static bool classof(const TypeExpansion *TE) {
867 return TE->Kind == TEK_ConstantArray;
868 }
869};
870
871struct RecordExpansion : TypeExpansion {
872 SmallVector<const CXXBaseSpecifier *, 1> Bases;
873
874 SmallVector<const FieldDecl *, 1> Fields;
875
876 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
877 SmallVector<const FieldDecl *, 1> &&Fields)
878 : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
879 Fields(std::move(Fields)) {}
880 static bool classof(const TypeExpansion *TE) {
881 return TE->Kind == TEK_Record;
882 }
883};
884
885struct ComplexExpansion : TypeExpansion {
886 QualType EltTy;
887
888 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
889 static bool classof(const TypeExpansion *TE) {
890 return TE->Kind == TEK_Complex;
891 }
892};
893
894struct NoExpansion : TypeExpansion {
895 NoExpansion() : TypeExpansion(TEK_None) {}
896 static bool classof(const TypeExpansion *TE) {
897 return TE->Kind == TEK_None;
898 }
899};
900} // namespace
901
902static std::unique_ptr<TypeExpansion>
903getTypeExpansion(QualType Ty, const ASTContext &Context) {
904 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
905 return llvm::make_unique<ConstantArrayExpansion>(
906 AT->getElementType(), AT->getSize().getZExtValue());
907 }
908 if (const RecordType *RT = Ty->getAs<RecordType>()) {
909 SmallVector<const CXXBaseSpecifier *, 1> Bases;
910 SmallVector<const FieldDecl *, 1> Fields;
911 const RecordDecl *RD = RT->getDecl();
912 assert(!RD->hasFlexibleArrayMember() &&(static_cast <bool> (!RD->hasFlexibleArrayMember() &&
"Cannot expand structure with flexible array.") ? void (0) :
__assert_fail ("!RD->hasFlexibleArrayMember() && \"Cannot expand structure with flexible array.\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 913, __extension__ __PRETTY_FUNCTION__))
913 "Cannot expand structure with flexible array.")(static_cast <bool> (!RD->hasFlexibleArrayMember() &&
"Cannot expand structure with flexible array.") ? void (0) :
__assert_fail ("!RD->hasFlexibleArrayMember() && \"Cannot expand structure with flexible array.\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 913, __extension__ __PRETTY_FUNCTION__))
;
914 if (RD->isUnion()) {
915 // Unions can be here only in degenerative cases - all the fields are same
916 // after flattening. Thus we have to use the "largest" field.
917 const FieldDecl *LargestFD = nullptr;
918 CharUnits UnionSize = CharUnits::Zero();
919
920 for (const auto *FD : RD->fields()) {
921 if (FD->isZeroLengthBitField(Context))
922 continue;
923 assert(!FD->isBitField() &&(static_cast <bool> (!FD->isBitField() && "Cannot expand structure with bit-field members."
) ? void (0) : __assert_fail ("!FD->isBitField() && \"Cannot expand structure with bit-field members.\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 924, __extension__ __PRETTY_FUNCTION__))
924 "Cannot expand structure with bit-field members.")(static_cast <bool> (!FD->isBitField() && "Cannot expand structure with bit-field members."
) ? void (0) : __assert_fail ("!FD->isBitField() && \"Cannot expand structure with bit-field members.\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 924, __extension__ __PRETTY_FUNCTION__))
;
925 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
926 if (UnionSize < FieldSize) {
927 UnionSize = FieldSize;
928 LargestFD = FD;
929 }
930 }
931 if (LargestFD)
932 Fields.push_back(LargestFD);
933 } else {
934 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
935 assert(!CXXRD->isDynamicClass() &&(static_cast <bool> (!CXXRD->isDynamicClass() &&
"cannot expand vtable pointers in dynamic classes") ? void (
0) : __assert_fail ("!CXXRD->isDynamicClass() && \"cannot expand vtable pointers in dynamic classes\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 936, __extension__ __PRETTY_FUNCTION__))
936 "cannot expand vtable pointers in dynamic classes")(static_cast <bool> (!CXXRD->isDynamicClass() &&
"cannot expand vtable pointers in dynamic classes") ? void (
0) : __assert_fail ("!CXXRD->isDynamicClass() && \"cannot expand vtable pointers in dynamic classes\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 936, __extension__ __PRETTY_FUNCTION__))
;
937 for (const CXXBaseSpecifier &BS : CXXRD->bases())
938 Bases.push_back(&BS);
939 }
940
941 for (const auto *FD : RD->fields()) {
942 if (FD->isZeroLengthBitField(Context))
943 continue;
944 assert(!FD->isBitField() &&(static_cast <bool> (!FD->isBitField() && "Cannot expand structure with bit-field members."
) ? void (0) : __assert_fail ("!FD->isBitField() && \"Cannot expand structure with bit-field members.\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 945, __extension__ __PRETTY_FUNCTION__))
945 "Cannot expand structure with bit-field members.")(static_cast <bool> (!FD->isBitField() && "Cannot expand structure with bit-field members."
) ? void (0) : __assert_fail ("!FD->isBitField() && \"Cannot expand structure with bit-field members.\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 945, __extension__ __PRETTY_FUNCTION__))
;
946 Fields.push_back(FD);
947 }
948 }
949 return llvm::make_unique<RecordExpansion>(std::move(Bases),
950 std::move(Fields));
951 }
952 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
953 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
954 }
955 return llvm::make_unique<NoExpansion>();
956}
957
958static int getExpansionSize(QualType Ty, const ASTContext &Context) {
959 auto Exp = getTypeExpansion(Ty, Context);
960 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
961 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
962 }
963 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
964 int Res = 0;
965 for (auto BS : RExp->Bases)
966 Res += getExpansionSize(BS->getType(), Context);
967 for (auto FD : RExp->Fields)
968 Res += getExpansionSize(FD->getType(), Context);
969 return Res;
970 }
971 if (isa<ComplexExpansion>(Exp.get()))
972 return 2;
973 assert(isa<NoExpansion>(Exp.get()))(static_cast <bool> (isa<NoExpansion>(Exp.get()))
? void (0) : __assert_fail ("isa<NoExpansion>(Exp.get())"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 973, __extension__ __PRETTY_FUNCTION__))
;
974 return 1;
975}
976
977void
978CodeGenTypes::getExpandedTypes(QualType Ty,
979 SmallVectorImpl<llvm::Type *>::iterator &TI) {
980 auto Exp = getTypeExpansion(Ty, Context);
981 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
982 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
983 getExpandedTypes(CAExp->EltTy, TI);
984 }
985 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
986 for (auto BS : RExp->Bases)
987 getExpandedTypes(BS->getType(), TI);
988 for (auto FD : RExp->Fields)
989 getExpandedTypes(FD->getType(), TI);
990 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
991 llvm::Type *EltTy = ConvertType(CExp->EltTy);
992 *TI++ = EltTy;
993 *TI++ = EltTy;
994 } else {
995 assert(isa<NoExpansion>(Exp.get()))(static_cast <bool> (isa<NoExpansion>(Exp.get()))
? void (0) : __assert_fail ("isa<NoExpansion>(Exp.get())"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 995, __extension__ __PRETTY_FUNCTION__))
;
996 *TI++ = ConvertType(Ty);
997 }
998}
999
1000static void forConstantArrayExpansion(CodeGenFunction &CGF,
1001 ConstantArrayExpansion *CAE,
1002 Address BaseAddr,
1003 llvm::function_ref<void(Address)> Fn) {
1004 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
1005 CharUnits EltAlign =
1006 BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
1007
1008 for (int i = 0, n = CAE->NumElts; i < n; i++) {
1009 llvm::Value *EltAddr =
1010 CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
1011 Fn(Address(EltAddr, EltAlign));
1012 }
1013}
1014
1015void CodeGenFunction::ExpandTypeFromArgs(
1016 QualType Ty, LValue LV, SmallVectorImpl<llvm::Value *>::iterator &AI) {
1017 assert(LV.isSimple() &&(static_cast <bool> (LV.isSimple() && "Unexpected non-simple lvalue during struct expansion."
) ? void (0) : __assert_fail ("LV.isSimple() && \"Unexpected non-simple lvalue during struct expansion.\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1018, __extension__ __PRETTY_FUNCTION__))
1018 "Unexpected non-simple lvalue during struct expansion.")(static_cast <bool> (LV.isSimple() && "Unexpected non-simple lvalue during struct expansion."
) ? void (0) : __assert_fail ("LV.isSimple() && \"Unexpected non-simple lvalue during struct expansion.\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1018, __extension__ __PRETTY_FUNCTION__))
;
1019
1020 auto Exp = getTypeExpansion(Ty, getContext());
1021 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1022 forConstantArrayExpansion(*this, CAExp, LV.getAddress(),
1023 [&](Address EltAddr) {
1024 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
1025 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
1026 });
1027 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1028 Address This = LV.getAddress();
1029 for (const CXXBaseSpecifier *BS : RExp->Bases) {
1030 // Perform a single step derived-to-base conversion.
1031 Address Base =
1032 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1033 /*NullCheckValue=*/false, SourceLocation());
1034 LValue SubLV = MakeAddrLValue(Base, BS->getType());
1035
1036 // Recurse onto bases.
1037 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
1038 }
1039 for (auto FD : RExp->Fields) {
1040 // FIXME: What are the right qualifiers here?
1041 LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
1042 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
1043 }
1044 } else if (isa<ComplexExpansion>(Exp.get())) {
1045 auto realValue = *AI++;
1046 auto imagValue = *AI++;
1047 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
1048 } else {
1049 assert(isa<NoExpansion>(Exp.get()))(static_cast <bool> (isa<NoExpansion>(Exp.get()))
? void (0) : __assert_fail ("isa<NoExpansion>(Exp.get())"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1049, __extension__ __PRETTY_FUNCTION__))
;
1050 EmitStoreThroughLValue(RValue::get(*AI++), LV);
1051 }
1052}
1053
1054void CodeGenFunction::ExpandTypeToArgs(
1055 QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
1056 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
1057 auto Exp = getTypeExpansion(Ty, getContext());
1058 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1059 Address Addr = Arg.hasLValue() ? Arg.getKnownLValue().getAddress()
1060 : Arg.getKnownRValue().getAggregateAddress();
1061 forConstantArrayExpansion(
1062 *this, CAExp, Addr, [&](Address EltAddr) {
1063 CallArg EltArg = CallArg(
1064 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation()),
1065 CAExp->EltTy);
1066 ExpandTypeToArgs(CAExp->EltTy, EltArg, IRFuncTy, IRCallArgs,
1067 IRCallArgPos);
1068 });
1069 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1070 Address This = Arg.hasLValue() ? Arg.getKnownLValue().getAddress()
1071 : Arg.getKnownRValue().getAggregateAddress();
1072 for (const CXXBaseSpecifier *BS : RExp->Bases) {
1073 // Perform a single step derived-to-base conversion.
1074 Address Base =
1075 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1076 /*NullCheckValue=*/false, SourceLocation());
1077 CallArg BaseArg = CallArg(RValue::getAggregate(Base), BS->getType());
1078
1079 // Recurse onto bases.
1080 ExpandTypeToArgs(BS->getType(), BaseArg, IRFuncTy, IRCallArgs,
1081 IRCallArgPos);
1082 }
1083
1084 LValue LV = MakeAddrLValue(This, Ty);
1085 for (auto FD : RExp->Fields) {
1086 CallArg FldArg =
1087 CallArg(EmitRValueForField(LV, FD, SourceLocation()), FD->getType());
1088 ExpandTypeToArgs(FD->getType(), FldArg, IRFuncTy, IRCallArgs,
1089 IRCallArgPos);
1090 }
1091 } else if (isa<ComplexExpansion>(Exp.get())) {
1092 ComplexPairTy CV = Arg.getKnownRValue().getComplexVal();
1093 IRCallArgs[IRCallArgPos++] = CV.first;
1094 IRCallArgs[IRCallArgPos++] = CV.second;
1095 } else {
1096 assert(isa<NoExpansion>(Exp.get()))(static_cast <bool> (isa<NoExpansion>(Exp.get()))
? void (0) : __assert_fail ("isa<NoExpansion>(Exp.get())"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1096, __extension__ __PRETTY_FUNCTION__))
;
1097 auto RV = Arg.getKnownRValue();
1098 assert(RV.isScalar() &&(static_cast <bool> (RV.isScalar() && "Unexpected non-scalar rvalue during struct expansion."
) ? void (0) : __assert_fail ("RV.isScalar() && \"Unexpected non-scalar rvalue during struct expansion.\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1099, __extension__ __PRETTY_FUNCTION__))
1099 "Unexpected non-scalar rvalue during struct expansion.")(static_cast <bool> (RV.isScalar() && "Unexpected non-scalar rvalue during struct expansion."
) ? void (0) : __assert_fail ("RV.isScalar() && \"Unexpected non-scalar rvalue during struct expansion.\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1099, __extension__ __PRETTY_FUNCTION__))
;
1100
1101 // Insert a bitcast as needed.
1102 llvm::Value *V = RV.getScalarVal();
1103 if (IRCallArgPos < IRFuncTy->getNumParams() &&
1104 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
1105 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
1106
1107 IRCallArgs[IRCallArgPos++] = V;
1108 }
1109}
1110
1111/// Create a temporary allocation for the purposes of coercion.
1112static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
1113 CharUnits MinAlign) {
1114 // Don't use an alignment that's worse than what LLVM would prefer.
1115 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
1116 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
1117
1118 return CGF.CreateTempAlloca(Ty, Align);
1119}
1120
1121/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
1122/// accessing some number of bytes out of it, try to gep into the struct to get
1123/// at its inner goodness. Dive as deep as possible without entering an element
1124/// with an in-memory size smaller than DstSize.
1125static Address
1126EnterStructPointerForCoercedAccess(Address SrcPtr,
1127 llvm::StructType *SrcSTy,
1128 uint64_t DstSize, CodeGenFunction &CGF) {
1129 // We can't dive into a zero-element struct.
1130 if (SrcSTy->getNumElements() == 0) return SrcPtr;
1131
1132 llvm::Type *FirstElt = SrcSTy->getElementType(0);
1133
1134 // If the first elt is at least as large as what we're looking for, or if the
1135 // first element is the same size as the whole struct, we can enter it. The
1136 // comparison must be made on the store size and not the alloca size. Using
1137 // the alloca size may overstate the size of the load.
1138 uint64_t FirstEltSize =
1139 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
1140 if (FirstEltSize < DstSize &&
1141 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
1142 return SrcPtr;
1143
1144 // GEP into the first element.
1145 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, CharUnits(), "coerce.dive");
1146
1147 // If the first element is a struct, recurse.
1148 llvm::Type *SrcTy = SrcPtr.getElementType();
1149 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
1150 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
1151
1152 return SrcPtr;
1153}
1154
1155/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1156/// are either integers or pointers. This does a truncation of the value if it
1157/// is too large or a zero extension if it is too small.
1158///
1159/// This behaves as if the value were coerced through memory, so on big-endian
1160/// targets the high bits are preserved in a truncation, while little-endian
1161/// targets preserve the low bits.
1162static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
1163 llvm::Type *Ty,
1164 CodeGenFunction &CGF) {
1165 if (Val->getType() == Ty)
1166 return Val;
1167
1168 if (isa<llvm::PointerType>(Val->getType())) {
1169 // If this is Pointer->Pointer avoid conversion to and from int.
1170 if (isa<llvm::PointerType>(Ty))
1171 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
1172
1173 // Convert the pointer to an integer so we can play with its width.
1174 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
1175 }
1176
1177 llvm::Type *DestIntTy = Ty;
1178 if (isa<llvm::PointerType>(DestIntTy))
1179 DestIntTy = CGF.IntPtrTy;
1180
1181 if (Val->getType() != DestIntTy) {
1182 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
1183 if (DL.isBigEndian()) {
1184 // Preserve the high bits on big-endian targets.
1185 // That is what memory coercion does.
1186 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1187 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1188
1189 if (SrcSize > DstSize) {
1190 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
1191 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
1192 } else {
1193 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
1194 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
1195 }
1196 } else {
1197 // Little-endian targets preserve the low bits. No shifts required.
1198 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
1199 }
1200 }
1201
1202 if (isa<llvm::PointerType>(Ty))
1203 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
1204 return Val;
1205}
1206
1207
1208
1209/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
1210/// a pointer to an object of type \arg Ty, known to be aligned to
1211/// \arg SrcAlign bytes.
1212///
1213/// This safely handles the case when the src type is smaller than the
1214/// destination type; in this situation the values of bits which not
1215/// present in the src are undefined.
1216static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
1217 CodeGenFunction &CGF) {
1218 llvm::Type *SrcTy = Src.getElementType();
1219
1220 // If SrcTy and Ty are the same, just do a load.
1221 if (SrcTy == Ty)
1222 return CGF.Builder.CreateLoad(Src);
1223
1224 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
1225
1226 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
1227 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF);
1228 SrcTy = Src.getType()->getElementType();
1229 }
1230
1231 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
1232
1233 // If the source and destination are integer or pointer types, just do an
1234 // extension or truncation to the desired type.
1235 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
1236 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
1237 llvm::Value *Load = CGF.Builder.CreateLoad(Src);
1238 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
1239 }
1240
1241 // If load is legal, just bitcast the src pointer.
1242 if (SrcSize >= DstSize) {
1243 // Generally SrcSize is never greater than DstSize, since this means we are
1244 // losing bits. However, this can happen in cases where the structure has
1245 // additional padding, for example due to a user specified alignment.
1246 //
1247 // FIXME: Assert that we aren't truncating non-padding bits when have access
1248 // to that information.
1249 Src = CGF.Builder.CreateBitCast(Src,
1250 Ty->getPointerTo(Src.getAddressSpace()));
1251 return CGF.Builder.CreateLoad(Src);
1252 }
1253
1254 // Otherwise do coercion through memory. This is stupid, but simple.
1255 Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment());
1256 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.AllocaInt8PtrTy);
1257 Address SrcCasted = CGF.Builder.CreateBitCast(Src, CGF.AllocaInt8PtrTy);
1258 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
1259 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
1260 false);
1261 return CGF.Builder.CreateLoad(Tmp);
1262}
1263
1264// Function to store a first-class aggregate into memory. We prefer to
1265// store the elements rather than the aggregate to be more friendly to
1266// fast-isel.
1267// FIXME: Do we need to recurse here?
1268static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
1269 Address Dest, bool DestIsVolatile) {
1270 // Prefer scalar stores to first-class aggregate stores.
1271 if (llvm::StructType *STy =
1272 dyn_cast<llvm::StructType>(Val->getType())) {
1273 const llvm::StructLayout *Layout =
1274 CGF.CGM.getDataLayout().getStructLayout(STy);
1275
1276 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1277 auto EltOffset = CharUnits::fromQuantity(Layout->getElementOffset(i));
1278 Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i, EltOffset);
1279 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
1280 CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
1281 }
1282 } else {
1283 CGF.Builder.CreateStore(Val, Dest, DestIsVolatile);
1284 }
1285}
1286
1287/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
1288/// where the source and destination may have different types. The
1289/// destination is known to be aligned to \arg DstAlign bytes.
1290///
1291/// This safely handles the case when the src type is larger than the
1292/// destination type; the upper bits of the src will be lost.
1293static void CreateCoercedStore(llvm::Value *Src,
1294 Address Dst,
1295 bool DstIsVolatile,
1296 CodeGenFunction &CGF) {
1297 llvm::Type *SrcTy = Src->getType();
1298 llvm::Type *DstTy = Dst.getType()->getElementType();
1299 if (SrcTy == DstTy) {
1300 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1301 return;
1302 }
1303
1304 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
1305
1306 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
1307 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF);
1308 DstTy = Dst.getType()->getElementType();
1309 }
1310
1311 // If the source and destination are integer or pointer types, just do an
1312 // extension or truncation to the desired type.
1313 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1314 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1315 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
1316 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1317 return;
1318 }
1319
1320 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
1321
1322 // If store is legal, just bitcast the src pointer.
1323 if (SrcSize <= DstSize) {
1324 Dst = CGF.Builder.CreateElementBitCast(Dst, SrcTy);
1325 BuildAggStore(CGF, Src, Dst, DstIsVolatile);
1326 } else {
1327 // Otherwise do coercion through memory. This is stupid, but
1328 // simple.
1329
1330 // Generally SrcSize is never greater than DstSize, since this means we are
1331 // losing bits. However, this can happen in cases where the structure has
1332 // additional padding, for example due to a user specified alignment.
1333 //
1334 // FIXME: Assert that we aren't truncating non-padding bits when have access
1335 // to that information.
1336 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1337 CGF.Builder.CreateStore(Src, Tmp);
1338 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.AllocaInt8PtrTy);
1339 Address DstCasted = CGF.Builder.CreateBitCast(Dst, CGF.AllocaInt8PtrTy);
1340 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1341 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
1342 false);
1343 }
1344}
1345
1346static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
1347 const ABIArgInfo &info) {
1348 if (unsigned offset = info.getDirectOffset()) {
1349 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
1350 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1351 CharUnits::fromQuantity(offset));
1352 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
1353 }
1354 return addr;
1355}
1356
1357namespace {
1358
1359/// Encapsulates information about the way function arguments from
1360/// CGFunctionInfo should be passed to actual LLVM IR function.
1361class ClangToLLVMArgMapping {
1362 static const unsigned InvalidIndex = ~0U;
1363 unsigned InallocaArgNo;
1364 unsigned SRetArgNo;
1365 unsigned TotalIRArgs;
1366
1367 /// Arguments of LLVM IR function corresponding to single Clang argument.
1368 struct IRArgs {
1369 unsigned PaddingArgIndex;
1370 // Argument is expanded to IR arguments at positions
1371 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1372 unsigned FirstArgIndex;
1373 unsigned NumberOfArgs;
1374
1375 IRArgs()
1376 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1377 NumberOfArgs(0) {}
1378 };
1379
1380 SmallVector<IRArgs, 8> ArgInfo;
1381
1382public:
1383 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1384 bool OnlyRequiredArgs = false)
1385 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1386 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1387 construct(Context, FI, OnlyRequiredArgs);
1388 }
1389
1390 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1391 unsigned getInallocaArgNo() const {
1392 assert(hasInallocaArg())(static_cast <bool> (hasInallocaArg()) ? void (0) : __assert_fail
("hasInallocaArg()", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1392, __extension__ __PRETTY_FUNCTION__))
;
1393 return InallocaArgNo;
1394 }
1395
1396 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1397 unsigned getSRetArgNo() const {
1398 assert(hasSRetArg())(static_cast <bool> (hasSRetArg()) ? void (0) : __assert_fail
("hasSRetArg()", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1398, __extension__ __PRETTY_FUNCTION__))
;
1399 return SRetArgNo;
1400 }
1401
1402 unsigned totalIRArgs() const { return TotalIRArgs; }
1403
1404 bool hasPaddingArg(unsigned ArgNo) const {
1405 assert(ArgNo < ArgInfo.size())(static_cast <bool> (ArgNo < ArgInfo.size()) ? void (
0) : __assert_fail ("ArgNo < ArgInfo.size()", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1405, __extension__ __PRETTY_FUNCTION__))
;
1406 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1407 }
1408 unsigned getPaddingArgNo(unsigned ArgNo) const {
1409 assert(hasPaddingArg(ArgNo))(static_cast <bool> (hasPaddingArg(ArgNo)) ? void (0) :
__assert_fail ("hasPaddingArg(ArgNo)", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1409, __extension__ __PRETTY_FUNCTION__))
;
1410 return ArgInfo[ArgNo].PaddingArgIndex;
1411 }
1412
1413 /// Returns index of first IR argument corresponding to ArgNo, and their
1414 /// quantity.
1415 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1416 assert(ArgNo < ArgInfo.size())(static_cast <bool> (ArgNo < ArgInfo.size()) ? void (
0) : __assert_fail ("ArgNo < ArgInfo.size()", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1416, __extension__ __PRETTY_FUNCTION__))
;
1417 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1418 ArgInfo[ArgNo].NumberOfArgs);
1419 }
1420
1421private:
1422 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1423 bool OnlyRequiredArgs);
1424};
1425
1426void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1427 const CGFunctionInfo &FI,
1428 bool OnlyRequiredArgs) {
1429 unsigned IRArgNo = 0;
1430 bool SwapThisWithSRet = false;
1431 const ABIArgInfo &RetAI = FI.getReturnInfo();
1432
1433 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1434 SwapThisWithSRet = RetAI.isSRetAfterThis();
1435 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1436 }
1437
1438 unsigned ArgNo = 0;
1439 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1440 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1441 ++I, ++ArgNo) {
1442 assert(I != FI.arg_end())(static_cast <bool> (I != FI.arg_end()) ? void (0) : __assert_fail
("I != FI.arg_end()", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1442, __extension__ __PRETTY_FUNCTION__))
;
1443 QualType ArgType = I->type;
1444 const ABIArgInfo &AI = I->info;
1445 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1446 auto &IRArgs = ArgInfo[ArgNo];
1447
1448 if (AI.getPaddingType())
1449 IRArgs.PaddingArgIndex = IRArgNo++;
1450
1451 switch (AI.getKind()) {
1452 case ABIArgInfo::Extend:
1453 case ABIArgInfo::Direct: {
1454 // FIXME: handle sseregparm someday...
1455 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1456 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1457 IRArgs.NumberOfArgs = STy->getNumElements();
1458 } else {
1459 IRArgs.NumberOfArgs = 1;
1460 }
1461 break;
1462 }
1463 case ABIArgInfo::Indirect:
1464 IRArgs.NumberOfArgs = 1;
1465 break;
1466 case ABIArgInfo::Ignore:
1467 case ABIArgInfo::InAlloca:
1468 // ignore and inalloca doesn't have matching LLVM parameters.
1469 IRArgs.NumberOfArgs = 0;
1470 break;
1471 case ABIArgInfo::CoerceAndExpand:
1472 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1473 break;
1474 case ABIArgInfo::Expand:
1475 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1476 break;
1477 }
1478
1479 if (IRArgs.NumberOfArgs > 0) {
1480 IRArgs.FirstArgIndex = IRArgNo;
1481 IRArgNo += IRArgs.NumberOfArgs;
1482 }
1483
1484 // Skip over the sret parameter when it comes second. We already handled it
1485 // above.
1486 if (IRArgNo == 1 && SwapThisWithSRet)
1487 IRArgNo++;
1488 }
1489 assert(ArgNo == ArgInfo.size())(static_cast <bool> (ArgNo == ArgInfo.size()) ? void (0
) : __assert_fail ("ArgNo == ArgInfo.size()", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1489, __extension__ __PRETTY_FUNCTION__))
;
1490
1491 if (FI.usesInAlloca())
1492 InallocaArgNo = IRArgNo++;
1493
1494 TotalIRArgs = IRArgNo;
1495}
1496} // namespace
1497
1498/***/
1499
1500bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
1501 const auto &RI = FI.getReturnInfo();
1502 return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet());
1503}
1504
1505bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1506 return ReturnTypeUsesSRet(FI) &&
1507 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1508}
1509
1510bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1511 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1512 switch (BT->getKind()) {
1513 default:
1514 return false;
1515 case BuiltinType::Float:
1516 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
1517 case BuiltinType::Double:
1518 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
1519 case BuiltinType::LongDouble:
1520 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
1521 }
1522 }
1523
1524 return false;
1525}
1526
1527bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1528 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1529 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1530 if (BT->getKind() == BuiltinType::LongDouble)
1531 return getTarget().useObjCFP2RetForComplexLongDouble();
1532 }
1533 }
1534
1535 return false;
1536}
1537
1538llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
1539 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1540 return GetFunctionType(FI);
1541}
1542
1543llvm::FunctionType *
1544CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
1545
1546 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1547 (void)Inserted;
1548 assert(Inserted && "Recursively being processed?")(static_cast <bool> (Inserted && "Recursively being processed?"
) ? void (0) : __assert_fail ("Inserted && \"Recursively being processed?\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1548, __extension__ __PRETTY_FUNCTION__))
;
1549
1550 llvm::Type *resultType = nullptr;
1551 const ABIArgInfo &retAI = FI.getReturnInfo();
1552 switch (retAI.getKind()) {
1553 case ABIArgInfo::Expand:
1554 llvm_unreachable("Invalid ABI kind for return argument")::llvm::llvm_unreachable_internal("Invalid ABI kind for return argument"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1554)
;
1555
1556 case ABIArgInfo::Extend:
1557 case ABIArgInfo::Direct:
1558 resultType = retAI.getCoerceToType();
1559 break;
1560
1561 case ABIArgInfo::InAlloca:
1562 if (retAI.getInAllocaSRet()) {
1563 // sret things on win32 aren't void, they return the sret pointer.
1564 QualType ret = FI.getReturnType();
1565 llvm::Type *ty = ConvertType(ret);
1566 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1567 resultType = llvm::PointerType::get(ty, addressSpace);
1568 } else {
1569 resultType = llvm::Type::getVoidTy(getLLVMContext());
1570 }
1571 break;
1572
1573 case ABIArgInfo::Indirect:
1574 case ABIArgInfo::Ignore:
1575 resultType = llvm::Type::getVoidTy(getLLVMContext());
1576 break;
1577
1578 case ABIArgInfo::CoerceAndExpand:
1579 resultType = retAI.getUnpaddedCoerceAndExpandType();
1580 break;
1581 }
1582
1583 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1584 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1585
1586 // Add type for sret argument.
1587 if (IRFunctionArgs.hasSRetArg()) {
1588 QualType Ret = FI.getReturnType();
1589 llvm::Type *Ty = ConvertType(Ret);
1590 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1591 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1592 llvm::PointerType::get(Ty, AddressSpace);
1593 }
1594
1595 // Add type for inalloca argument.
1596 if (IRFunctionArgs.hasInallocaArg()) {
1597 auto ArgStruct = FI.getArgStruct();
1598 assert(ArgStruct)(static_cast <bool> (ArgStruct) ? void (0) : __assert_fail
("ArgStruct", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1598, __extension__ __PRETTY_FUNCTION__))
;
1599 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1600 }
1601
1602 // Add in all of the required arguments.
1603 unsigned ArgNo = 0;
1604 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1605 ie = it + FI.getNumRequiredArgs();
1606 for (; it != ie; ++it, ++ArgNo) {
1607 const ABIArgInfo &ArgInfo = it->info;
1608
1609 // Insert a padding type to ensure proper alignment.
1610 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1611 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1612 ArgInfo.getPaddingType();
1613
1614 unsigned FirstIRArg, NumIRArgs;
1615 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1616
1617 switch (ArgInfo.getKind()) {
1618 case ABIArgInfo::Ignore:
1619 case ABIArgInfo::InAlloca:
1620 assert(NumIRArgs == 0)(static_cast <bool> (NumIRArgs == 0) ? void (0) : __assert_fail
("NumIRArgs == 0", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1620, __extension__ __PRETTY_FUNCTION__))
;
1621 break;
1622
1623 case ABIArgInfo::Indirect: {
1624 assert(NumIRArgs == 1)(static_cast <bool> (NumIRArgs == 1) ? void (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1624, __extension__ __PRETTY_FUNCTION__))
;
1625 // indirect arguments are always on the stack, which is alloca addr space.
1626 llvm::Type *LTy = ConvertTypeForMem(it->type);
1627 ArgTypes[FirstIRArg] = LTy->getPointerTo(
1628 CGM.getDataLayout().getAllocaAddrSpace());
1629 break;
1630 }
1631
1632 case ABIArgInfo::Extend:
1633 case ABIArgInfo::Direct: {
1634 // Fast-isel and the optimizer generally like scalar values better than
1635 // FCAs, so we flatten them if this is safe to do for this argument.
1636 llvm::Type *argType = ArgInfo.getCoerceToType();
1637 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
1638 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1639 assert(NumIRArgs == st->getNumElements())(static_cast <bool> (NumIRArgs == st->getNumElements
()) ? void (0) : __assert_fail ("NumIRArgs == st->getNumElements()"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1639, __extension__ __PRETTY_FUNCTION__))
;
1640 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
1641 ArgTypes[FirstIRArg + i] = st->getElementType(i);
1642 } else {
1643 assert(NumIRArgs == 1)(static_cast <bool> (NumIRArgs == 1) ? void (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1643, __extension__ __PRETTY_FUNCTION__))
;
1644 ArgTypes[FirstIRArg] = argType;
1645 }
1646 break;
1647 }
1648
1649 case ABIArgInfo::CoerceAndExpand: {
1650 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1651 for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1652 *ArgTypesIter++ = EltTy;
1653 }
1654 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs)(static_cast <bool> (ArgTypesIter == ArgTypes.begin() +
FirstIRArg + NumIRArgs) ? void (0) : __assert_fail ("ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1654, __extension__ __PRETTY_FUNCTION__))
;
1655 break;
1656 }
1657
1658 case ABIArgInfo::Expand:
1659 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1660 getExpandedTypes(it->type, ArgTypesIter);
1661 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs)(static_cast <bool> (ArgTypesIter == ArgTypes.begin() +
FirstIRArg + NumIRArgs) ? void (0) : __assert_fail ("ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1661, __extension__ __PRETTY_FUNCTION__))
;
1662 break;
1663 }
1664 }
1665
1666 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1667 assert(Erased && "Not in set?")(static_cast <bool> (Erased && "Not in set?") ?
void (0) : __assert_fail ("Erased && \"Not in set?\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1667, __extension__ __PRETTY_FUNCTION__))
;
1668
1669 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
1670}
1671
1672llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
1673 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1674 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
1675
1676 if (!isFuncTypeConvertible(FPT))
1677 return llvm::StructType::get(getLLVMContext());
1678
1679 const CGFunctionInfo *Info;
1680 if (isa<CXXDestructorDecl>(MD))
1681 Info =
1682 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
1683 else
1684 Info = &arrangeCXXMethodDeclaration(MD);
1685 return GetFunctionType(*Info);
1686}
1687
1688static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
1689 llvm::AttrBuilder &FuncAttrs,
1690 const FunctionProtoType *FPT) {
1691 if (!FPT)
1692 return;
1693
1694 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
1695 FPT->isNothrow())
1696 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1697}
1698
1699void CodeGenModule::ConstructDefaultFnAttrList(StringRef Name, bool HasOptnone,
1700 bool AttrOnCallSite,
1701 llvm::AttrBuilder &FuncAttrs) {
1702 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1703 if (!HasOptnone) {
1704 if (CodeGenOpts.OptimizeSize)
1705 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1706 if (CodeGenOpts.OptimizeSize == 2)
1707 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1708 }
1709
1710 if (CodeGenOpts.DisableRedZone)
1711 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
1712 if (CodeGenOpts.NoImplicitFloat)
1713 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
1714
1715 if (AttrOnCallSite) {
1716 // Attributes that should go on the call site only.
1717 if (!CodeGenOpts.SimplifyLibCalls ||
1718 CodeGenOpts.isNoBuiltinFunc(Name.data()))
1719 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
1720 if (!CodeGenOpts.TrapFuncName.empty())
1721 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
1722 } else {
1723 // Attributes that should go on the function, but not the call site.
1724 if (!CodeGenOpts.DisableFPElim) {
1725 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
1726 } else if (CodeGenOpts.OmitLeafFramePointer) {
1727 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
1728 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
1729 } else {
1730 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
1731 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
1732 }
1733
1734 FuncAttrs.addAttribute("less-precise-fpmad",
1735 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
1736
1737 if (CodeGenOpts.NullPointerIsValid)
1738 FuncAttrs.addAttribute("null-pointer-is-valid", "true");
1739 if (!CodeGenOpts.FPDenormalMode.empty())
1740 FuncAttrs.addAttribute("denormal-fp-math", CodeGenOpts.FPDenormalMode);
1741
1742 FuncAttrs.addAttribute("no-trapping-math",
1743 llvm::toStringRef(CodeGenOpts.NoTrappingMath));
1744
1745 // Strict (compliant) code is the default, so only add this attribute to
1746 // indicate that we are trying to workaround a problem case.
1747 if (!CodeGenOpts.StrictFloatCastOverflow)
1748 FuncAttrs.addAttribute("strict-float-cast-overflow", "false");
1749
1750 // TODO: Are these all needed?
1751 // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
1752 FuncAttrs.addAttribute("no-infs-fp-math",
1753 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
1754 FuncAttrs.addAttribute("no-nans-fp-math",
1755 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
1756 FuncAttrs.addAttribute("unsafe-fp-math",
1757 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
1758 FuncAttrs.addAttribute("use-soft-float",
1759 llvm::toStringRef(CodeGenOpts.SoftFloat));
1760 FuncAttrs.addAttribute("stack-protector-buffer-size",
1761 llvm::utostr(CodeGenOpts.SSPBufferSize));
1762 FuncAttrs.addAttribute("no-signed-zeros-fp-math",
1763 llvm::toStringRef(CodeGenOpts.NoSignedZeros));
1764 FuncAttrs.addAttribute(
1765 "correctly-rounded-divide-sqrt-fp-math",
1766 llvm::toStringRef(CodeGenOpts.CorrectlyRoundedDivSqrt));
1767
1768 if (getLangOpts().OpenCL)
1769 FuncAttrs.addAttribute("denorms-are-zero",
1770 llvm::toStringRef(CodeGenOpts.FlushDenorm));
1771
1772 // TODO: Reciprocal estimate codegen options should apply to instructions?
1773 const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals;
1774 if (!Recips.empty())
1775 FuncAttrs.addAttribute("reciprocal-estimates",
1776 llvm::join(Recips, ","));
1777
1778 if (!CodeGenOpts.PreferVectorWidth.empty() &&
1779 CodeGenOpts.PreferVectorWidth != "none")
1780 FuncAttrs.addAttribute("prefer-vector-width",
1781 CodeGenOpts.PreferVectorWidth);
1782
1783 if (CodeGenOpts.StackRealignment)
1784 FuncAttrs.addAttribute("stackrealign");
1785 if (CodeGenOpts.Backchain)
1786 FuncAttrs.addAttribute("backchain");
1787 }
1788
1789 if (getLangOpts().assumeFunctionsAreConvergent()) {
1790 // Conservatively, mark all functions and calls in CUDA and OpenCL as
1791 // convergent (meaning, they may call an intrinsically convergent op, such
1792 // as __syncthreads() / barrier(), and so can't have certain optimizations
1793 // applied around them). LLVM will remove this attribute where it safely
1794 // can.
1795 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
1796 }
1797
1798 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
1799 // Exceptions aren't supported in CUDA device code.
1800 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1801
1802 // Respect -fcuda-flush-denormals-to-zero.
1803 if (getLangOpts().CUDADeviceFlushDenormalsToZero)
1804 FuncAttrs.addAttribute("nvptx-f32ftz", "true");
1805 }
1806}
1807
1808void CodeGenModule::AddDefaultFnAttrs(llvm::Function &F) {
1809 llvm::AttrBuilder FuncAttrs;
1810 ConstructDefaultFnAttrList(F.getName(),
1811 F.hasFnAttribute(llvm::Attribute::OptimizeNone),
1812 /* AttrOnCallsite = */ false, FuncAttrs);
1813 F.addAttributes(llvm::AttributeList::FunctionIndex, FuncAttrs);
1814}
1815
1816void CodeGenModule::ConstructAttributeList(
1817 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo,
1818 llvm::AttributeList &AttrList, unsigned &CallingConv, bool AttrOnCallSite) {
1819 llvm::AttrBuilder FuncAttrs;
1820 llvm::AttrBuilder RetAttrs;
1821
1822 CallingConv = FI.getEffectiveCallingConvention();
1823 if (FI.isNoReturn())
1824 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1825
1826 // If we have information about the function prototype, we can learn
1827 // attributes from there.
1828 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
1829 CalleeInfo.getCalleeFunctionProtoType());
1830
1831 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
1832
1833 bool HasOptnone = false;
1834 // FIXME: handle sseregparm someday...
1835 if (TargetDecl) {
1836 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
1837 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
1838 if (TargetDecl->hasAttr<NoThrowAttr>())
1839 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1840 if (TargetDecl->hasAttr<NoReturnAttr>())
1841 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1842 if (TargetDecl->hasAttr<ColdAttr>())
1843 FuncAttrs.addAttribute(llvm::Attribute::Cold);
1844 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1845 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
1846 if (TargetDecl->hasAttr<ConvergentAttr>())
1847 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
1848
1849 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
1850 AddAttributesFromFunctionProtoType(
1851 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
1852 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1853 // These attributes are not inherited by overloads.
1854 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1855 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
1856 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1857 }
1858
1859 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
1860 if (TargetDecl->hasAttr<ConstAttr>()) {
1861 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1862 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1863 } else if (TargetDecl->hasAttr<PureAttr>()) {
1864 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1865 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1866 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
1867 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
1868 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1869 }
1870 if (TargetDecl->hasAttr<RestrictAttr>())
1871 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
1872 if (TargetDecl->hasAttr<ReturnsNonNullAttr>() &&
1873 !CodeGenOpts.NullPointerIsValid)
1874 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1875 if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
1876 FuncAttrs.addAttribute("no_caller_saved_registers");
1877 if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>())
1878 FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck);
1879
1880 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
1881 if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
1882 Optional<unsigned> NumElemsParam;
1883 if (AllocSize->getNumElemsParam().isValid())
1884 NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
1885 FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(),
1886 NumElemsParam);
1887 }
1888 }
1889
1890 ConstructDefaultFnAttrList(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
1891
1892 if (CodeGenOpts.EnableSegmentedStacks &&
1893 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
1894 FuncAttrs.addAttribute("split-stack");
1895
1896 // Add NonLazyBind attribute to function declarations when -fno-plt
1897 // is used.
1898 if (TargetDecl && CodeGenOpts.NoPLT) {
1899 if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
1900 if (!Fn->isDefined() && !AttrOnCallSite) {
1901 FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind);
1902 }
1903 }
1904 }
1905
1906 if (TargetDecl && TargetDecl->hasAttr<OpenCLKernelAttr>()) {
1907 if (getLangOpts().OpenCLVersion <= 120) {
1908 // OpenCL v1.2 Work groups are always uniform
1909 FuncAttrs.addAttribute("uniform-work-group-size", "true");
1910 } else {
1911 // OpenCL v2.0 Work groups may be whether uniform or not.
1912 // '-cl-uniform-work-group-size' compile option gets a hint
1913 // to the compiler that the global work-size be a multiple of
1914 // the work-group size specified to clEnqueueNDRangeKernel
1915 // (i.e. work groups are uniform).
1916 FuncAttrs.addAttribute("uniform-work-group-size",
1917 llvm::toStringRef(CodeGenOpts.UniformWGSize));
1918 }
1919 }
1920
1921 if (!AttrOnCallSite) {
1922 bool DisableTailCalls = false;
1923
1924 if (CodeGenOpts.DisableTailCalls)
1925 DisableTailCalls = true;
1926 else if (TargetDecl) {
1927 if (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
1928 TargetDecl->hasAttr<AnyX86InterruptAttr>())
1929 DisableTailCalls = true;
1930 else if (CodeGenOpts.NoEscapingBlockTailCalls) {
1931 if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl))
1932 if (!BD->doesNotEscape())
1933 DisableTailCalls = true;
1934 }
1935 }
1936
1937 FuncAttrs.addAttribute("disable-tail-calls",
1938 llvm::toStringRef(DisableTailCalls));
1939 GetCPUAndFeaturesAttributes(TargetDecl, FuncAttrs);
1940 }
1941
1942 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
1943
1944 QualType RetTy = FI.getReturnType();
1945 const ABIArgInfo &RetAI = FI.getReturnInfo();
1946 switch (RetAI.getKind()) {
1947 case ABIArgInfo::Extend:
1948 if (RetAI.isSignExt())
1949 RetAttrs.addAttribute(llvm::Attribute::SExt);
1950 else
1951 RetAttrs.addAttribute(llvm::Attribute::ZExt);
1952 LLVM_FALLTHROUGH[[clang::fallthrough]];
1953 case ABIArgInfo::Direct:
1954 if (RetAI.getInReg())
1955 RetAttrs.addAttribute(llvm::Attribute::InReg);
1956 break;
1957 case ABIArgInfo::Ignore:
1958 break;
1959
1960 case ABIArgInfo::InAlloca:
1961 case ABIArgInfo::Indirect: {
1962 // inalloca and sret disable readnone and readonly
1963 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1964 .removeAttribute(llvm::Attribute::ReadNone);
1965 break;
1966 }
1967
1968 case ABIArgInfo::CoerceAndExpand:
1969 break;
1970
1971 case ABIArgInfo::Expand:
1972 llvm_unreachable("Invalid ABI kind for return argument")::llvm::llvm_unreachable_internal("Invalid ABI kind for return argument"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 1972)
;
1973 }
1974
1975 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1976 QualType PTy = RefTy->getPointeeType();
1977 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1978 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1979 .getQuantity());
1980 else if (getContext().getTargetAddressSpace(PTy) == 0 &&
1981 !CodeGenOpts.NullPointerIsValid)
1982 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1983 }
1984
1985 bool hasUsedSRet = false;
1986 SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs());
1987
1988 // Attach attributes to sret.
1989 if (IRFunctionArgs.hasSRetArg()) {
1990 llvm::AttrBuilder SRETAttrs;
1991 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1992 hasUsedSRet = true;
1993 if (RetAI.getInReg())
1994 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1995 ArgAttrs[IRFunctionArgs.getSRetArgNo()] =
1996 llvm::AttributeSet::get(getLLVMContext(), SRETAttrs);
1997 }
1998
1999 // Attach attributes to inalloca argument.
2000 if (IRFunctionArgs.hasInallocaArg()) {
2001 llvm::AttrBuilder Attrs;
2002 Attrs.addAttribute(llvm::Attribute::InAlloca);
2003 ArgAttrs[IRFunctionArgs.getInallocaArgNo()] =
2004 llvm::AttributeSet::get(getLLVMContext(), Attrs);
2005 }
2006
2007 unsigned ArgNo = 0;
2008 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
2009 E = FI.arg_end();
2010 I != E; ++I, ++ArgNo) {
2011 QualType ParamType = I->type;
2012 const ABIArgInfo &AI = I->info;
2013 llvm::AttrBuilder Attrs;
2014
2015 // Add attribute for padding argument, if necessary.
2016 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
2017 if (AI.getPaddingInReg()) {
2018 ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2019 llvm::AttributeSet::get(
2020 getLLVMContext(),
2021 llvm::AttrBuilder().addAttribute(llvm::Attribute::InReg));
2022 }
2023 }
2024
2025 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
2026 // have the corresponding parameter variable. It doesn't make
2027 // sense to do it here because parameters are so messed up.
2028 switch (AI.getKind()) {
2029 case ABIArgInfo::Extend:
2030 if (AI.isSignExt())
2031 Attrs.addAttribute(llvm::Attribute::SExt);
2032 else
2033 Attrs.addAttribute(llvm::Attribute::ZExt);
2034 LLVM_FALLTHROUGH[[clang::fallthrough]];
2035 case ABIArgInfo::Direct:
2036 if (ArgNo == 0 && FI.isChainCall())
2037 Attrs.addAttribute(llvm::Attribute::Nest);
2038 else if (AI.getInReg())
2039 Attrs.addAttribute(llvm::Attribute::InReg);
2040 break;
2041
2042 case ABIArgInfo::Indirect: {
2043 if (AI.getInReg())
2044 Attrs.addAttribute(llvm::Attribute::InReg);
2045
2046 if (AI.getIndirectByVal())
2047 Attrs.addAttribute(llvm::Attribute::ByVal);
2048
2049 CharUnits Align = AI.getIndirectAlign();
2050
2051 // In a byval argument, it is important that the required
2052 // alignment of the type is honored, as LLVM might be creating a
2053 // *new* stack object, and needs to know what alignment to give
2054 // it. (Sometimes it can deduce a sensible alignment on its own,
2055 // but not if clang decides it must emit a packed struct, or the
2056 // user specifies increased alignment requirements.)
2057 //
2058 // This is different from indirect *not* byval, where the object
2059 // exists already, and the align attribute is purely
2060 // informative.
2061 assert(!Align.isZero())(static_cast <bool> (!Align.isZero()) ? void (0) : __assert_fail
("!Align.isZero()", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2061, __extension__ __PRETTY_FUNCTION__))
;
2062
2063 // For now, only add this when we have a byval argument.
2064 // TODO: be less lazy about updating test cases.
2065 if (AI.getIndirectByVal())
2066 Attrs.addAlignmentAttr(Align.getQuantity());
2067
2068 // byval disables readnone and readonly.
2069 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
2070 .removeAttribute(llvm::Attribute::ReadNone);
2071 break;
2072 }
2073 case ABIArgInfo::Ignore:
2074 case ABIArgInfo::Expand:
2075 case ABIArgInfo::CoerceAndExpand:
2076 break;
2077
2078 case ABIArgInfo::InAlloca:
2079 // inalloca disables readnone and readonly.
2080 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
2081 .removeAttribute(llvm::Attribute::ReadNone);
2082 continue;
2083 }
2084
2085 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
2086 QualType PTy = RefTy->getPointeeType();
2087 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2088 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
2089 .getQuantity());
2090 else if (getContext().getTargetAddressSpace(PTy) == 0 &&
2091 !CodeGenOpts.NullPointerIsValid)
2092 Attrs.addAttribute(llvm::Attribute::NonNull);
2093 }
2094
2095 switch (FI.getExtParameterInfo(ArgNo).getABI()) {
2096 case ParameterABI::Ordinary:
2097 break;
2098
2099 case ParameterABI::SwiftIndirectResult: {
2100 // Add 'sret' if we haven't already used it for something, but
2101 // only if the result is void.
2102 if (!hasUsedSRet && RetTy->isVoidType()) {
2103 Attrs.addAttribute(llvm::Attribute::StructRet);
2104 hasUsedSRet = true;
2105 }
2106
2107 // Add 'noalias' in either case.
2108 Attrs.addAttribute(llvm::Attribute::NoAlias);
2109
2110 // Add 'dereferenceable' and 'alignment'.
2111 auto PTy = ParamType->getPointeeType();
2112 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2113 auto info = getContext().getTypeInfoInChars(PTy);
2114 Attrs.addDereferenceableAttr(info.first.getQuantity());
2115 Attrs.addAttribute(llvm::Attribute::getWithAlignment(getLLVMContext(),
2116 info.second.getQuantity()));
2117 }
2118 break;
2119 }
2120
2121 case ParameterABI::SwiftErrorResult:
2122 Attrs.addAttribute(llvm::Attribute::SwiftError);
2123 break;
2124
2125 case ParameterABI::SwiftContext:
2126 Attrs.addAttribute(llvm::Attribute::SwiftSelf);
2127 break;
2128 }
2129
2130 if (FI.getExtParameterInfo(ArgNo).isNoEscape())
2131 Attrs.addAttribute(llvm::Attribute::NoCapture);
2132
2133 if (Attrs.hasAttributes()) {
2134 unsigned FirstIRArg, NumIRArgs;
2135 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2136 for (unsigned i = 0; i < NumIRArgs; i++)
2137 ArgAttrs[FirstIRArg + i] =
2138 llvm::AttributeSet::get(getLLVMContext(), Attrs);
2139 }
2140 }
2141 assert(ArgNo == FI.arg_size())(static_cast <bool> (ArgNo == FI.arg_size()) ? void (0)
: __assert_fail ("ArgNo == FI.arg_size()", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2141, __extension__ __PRETTY_FUNCTION__))
;
2142
2143 AttrList = llvm::AttributeList::get(
2144 getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs),
2145 llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs);
2146}
2147
2148/// An argument came in as a promoted argument; demote it back to its
2149/// declared type.
2150static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
2151 const VarDecl *var,
2152 llvm::Value *value) {
2153 llvm::Type *varType = CGF.ConvertType(var->getType());
2154
2155 // This can happen with promotions that actually don't change the
2156 // underlying type, like the enum promotions.
2157 if (value->getType() == varType) return value;
2158
2159 assert((varType->isIntegerTy() || varType->isFloatingPointTy())(static_cast <bool> ((varType->isIntegerTy() || varType
->isFloatingPointTy()) && "unexpected promotion type"
) ? void (0) : __assert_fail ("(varType->isIntegerTy() || varType->isFloatingPointTy()) && \"unexpected promotion type\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2160, __extension__ __PRETTY_FUNCTION__))
2160 && "unexpected promotion type")(static_cast <bool> ((varType->isIntegerTy() || varType
->isFloatingPointTy()) && "unexpected promotion type"
) ? void (0) : __assert_fail ("(varType->isIntegerTy() || varType->isFloatingPointTy()) && \"unexpected promotion type\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2160, __extension__ __PRETTY_FUNCTION__))
;
2161
2162 if (isa<llvm::IntegerType>(varType))
2163 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2164
2165 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2166}
2167
2168/// Returns the attribute (either parameter attribute, or function
2169/// attribute), which declares argument ArgNo to be non-null.
2170static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2171 QualType ArgType, unsigned ArgNo) {
2172 // FIXME: __attribute__((nonnull)) can also be applied to:
2173 // - references to pointers, where the pointee is known to be
2174 // nonnull (apparently a Clang extension)
2175 // - transparent unions containing pointers
2176 // In the former case, LLVM IR cannot represent the constraint. In
2177 // the latter case, we have no guarantee that the transparent union
2178 // is in fact passed as a pointer.
2179 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2180 return nullptr;
2181 // First, check attribute on parameter itself.
2182 if (PVD) {
2183 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2184 return ParmNNAttr;
2185 }
2186 // Check function attributes.
2187 if (!FD)
2188 return nullptr;
2189 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
2190 if (NNAttr->isNonNull(ArgNo))
2191 return NNAttr;
2192 }
2193 return nullptr;
2194}
2195
2196namespace {
2197 struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2198 Address Temp;
2199 Address Arg;
2200 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
2201 void Emit(CodeGenFunction &CGF, Flags flags) override {
2202 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2203 CGF.Builder.CreateStore(errorValue, Arg);
2204 }
2205 };
2206}
2207
2208void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
2209 llvm::Function *Fn,
2210 const FunctionArgList &Args) {
2211 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
1
Assuming the condition is false
2212 // Naked functions don't have prologues.
2213 return;
2214
2215 // If this is an implicit-return-zero function, go ahead and
2216 // initialize the return value. TODO: it might be nice to have
2217 // a more general mechanism for this that didn't require synthesized
2218 // return statements.
2219 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
2
Taking false branch
2220 if (FD->hasImplicitReturnZero()) {
2221 QualType RetTy = FD->getReturnType().getUnqualifiedType();
2222 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
2223 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
2224 Builder.CreateStore(Zero, ReturnValue);
2225 }
2226 }
2227
2228 // FIXME: We no longer need the types from FunctionArgList; lift up and
2229 // simplify.
2230
2231 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
2232 // Flattened function arguments.
2233 SmallVector<llvm::Value *, 16> FnArgs;
2234 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
2235 for (auto &Arg : Fn->args()) {
3
Assuming '__begin1' is equal to '__end1'
2236 FnArgs.push_back(&Arg);
2237 }
2238 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs())(static_cast <bool> (FnArgs.size() == IRFunctionArgs.totalIRArgs
()) ? void (0) : __assert_fail ("FnArgs.size() == IRFunctionArgs.totalIRArgs()"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2238, __extension__ __PRETTY_FUNCTION__))
;
2239
2240 // If we're using inalloca, all the memory arguments are GEPs off of the last
2241 // parameter, which is a pointer to the complete memory area.
2242 Address ArgStruct = Address::invalid();
2243 const llvm::StructLayout *ArgStructLayout = nullptr;
4
'ArgStructLayout' initialized to a null pointer value
2244 if (IRFunctionArgs.hasInallocaArg()) {
5
Taking false branch
2245 ArgStructLayout = CGM.getDataLayout().getStructLayout(FI.getArgStruct());
2246 ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()],
2247 FI.getArgStructAlignment());
2248
2249 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo())(static_cast <bool> (ArgStruct.getType() == FI.getArgStruct
()->getPointerTo()) ? void (0) : __assert_fail ("ArgStruct.getType() == FI.getArgStruct()->getPointerTo()"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2249, __extension__ __PRETTY_FUNCTION__))
;
2250 }
2251
2252 // Name the struct return parameter.
2253 if (IRFunctionArgs.hasSRetArg()) {
6
Taking false branch
2254 auto AI = cast<llvm::Argument>(FnArgs[IRFunctionArgs.getSRetArgNo()]);
2255 AI->setName("agg.result");
2256 AI->addAttr(llvm::Attribute::NoAlias);
2257 }
2258
2259 // Track if we received the parameter as a pointer (indirect, byval, or
2260 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
2261 // into a local alloca for us.
2262 SmallVector<ParamValue, 16> ArgVals;
2263 ArgVals.reserve(Args.size());
2264
2265 // Create a pointer value for every parameter declaration. This usually
2266 // entails copying one or more LLVM IR arguments into an alloca. Don't push
2267 // any cleanups or do anything that might unwind. We do that separately, so
2268 // we can push the cleanups in the correct order for the ABI.
2269 assert(FI.arg_size() == Args.size() &&(static_cast <bool> (FI.arg_size() == Args.size() &&
"Mismatch between function signature & arguments.") ? void
(0) : __assert_fail ("FI.arg_size() == Args.size() && \"Mismatch between function signature & arguments.\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2270, __extension__ __PRETTY_FUNCTION__))
2270 "Mismatch between function signature & arguments.")(static_cast <bool> (FI.arg_size() == Args.size() &&
"Mismatch between function signature & arguments.") ? void
(0) : __assert_fail ("FI.arg_size() == Args.size() && \"Mismatch between function signature & arguments.\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2270, __extension__ __PRETTY_FUNCTION__))
;
2271 unsigned ArgNo = 0;
2272 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
2273 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
8
Loop condition is true. Entering loop body
2274 i != e; ++i, ++info_it, ++ArgNo) {
7
Assuming 'i' is not equal to 'e'
2275 const VarDecl *Arg = *i;
2276 const ABIArgInfo &ArgI = info_it->info;
2277
2278 bool isPromoted =
2279 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
2280 // We are converting from ABIArgInfo type to VarDecl type directly, unless
2281 // the parameter is promoted. In this case we convert to
2282 // CGFunctionInfo::ArgInfo type with subsequent argument demotion.
2283 QualType Ty = isPromoted ? info_it->type : Arg->getType();
9
'?' condition is false
2284 assert(hasScalarEvaluationKind(Ty) ==(static_cast <bool> (hasScalarEvaluationKind(Ty) == hasScalarEvaluationKind
(Arg->getType())) ? void (0) : __assert_fail ("hasScalarEvaluationKind(Ty) == hasScalarEvaluationKind(Arg->getType())"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2285, __extension__ __PRETTY_FUNCTION__))
2285 hasScalarEvaluationKind(Arg->getType()))(static_cast <bool> (hasScalarEvaluationKind(Ty) == hasScalarEvaluationKind
(Arg->getType())) ? void (0) : __assert_fail ("hasScalarEvaluationKind(Ty) == hasScalarEvaluationKind(Arg->getType())"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2285, __extension__ __PRETTY_FUNCTION__))
;
2286
2287 unsigned FirstIRArg, NumIRArgs;
2288 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2289
2290 switch (ArgI.getKind()) {
10
Control jumps to 'case InAlloca:' at line 2291
2291 case ABIArgInfo::InAlloca: {
2292 assert(NumIRArgs == 0)(static_cast <bool> (NumIRArgs == 0) ? void (0) : __assert_fail
("NumIRArgs == 0", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2292, __extension__ __PRETTY_FUNCTION__))
;
2293 auto FieldIndex = ArgI.getInAllocaFieldIndex();
2294 CharUnits FieldOffset =
2295 CharUnits::fromQuantity(ArgStructLayout->getElementOffset(FieldIndex));
11
Called C++ object pointer is null
2296 Address V = Builder.CreateStructGEP(ArgStruct, FieldIndex, FieldOffset,
2297 Arg->getName());
2298 ArgVals.push_back(ParamValue::forIndirect(V));
2299 break;
2300 }
2301
2302 case ABIArgInfo::Indirect: {
2303 assert(NumIRArgs == 1)(static_cast <bool> (NumIRArgs == 1) ? void (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2303, __extension__ __PRETTY_FUNCTION__))
;
2304 Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign());
2305
2306 if (!hasScalarEvaluationKind(Ty)) {
2307 // Aggregates and complex variables are accessed by reference. All we
2308 // need to do is realign the value, if requested.
2309 Address V = ParamAddr;
2310 if (ArgI.getIndirectRealign()) {
2311 Address AlignedTemp = CreateMemTemp(Ty, "coerce");
2312
2313 // Copy from the incoming argument pointer to the temporary with the
2314 // appropriate alignment.
2315 //
2316 // FIXME: We should have a common utility for generating an aggregate
2317 // copy.
2318 CharUnits Size = getContext().getTypeSizeInChars(Ty);
2319 auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity());
2320 Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy);
2321 Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy);
2322 Builder.CreateMemCpy(Dst, Src, SizeVal, false);
2323 V = AlignedTemp;
2324 }
2325 ArgVals.push_back(ParamValue::forIndirect(V));
2326 } else {
2327 // Load scalar value from indirect argument.
2328 llvm::Value *V =
2329 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getLocStart());
2330
2331 if (isPromoted)
2332 V = emitArgumentDemotion(*this, Arg, V);
2333 ArgVals.push_back(ParamValue::forDirect(V));
2334 }
2335 break;
2336 }
2337
2338 case ABIArgInfo::Extend:
2339 case ABIArgInfo::Direct: {
2340
2341 // If we have the trivial case, handle it with no muss and fuss.
2342 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
2343 ArgI.getCoerceToType() == ConvertType(Ty) &&
2344 ArgI.getDirectOffset() == 0) {
2345 assert(NumIRArgs == 1)(static_cast <bool> (NumIRArgs == 1) ? void (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2345, __extension__ __PRETTY_FUNCTION__))
;
2346 llvm::Value *V = FnArgs[FirstIRArg];
2347 auto AI = cast<llvm::Argument>(V);
2348
2349 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
2350 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
2351 PVD->getFunctionScopeIndex()) &&
2352 !CGM.getCodeGenOpts().NullPointerIsValid)
2353 AI->addAttr(llvm::Attribute::NonNull);
2354
2355 QualType OTy = PVD->getOriginalType();
2356 if (const auto *ArrTy =
2357 getContext().getAsConstantArrayType(OTy)) {
2358 // A C99 array parameter declaration with the static keyword also
2359 // indicates dereferenceability, and if the size is constant we can
2360 // use the dereferenceable attribute (which requires the size in
2361 // bytes).
2362 if (ArrTy->getSizeModifier() == ArrayType::Static) {
2363 QualType ETy = ArrTy->getElementType();
2364 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
2365 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
2366 ArrSize) {
2367 llvm::AttrBuilder Attrs;
2368 Attrs.addDereferenceableAttr(
2369 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
2370 AI->addAttrs(Attrs);
2371 } else if (getContext().getTargetAddressSpace(ETy) == 0 &&
2372 !CGM.getCodeGenOpts().NullPointerIsValid) {
2373 AI->addAttr(llvm::Attribute::NonNull);
2374 }
2375 }
2376 } else if (const auto *ArrTy =
2377 getContext().getAsVariableArrayType(OTy)) {
2378 // For C99 VLAs with the static keyword, we don't know the size so
2379 // we can't use the dereferenceable attribute, but in addrspace(0)
2380 // we know that it must be nonnull.
2381 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
2382 !getContext().getTargetAddressSpace(ArrTy->getElementType()) &&
2383 !CGM.getCodeGenOpts().NullPointerIsValid)
2384 AI->addAttr(llvm::Attribute::NonNull);
2385 }
2386
2387 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
2388 if (!AVAttr)
2389 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
2390 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
2391 if (AVAttr) {
2392 llvm::Value *AlignmentValue =
2393 EmitScalarExpr(AVAttr->getAlignment());
2394 llvm::ConstantInt *AlignmentCI =
2395 cast<llvm::ConstantInt>(AlignmentValue);
2396 unsigned Alignment = std::min((unsigned)AlignmentCI->getZExtValue(),
2397 +llvm::Value::MaximumAlignment);
2398 AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(Alignment));
2399 }
2400 }
2401
2402 if (Arg->getType().isRestrictQualified())
2403 AI->addAttr(llvm::Attribute::NoAlias);
2404
2405 // LLVM expects swifterror parameters to be used in very restricted
2406 // ways. Copy the value into a less-restricted temporary.
2407 if (FI.getExtParameterInfo(ArgNo).getABI()
2408 == ParameterABI::SwiftErrorResult) {
2409 QualType pointeeTy = Ty->getPointeeType();
2410 assert(pointeeTy->isPointerType())(static_cast <bool> (pointeeTy->isPointerType()) ? void
(0) : __assert_fail ("pointeeTy->isPointerType()", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2410, __extension__ __PRETTY_FUNCTION__))
;
2411 Address temp =
2412 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
2413 Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy));
2414 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
2415 Builder.CreateStore(incomingErrorValue, temp);
2416 V = temp.getPointer();
2417
2418 // Push a cleanup to copy the value back at the end of the function.
2419 // The convention does not guarantee that the value will be written
2420 // back if the function exits with an unwind exception.
2421 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
2422 }
2423
2424 // Ensure the argument is the correct type.
2425 if (V->getType() != ArgI.getCoerceToType())
2426 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
2427
2428 if (isPromoted)
2429 V = emitArgumentDemotion(*this, Arg, V);
2430
2431 // Because of merging of function types from multiple decls it is
2432 // possible for the type of an argument to not match the corresponding
2433 // type in the function type. Since we are codegening the callee
2434 // in here, add a cast to the argument type.
2435 llvm::Type *LTy = ConvertType(Arg->getType());
2436 if (V->getType() != LTy)
2437 V = Builder.CreateBitCast(V, LTy);
2438
2439 ArgVals.push_back(ParamValue::forDirect(V));
2440 break;
2441 }
2442
2443 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
2444 Arg->getName());
2445
2446 // Pointer to store into.
2447 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
2448
2449 // Fast-isel and the optimizer generally like scalar values better than
2450 // FCAs, so we flatten them if this is safe to do for this argument.
2451 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
2452 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
2453 STy->getNumElements() > 1) {
2454 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
2455 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
2456 llvm::Type *DstTy = Ptr.getElementType();
2457 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
2458
2459 Address AddrToStoreInto = Address::invalid();
2460 if (SrcSize <= DstSize) {
2461 AddrToStoreInto = Builder.CreateElementBitCast(Ptr, STy);
2462 } else {
2463 AddrToStoreInto =
2464 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
2465 }
2466
2467 assert(STy->getNumElements() == NumIRArgs)(static_cast <bool> (STy->getNumElements() == NumIRArgs
) ? void (0) : __assert_fail ("STy->getNumElements() == NumIRArgs"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2467, __extension__ __PRETTY_FUNCTION__))
;
2468 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2469 auto AI = FnArgs[FirstIRArg + i];
2470 AI->setName(Arg->getName() + ".coerce" + Twine(i));
2471 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
2472 Address EltPtr =
2473 Builder.CreateStructGEP(AddrToStoreInto, i, Offset);
2474 Builder.CreateStore(AI, EltPtr);
2475 }
2476
2477 if (SrcSize > DstSize) {
2478 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
2479 }
2480
2481 } else {
2482 // Simple case, just do a coerced store of the argument into the alloca.
2483 assert(NumIRArgs == 1)(static_cast <bool> (NumIRArgs == 1) ? void (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2483, __extension__ __PRETTY_FUNCTION__))
;
2484 auto AI = FnArgs[FirstIRArg];
2485 AI->setName(Arg->getName() + ".coerce");
2486 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
2487 }
2488
2489 // Match to what EmitParmDecl is expecting for this type.
2490 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
2491 llvm::Value *V =
2492 EmitLoadOfScalar(Alloca, false, Ty, Arg->getLocStart());
2493 if (isPromoted)
2494 V = emitArgumentDemotion(*this, Arg, V);
2495 ArgVals.push_back(ParamValue::forDirect(V));
2496 } else {
2497 ArgVals.push_back(ParamValue::forIndirect(Alloca));
2498 }
2499 break;
2500 }
2501
2502 case ABIArgInfo::CoerceAndExpand: {
2503 // Reconstruct into a temporary.
2504 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2505 ArgVals.push_back(ParamValue::forIndirect(alloca));
2506
2507 auto coercionType = ArgI.getCoerceAndExpandType();
2508 alloca = Builder.CreateElementBitCast(alloca, coercionType);
2509 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2510
2511 unsigned argIndex = FirstIRArg;
2512 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2513 llvm::Type *eltType = coercionType->getElementType(i);
2514 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
2515 continue;
2516
2517 auto eltAddr = Builder.CreateStructGEP(alloca, i, layout);
2518 auto elt = FnArgs[argIndex++];
2519 Builder.CreateStore(elt, eltAddr);
2520 }
2521 assert(argIndex == FirstIRArg + NumIRArgs)(static_cast <bool> (argIndex == FirstIRArg + NumIRArgs
) ? void (0) : __assert_fail ("argIndex == FirstIRArg + NumIRArgs"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2521, __extension__ __PRETTY_FUNCTION__))
;
2522 break;
2523 }
2524
2525 case ABIArgInfo::Expand: {
2526 // If this structure was expanded into multiple arguments then
2527 // we need to create a temporary and reconstruct it from the
2528 // arguments.
2529 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2530 LValue LV = MakeAddrLValue(Alloca, Ty);
2531 ArgVals.push_back(ParamValue::forIndirect(Alloca));
2532
2533 auto FnArgIter = FnArgs.begin() + FirstIRArg;
2534 ExpandTypeFromArgs(Ty, LV, FnArgIter);
2535 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs)(static_cast <bool> (FnArgIter == FnArgs.begin() + FirstIRArg
+ NumIRArgs) ? void (0) : __assert_fail ("FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2535, __extension__ __PRETTY_FUNCTION__))
;
2536 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2537 auto AI = FnArgs[FirstIRArg + i];
2538 AI->setName(Arg->getName() + "." + Twine(i));
2539 }
2540 break;
2541 }
2542
2543 case ABIArgInfo::Ignore:
2544 assert(NumIRArgs == 0)(static_cast <bool> (NumIRArgs == 0) ? void (0) : __assert_fail
("NumIRArgs == 0", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2544, __extension__ __PRETTY_FUNCTION__))
;
2545 // Initialize the local variable appropriately.
2546 if (!hasScalarEvaluationKind(Ty)) {
2547 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
2548 } else {
2549 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
2550 ArgVals.push_back(ParamValue::forDirect(U));
2551 }
2552 break;
2553 }
2554 }
2555
2556 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2557 for (int I = Args.size() - 1; I >= 0; --I)
2558 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
2559 } else {
2560 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2561 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
2562 }
2563}
2564
2565static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2566 while (insn->use_empty()) {
2567 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2568 if (!bitcast) return;
2569
2570 // This is "safe" because we would have used a ConstantExpr otherwise.
2571 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2572 bitcast->eraseFromParent();
2573 }
2574}
2575
2576/// Try to emit a fused autorelease of a return result.
2577static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2578 llvm::Value *result) {
2579 // We must be immediately followed the cast.
2580 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
2581 if (BB->empty()) return nullptr;
2582 if (&BB->back() != result) return nullptr;
2583
2584 llvm::Type *resultType = result->getType();
2585
2586 // result is in a BasicBlock and is therefore an Instruction.
2587 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2588
2589 SmallVector<llvm::Instruction *, 4> InstsToKill;
2590
2591 // Look for:
2592 // %generator = bitcast %type1* %generator2 to %type2*
2593 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2594 // We would have emitted this as a constant if the operand weren't
2595 // an Instruction.
2596 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2597
2598 // Require the generator to be immediately followed by the cast.
2599 if (generator->getNextNode() != bitcast)
2600 return nullptr;
2601
2602 InstsToKill.push_back(bitcast);
2603 }
2604
2605 // Look for:
2606 // %generator = call i8* @objc_retain(i8* %originalResult)
2607 // or
2608 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2609 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
2610 if (!call) return nullptr;
2611
2612 bool doRetainAutorelease;
2613
2614 if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) {
2615 doRetainAutorelease = true;
2616 } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints()
2617 .objc_retainAutoreleasedReturnValue) {
2618 doRetainAutorelease = false;
2619
2620 // If we emitted an assembly marker for this call (and the
2621 // ARCEntrypoints field should have been set if so), go looking
2622 // for that call. If we can't find it, we can't do this
2623 // optimization. But it should always be the immediately previous
2624 // instruction, unless we needed bitcasts around the call.
2625 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
2626 llvm::Instruction *prev = call->getPrevNode();
2627 assert(prev)(static_cast <bool> (prev) ? void (0) : __assert_fail (
"prev", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2627, __extension__ __PRETTY_FUNCTION__))
;
2628 if (isa<llvm::BitCastInst>(prev)) {
2629 prev = prev->getPrevNode();
2630 assert(prev)(static_cast <bool> (prev) ? void (0) : __assert_fail (
"prev", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2630, __extension__ __PRETTY_FUNCTION__))
;
2631 }
2632 assert(isa<llvm::CallInst>(prev))(static_cast <bool> (isa<llvm::CallInst>(prev)) ?
void (0) : __assert_fail ("isa<llvm::CallInst>(prev)",
"/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2632, __extension__ __PRETTY_FUNCTION__))
;
2633 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==(static_cast <bool> (cast<llvm::CallInst>(prev)->
getCalledValue() == CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker
) ? void (0) : __assert_fail ("cast<llvm::CallInst>(prev)->getCalledValue() == CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2634, __extension__ __PRETTY_FUNCTION__))
2634 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker)(static_cast <bool> (cast<llvm::CallInst>(prev)->
getCalledValue() == CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker
) ? void (0) : __assert_fail ("cast<llvm::CallInst>(prev)->getCalledValue() == CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2634, __extension__ __PRETTY_FUNCTION__))
;
2635 InstsToKill.push_back(prev);
2636 }
2637 } else {
2638 return nullptr;
2639 }
2640
2641 result = call->getArgOperand(0);
2642 InstsToKill.push_back(call);
2643
2644 // Keep killing bitcasts, for sanity. Note that we no longer care
2645 // about precise ordering as long as there's exactly one use.
2646 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2647 if (!bitcast->hasOneUse()) break;
2648 InstsToKill.push_back(bitcast);
2649 result = bitcast->getOperand(0);
2650 }
2651
2652 // Delete all the unnecessary instructions, from latest to earliest.
2653 for (auto *I : InstsToKill)
2654 I->eraseFromParent();
2655
2656 // Do the fused retain/autorelease if we were asked to.
2657 if (doRetainAutorelease)
2658 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2659
2660 // Cast back to the result type.
2661 return CGF.Builder.CreateBitCast(result, resultType);
2662}
2663
2664/// If this is a +1 of the value of an immutable 'self', remove it.
2665static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2666 llvm::Value *result) {
2667 // This is only applicable to a method with an immutable 'self'.
2668 const ObjCMethodDecl *method =
2669 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
2670 if (!method) return nullptr;
2671 const VarDecl *self = method->getSelfDecl();
2672 if (!self->getType().isConstQualified()) return nullptr;
2673
2674 // Look for a retain call.
2675 llvm::CallInst *retainCall =
2676 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2677 if (!retainCall ||
2678 retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain)
2679 return nullptr;
2680
2681 // Look for an ordinary load of 'self'.
2682 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2683 llvm::LoadInst *load =
2684 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2685 if (!load || load->isAtomic() || load->isVolatile() ||
2686 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
2687 return nullptr;
2688
2689 // Okay! Burn it all down. This relies for correctness on the
2690 // assumption that the retain is emitted as part of the return and
2691 // that thereafter everything is used "linearly".
2692 llvm::Type *resultType = result->getType();
2693 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2694 assert(retainCall->use_empty())(static_cast <bool> (retainCall->use_empty()) ? void
(0) : __assert_fail ("retainCall->use_empty()", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2694, __extension__ __PRETTY_FUNCTION__))
;
2695 retainCall->eraseFromParent();
2696 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2697
2698 return CGF.Builder.CreateBitCast(load, resultType);
2699}
2700
2701/// Emit an ARC autorelease of the result of a function.
2702///
2703/// \return the value to actually return from the function
2704static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2705 llvm::Value *result) {
2706 // If we're returning 'self', kill the initial retain. This is a
2707 // heuristic attempt to "encourage correctness" in the really unfortunate
2708 // case where we have a return of self during a dealloc and we desperately
2709 // need to avoid the possible autorelease.
2710 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2711 return self;
2712
2713 // At -O0, try to emit a fused retain/autorelease.
2714 if (CGF.shouldUseFusedARCCalls())
2715 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2716 return fused;
2717
2718 return CGF.EmitARCAutoreleaseReturnValue(result);
2719}
2720
2721/// Heuristically search for a dominating store to the return-value slot.
2722static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
2723 // Check if a User is a store which pointerOperand is the ReturnValue.
2724 // We are looking for stores to the ReturnValue, not for stores of the
2725 // ReturnValue to some other location.
2726 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
2727 auto *SI = dyn_cast<llvm::StoreInst>(U);
2728 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
2729 return nullptr;
2730 // These aren't actually possible for non-coerced returns, and we
2731 // only care about non-coerced returns on this code path.
2732 assert(!SI->isAtomic() && !SI->isVolatile())(static_cast <bool> (!SI->isAtomic() && !SI->
isVolatile()) ? void (0) : __assert_fail ("!SI->isAtomic() && !SI->isVolatile()"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2732, __extension__ __PRETTY_FUNCTION__))
;
2733 return SI;
2734 };
2735 // If there are multiple uses of the return-value slot, just check
2736 // for something immediately preceding the IP. Sometimes this can
2737 // happen with how we generate implicit-returns; it can also happen
2738 // with noreturn cleanups.
2739 if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
2740 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2741 if (IP->empty()) return nullptr;
2742 llvm::Instruction *I = &IP->back();
2743
2744 // Skip lifetime markers
2745 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
2746 IE = IP->rend();
2747 II != IE; ++II) {
2748 if (llvm::IntrinsicInst *Intrinsic =
2749 dyn_cast<llvm::IntrinsicInst>(&*II)) {
2750 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
2751 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
2752 ++II;
2753 if (II == IE)
2754 break;
2755 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
2756 continue;
2757 }
2758 }
2759 I = &*II;
2760 break;
2761 }
2762
2763 return GetStoreIfValid(I);
2764 }
2765
2766 llvm::StoreInst *store =
2767 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
2768 if (!store) return nullptr;
2769
2770 // Now do a first-and-dirty dominance check: just walk up the
2771 // single-predecessors chain from the current insertion point.
2772 llvm::BasicBlock *StoreBB = store->getParent();
2773 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2774 while (IP != StoreBB) {
2775 if (!(IP = IP->getSinglePredecessor()))
2776 return nullptr;
2777 }
2778
2779 // Okay, the store's basic block dominates the insertion point; we
2780 // can do our thing.
2781 return store;
2782}
2783
2784void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
2785 bool EmitRetDbgLoc,
2786 SourceLocation EndLoc) {
2787 if (FI.isNoReturn()) {
2788 // Noreturn functions don't return.
2789 EmitUnreachable(EndLoc);
2790 return;
2791 }
2792
2793 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2794 // Naked functions don't have epilogues.
2795 Builder.CreateUnreachable();
2796 return;
2797 }
2798
2799 // Functions with no result always return void.
2800 if (!ReturnValue.isValid()) {
2801 Builder.CreateRetVoid();
2802 return;
2803 }
2804
2805 llvm::DebugLoc RetDbgLoc;
2806 llvm::Value *RV = nullptr;
2807 QualType RetTy = FI.getReturnType();
2808 const ABIArgInfo &RetAI = FI.getReturnInfo();
2809
2810 switch (RetAI.getKind()) {
2811 case ABIArgInfo::InAlloca:
2812 // Aggregrates get evaluated directly into the destination. Sometimes we
2813 // need to return the sret value in a register, though.
2814 assert(hasAggregateEvaluationKind(RetTy))(static_cast <bool> (hasAggregateEvaluationKind(RetTy))
? void (0) : __assert_fail ("hasAggregateEvaluationKind(RetTy)"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2814, __extension__ __PRETTY_FUNCTION__))
;
2815 if (RetAI.getInAllocaSRet()) {
2816 llvm::Function::arg_iterator EI = CurFn->arg_end();
2817 --EI;
2818 llvm::Value *ArgStruct = &*EI;
2819 llvm::Value *SRet = Builder.CreateStructGEP(
2820 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
2821 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret");
2822 }
2823 break;
2824
2825 case ABIArgInfo::Indirect: {
2826 auto AI = CurFn->arg_begin();
2827 if (RetAI.isSRetAfterThis())
2828 ++AI;
2829 switch (getEvaluationKind(RetTy)) {
2830 case TEK_Complex: {
2831 ComplexPairTy RT =
2832 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
2833 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
2834 /*isInit*/ true);
2835 break;
2836 }
2837 case TEK_Aggregate:
2838 // Do nothing; aggregrates get evaluated directly into the destination.
2839 break;
2840 case TEK_Scalar:
2841 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
2842 MakeNaturalAlignAddrLValue(&*AI, RetTy),
2843 /*isInit*/ true);
2844 break;
2845 }
2846 break;
2847 }
2848
2849 case ABIArgInfo::Extend:
2850 case ABIArgInfo::Direct:
2851 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2852 RetAI.getDirectOffset() == 0) {
2853 // The internal return value temp always will have pointer-to-return-type
2854 // type, just do a load.
2855
2856 // If there is a dominating store to ReturnValue, we can elide
2857 // the load, zap the store, and usually zap the alloca.
2858 if (llvm::StoreInst *SI =
2859 findDominatingStoreToReturnValue(*this)) {
2860 // Reuse the debug location from the store unless there is
2861 // cleanup code to be emitted between the store and return
2862 // instruction.
2863 if (EmitRetDbgLoc && !AutoreleaseResult)
2864 RetDbgLoc = SI->getDebugLoc();
2865 // Get the stored value and nuke the now-dead store.
2866 RV = SI->getValueOperand();
2867 SI->eraseFromParent();
2868
2869 // If that was the only use of the return value, nuke it as well now.
2870 auto returnValueInst = ReturnValue.getPointer();
2871 if (returnValueInst->use_empty()) {
2872 if (auto alloca = dyn_cast<llvm::AllocaInst>(returnValueInst)) {
2873 alloca->eraseFromParent();
2874 ReturnValue = Address::invalid();
2875 }
2876 }
2877
2878 // Otherwise, we have to do a simple load.
2879 } else {
2880 RV = Builder.CreateLoad(ReturnValue);
2881 }
2882 } else {
2883 // If the value is offset in memory, apply the offset now.
2884 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
2885
2886 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
2887 }
2888
2889 // In ARC, end functions that return a retainable type with a call
2890 // to objc_autoreleaseReturnValue.
2891 if (AutoreleaseResult) {
2892#ifndef NDEBUG
2893 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
2894 // been stripped of the typedefs, so we cannot use RetTy here. Get the
2895 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
2896 // CurCodeDecl or BlockInfo.
2897 QualType RT;
2898
2899 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
2900 RT = FD->getReturnType();
2901 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
2902 RT = MD->getReturnType();
2903 else if (isa<BlockDecl>(CurCodeDecl))
2904 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
2905 else
2906 llvm_unreachable("Unexpected function/method type")::llvm::llvm_unreachable_internal("Unexpected function/method type"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2906)
;
2907
2908 assert(getLangOpts().ObjCAutoRefCount &&(static_cast <bool> (getLangOpts().ObjCAutoRefCount &&
!FI.isReturnsRetained() && RT->isObjCRetainableType
()) ? void (0) : __assert_fail ("getLangOpts().ObjCAutoRefCount && !FI.isReturnsRetained() && RT->isObjCRetainableType()"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2910, __extension__ __PRETTY_FUNCTION__))
2909 !FI.isReturnsRetained() &&(static_cast <bool> (getLangOpts().ObjCAutoRefCount &&
!FI.isReturnsRetained() && RT->isObjCRetainableType
()) ? void (0) : __assert_fail ("getLangOpts().ObjCAutoRefCount && !FI.isReturnsRetained() && RT->isObjCRetainableType()"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2910, __extension__ __PRETTY_FUNCTION__))
2910 RT->isObjCRetainableType())(static_cast <bool> (getLangOpts().ObjCAutoRefCount &&
!FI.isReturnsRetained() && RT->isObjCRetainableType
()) ? void (0) : __assert_fail ("getLangOpts().ObjCAutoRefCount && !FI.isReturnsRetained() && RT->isObjCRetainableType()"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2910, __extension__ __PRETTY_FUNCTION__))
;
2911#endif
2912 RV = emitAutoreleaseOfResult(*this, RV);
2913 }
2914
2915 break;
2916
2917 case ABIArgInfo::Ignore:
2918 break;
2919
2920 case ABIArgInfo::CoerceAndExpand: {
2921 auto coercionType = RetAI.getCoerceAndExpandType();
2922 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2923
2924 // Load all of the coerced elements out into results.
2925 llvm::SmallVector<llvm::Value*, 4> results;
2926 Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
2927 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2928 auto coercedEltType = coercionType->getElementType(i);
2929 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
2930 continue;
2931
2932 auto eltAddr = Builder.CreateStructGEP(addr, i, layout);
2933 auto elt = Builder.CreateLoad(eltAddr);
2934 results.push_back(elt);
2935 }
2936
2937 // If we have one result, it's the single direct result type.
2938 if (results.size() == 1) {
2939 RV = results[0];
2940
2941 // Otherwise, we need to make a first-class aggregate.
2942 } else {
2943 // Construct a return type that lacks padding elements.
2944 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
2945
2946 RV = llvm::UndefValue::get(returnType);
2947 for (unsigned i = 0, e = results.size(); i != e; ++i) {
2948 RV = Builder.CreateInsertValue(RV, results[i], i);
2949 }
2950 }
2951 break;
2952 }
2953
2954 case ABIArgInfo::Expand:
2955 llvm_unreachable("Invalid ABI kind for return argument")::llvm::llvm_unreachable_internal("Invalid ABI kind for return argument"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2955)
;
2956 }
2957
2958 llvm::Instruction *Ret;
2959 if (RV) {
2960 EmitReturnValueCheck(RV);
2961 Ret = Builder.CreateRet(RV);
2962 } else {
2963 Ret = Builder.CreateRetVoid();
2964 }
2965
2966 if (RetDbgLoc)
2967 Ret->setDebugLoc(std::move(RetDbgLoc));
2968}
2969
2970void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) {
2971 // A current decl may not be available when emitting vtable thunks.
2972 if (!CurCodeDecl)
2973 return;
2974
2975 ReturnsNonNullAttr *RetNNAttr = nullptr;
2976 if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
2977 RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
2978
2979 if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
2980 return;
2981
2982 // Prefer the returns_nonnull attribute if it's present.
2983 SourceLocation AttrLoc;
2984 SanitizerMask CheckKind;
2985 SanitizerHandler Handler;
2986 if (RetNNAttr) {
2987 assert(!requiresReturnValueNullabilityCheck() &&(static_cast <bool> (!requiresReturnValueNullabilityCheck
() && "Cannot check nullability and the nonnull attribute"
) ? void (0) : __assert_fail ("!requiresReturnValueNullabilityCheck() && \"Cannot check nullability and the nonnull attribute\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2988, __extension__ __PRETTY_FUNCTION__))
2988 "Cannot check nullability and the nonnull attribute")(static_cast <bool> (!requiresReturnValueNullabilityCheck
() && "Cannot check nullability and the nonnull attribute"
) ? void (0) : __assert_fail ("!requiresReturnValueNullabilityCheck() && \"Cannot check nullability and the nonnull attribute\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 2988, __extension__ __PRETTY_FUNCTION__))
;
2989 AttrLoc = RetNNAttr->getLocation();
2990 CheckKind = SanitizerKind::ReturnsNonnullAttribute;
2991 Handler = SanitizerHandler::NonnullReturn;
2992 } else {
2993 if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl))
2994 if (auto *TSI = DD->getTypeSourceInfo())
2995 if (auto FTL = TSI->getTypeLoc().castAs<FunctionTypeLoc>())
2996 AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
2997 CheckKind = SanitizerKind::NullabilityReturn;
2998 Handler = SanitizerHandler::NullabilityReturn;
2999 }
3000
3001 SanitizerScope SanScope(this);
3002
3003 // Make sure the "return" source location is valid. If we're checking a
3004 // nullability annotation, make sure the preconditions for the check are met.
3005 llvm::BasicBlock *Check = createBasicBlock("nullcheck");
3006 llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck");
3007 llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load");
3008 llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr);
3009 if (requiresReturnValueNullabilityCheck())
3010 CanNullCheck =
3011 Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition);
3012 Builder.CreateCondBr(CanNullCheck, Check, NoCheck);
3013 EmitBlock(Check);
3014
3015 // Now do the null check.
3016 llvm::Value *Cond = Builder.CreateIsNotNull(RV);
3017 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)};
3018 llvm::Value *DynamicData[] = {SLocPtr};
3019 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData);
3020
3021 EmitBlock(NoCheck);
3022
3023#ifndef NDEBUG
3024 // The return location should not be used after the check has been emitted.
3025 ReturnLocation = Address::invalid();
3026#endif
3027}
3028
3029static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
3030 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
3031 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
3032}
3033
3034static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
3035 QualType Ty) {
3036 // FIXME: Generate IR in one pass, rather than going back and fixing up these
3037 // placeholders.
3038 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
3039 llvm::Type *IRPtrTy = IRTy->getPointerTo();
3040 llvm::Value *Placeholder = llvm::UndefValue::get(IRPtrTy->getPointerTo());
3041
3042 // FIXME: When we generate this IR in one pass, we shouldn't need
3043 // this win32-specific alignment hack.
3044 CharUnits Align = CharUnits::fromQuantity(4);
3045 Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
3046
3047 return AggValueSlot::forAddr(Address(Placeholder, Align),
3048 Ty.getQualifiers(),
3049 AggValueSlot::IsNotDestructed,
3050 AggValueSlot::DoesNotNeedGCBarriers,
3051 AggValueSlot::IsNotAliased,
3052 AggValueSlot::DoesNotOverlap);
3053}
3054
3055void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
3056 const VarDecl *param,
3057 SourceLocation loc) {
3058 // StartFunction converted the ABI-lowered parameter(s) into a
3059 // local alloca. We need to turn that into an r-value suitable
3060 // for EmitCall.
3061 Address local = GetAddrOfLocalVar(param);
3062
3063 QualType type = param->getType();
3064
3065 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&(static_cast <bool> (!isInAllocaArgument(CGM.getCXXABI(
), type) && "cannot emit delegate call arguments for inalloca arguments!"
) ? void (0) : __assert_fail ("!isInAllocaArgument(CGM.getCXXABI(), type) && \"cannot emit delegate call arguments for inalloca arguments!\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3066, __extension__ __PRETTY_FUNCTION__))
3066 "cannot emit delegate call arguments for inalloca arguments!")(static_cast <bool> (!isInAllocaArgument(CGM.getCXXABI(
), type) && "cannot emit delegate call arguments for inalloca arguments!"
) ? void (0) : __assert_fail ("!isInAllocaArgument(CGM.getCXXABI(), type) && \"cannot emit delegate call arguments for inalloca arguments!\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3066, __extension__ __PRETTY_FUNCTION__))
;
3067
3068 // GetAddrOfLocalVar returns a pointer-to-pointer for references,
3069 // but the argument needs to be the original pointer.
3070 if (type->isReferenceType()) {
3071 args.add(RValue::get(Builder.CreateLoad(local)), type);
3072
3073 // In ARC, move out of consumed arguments so that the release cleanup
3074 // entered by StartFunction doesn't cause an over-release. This isn't
3075 // optimal -O0 code generation, but it should get cleaned up when
3076 // optimization is enabled. This also assumes that delegate calls are
3077 // performed exactly once for a set of arguments, but that should be safe.
3078 } else if (getLangOpts().ObjCAutoRefCount &&
3079 param->hasAttr<NSConsumedAttr>() &&
3080 type->isObjCRetainableType()) {
3081 llvm::Value *ptr = Builder.CreateLoad(local);
3082 auto null =
3083 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
3084 Builder.CreateStore(null, local);
3085 args.add(RValue::get(ptr), type);
3086
3087 // For the most part, we just need to load the alloca, except that
3088 // aggregate r-values are actually pointers to temporaries.
3089 } else {
3090 args.add(convertTempToRValue(local, type, loc), type);
3091 }
3092
3093 // Deactivate the cleanup for the callee-destructed param that was pushed.
3094 if (hasAggregateEvaluationKind(type) && !CurFuncIsThunk &&
3095 type->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee() &&
3096 type.isDestructedType()) {
3097 EHScopeStack::stable_iterator cleanup =
3098 CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param));
3099 assert(cleanup.isValid() &&(static_cast <bool> (cleanup.isValid() && "cleanup for callee-destructed param not recorded"
) ? void (0) : __assert_fail ("cleanup.isValid() && \"cleanup for callee-destructed param not recorded\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3100, __extension__ __PRETTY_FUNCTION__))
3100 "cleanup for callee-destructed param not recorded")(static_cast <bool> (cleanup.isValid() && "cleanup for callee-destructed param not recorded"
) ? void (0) : __assert_fail ("cleanup.isValid() && \"cleanup for callee-destructed param not recorded\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3100, __extension__ __PRETTY_FUNCTION__))
;
3101 // This unreachable is a temporary marker which will be removed later.
3102 llvm::Instruction *isActive = Builder.CreateUnreachable();
3103 args.addArgCleanupDeactivation(cleanup, isActive);
3104 }
3105}
3106
3107static bool isProvablyNull(llvm::Value *addr) {
3108 return isa<llvm::ConstantPointerNull>(addr);
3109}
3110
3111/// Emit the actual writing-back of a writeback.
3112static void emitWriteback(CodeGenFunction &CGF,
3113 const CallArgList::Writeback &writeback) {
3114 const LValue &srcLV = writeback.Source;
3115 Address srcAddr = srcLV.getAddress();
3116 assert(!isProvablyNull(srcAddr.getPointer()) &&(static_cast <bool> (!isProvablyNull(srcAddr.getPointer
()) && "shouldn't have writeback for provably null argument"
) ? void (0) : __assert_fail ("!isProvablyNull(srcAddr.getPointer()) && \"shouldn't have writeback for provably null argument\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3117, __extension__ __PRETTY_FUNCTION__))
3117 "shouldn't have writeback for provably null argument")(static_cast <bool> (!isProvablyNull(srcAddr.getPointer
()) && "shouldn't have writeback for provably null argument"
) ? void (0) : __assert_fail ("!isProvablyNull(srcAddr.getPointer()) && \"shouldn't have writeback for provably null argument\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3117, __extension__ __PRETTY_FUNCTION__))
;
3118
3119 llvm::BasicBlock *contBB = nullptr;
3120
3121 // If the argument wasn't provably non-null, we need to null check
3122 // before doing the store.
3123 bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
3124 CGF.CGM.getDataLayout());
3125 if (!provablyNonNull) {
3126 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
3127 contBB = CGF.createBasicBlock("icr.done");
3128
3129 llvm::Value *isNull =
3130 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
3131 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
3132 CGF.EmitBlock(writebackBB);
3133 }
3134
3135 // Load the value to writeback.
3136 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
3137
3138 // Cast it back, in case we're writing an id to a Foo* or something.
3139 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
3140 "icr.writeback-cast");
3141
3142 // Perform the writeback.
3143
3144 // If we have a "to use" value, it's something we need to emit a use
3145 // of. This has to be carefully threaded in: if it's done after the
3146 // release it's potentially undefined behavior (and the optimizer
3147 // will ignore it), and if it happens before the retain then the
3148 // optimizer could move the release there.
3149 if (writeback.ToUse) {
3150 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong)(static_cast <bool> (srcLV.getObjCLifetime() == Qualifiers
::OCL_Strong) ? void (0) : __assert_fail ("srcLV.getObjCLifetime() == Qualifiers::OCL_Strong"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3150, __extension__ __PRETTY_FUNCTION__))
;
3151
3152 // Retain the new value. No need to block-copy here: the block's
3153 // being passed up the stack.
3154 value = CGF.EmitARCRetainNonBlock(value);
3155
3156 // Emit the intrinsic use here.
3157 CGF.EmitARCIntrinsicUse(writeback.ToUse);
3158
3159 // Load the old value (primitively).
3160 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
3161
3162 // Put the new value in place (primitively).
3163 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
3164
3165 // Release the old value.
3166 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
3167
3168 // Otherwise, we can just do a normal lvalue store.
3169 } else {
3170 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
3171 }
3172
3173 // Jump to the continuation block.
3174 if (!provablyNonNull)
3175 CGF.EmitBlock(contBB);
3176}
3177
3178static void emitWritebacks(CodeGenFunction &CGF,
3179 const CallArgList &args) {
3180 for (const auto &I : args.writebacks())
3181 emitWriteback(CGF, I);
3182}
3183
3184static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
3185 const CallArgList &CallArgs) {
3186 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
3187 CallArgs.getCleanupsToDeactivate();
3188 // Iterate in reverse to increase the likelihood of popping the cleanup.
3189 for (const auto &I : llvm::reverse(Cleanups)) {
3190 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
3191 I.IsActiveIP->eraseFromParent();
3192 }
3193}
3194
3195static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
3196 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
3197 if (uop->getOpcode() == UO_AddrOf)
3198 return uop->getSubExpr();
3199 return nullptr;
3200}
3201
3202/// Emit an argument that's being passed call-by-writeback. That is,
3203/// we are passing the address of an __autoreleased temporary; it
3204/// might be copy-initialized with the current value of the given
3205/// address, but it will definitely be copied out of after the call.
3206static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
3207 const ObjCIndirectCopyRestoreExpr *CRE) {
3208 LValue srcLV;
3209
3210 // Make an optimistic effort to emit the address as an l-value.
3211 // This can fail if the argument expression is more complicated.
3212 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
3213 srcLV = CGF.EmitLValue(lvExpr);
3214
3215 // Otherwise, just emit it as a scalar.
3216 } else {
3217 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
3218
3219 QualType srcAddrType =
3220 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
3221 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
3222 }
3223 Address srcAddr = srcLV.getAddress();
3224
3225 // The dest and src types don't necessarily match in LLVM terms
3226 // because of the crazy ObjC compatibility rules.
3227
3228 llvm::PointerType *destType =
3229 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
3230
3231 // If the address is a constant null, just pass the appropriate null.
3232 if (isProvablyNull(srcAddr.getPointer())) {
3233 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
3234 CRE->getType());
3235 return;
3236 }
3237
3238 // Create the temporary.
3239 Address temp = CGF.CreateTempAlloca(destType->getElementType(),
3240 CGF.getPointerAlign(),
3241 "icr.temp");
3242 // Loading an l-value can introduce a cleanup if the l-value is __weak,
3243 // and that cleanup will be conditional if we can't prove that the l-value
3244 // isn't null, so we need to register a dominating point so that the cleanups
3245 // system will make valid IR.
3246 CodeGenFunction::ConditionalEvaluation condEval(CGF);
3247
3248 // Zero-initialize it if we're not doing a copy-initialization.
3249 bool shouldCopy = CRE->shouldCopy();
3250 if (!shouldCopy) {
3251 llvm::Value *null =
3252 llvm::ConstantPointerNull::get(
3253 cast<llvm::PointerType>(destType->getElementType()));
3254 CGF.Builder.CreateStore(null, temp);
3255 }
3256
3257 llvm::BasicBlock *contBB = nullptr;
3258 llvm::BasicBlock *originBB = nullptr;
3259
3260 // If the address is *not* known to be non-null, we need to switch.
3261 llvm::Value *finalArgument;
3262
3263 bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
3264 CGF.CGM.getDataLayout());
3265 if (provablyNonNull) {
3266 finalArgument = temp.getPointer();
3267 } else {
3268 llvm::Value *isNull =
3269 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
3270
3271 finalArgument = CGF.Builder.CreateSelect(isNull,
3272 llvm::ConstantPointerNull::get(destType),
3273 temp.getPointer(), "icr.argument");
3274
3275 // If we need to copy, then the load has to be conditional, which
3276 // means we need control flow.
3277 if (shouldCopy) {
3278 originBB = CGF.Builder.GetInsertBlock();
3279 contBB = CGF.createBasicBlock("icr.cont");
3280 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
3281 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
3282 CGF.EmitBlock(copyBB);
3283 condEval.begin(CGF);
3284 }
3285 }
3286
3287 llvm::Value *valueToUse = nullptr;
3288
3289 // Perform a copy if necessary.
3290 if (shouldCopy) {
3291 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
3292 assert(srcRV.isScalar())(static_cast <bool> (srcRV.isScalar()) ? void (0) : __assert_fail
("srcRV.isScalar()", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3292, __extension__ __PRETTY_FUNCTION__))
;
3293
3294 llvm::Value *src = srcRV.getScalarVal();
3295 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
3296 "icr.cast");
3297
3298 // Use an ordinary store, not a store-to-lvalue.
3299 CGF.Builder.CreateStore(src, temp);
3300
3301 // If optimization is enabled, and the value was held in a
3302 // __strong variable, we need to tell the optimizer that this
3303 // value has to stay alive until we're doing the store back.
3304 // This is because the temporary is effectively unretained,
3305 // and so otherwise we can violate the high-level semantics.
3306 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3307 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
3308 valueToUse = src;
3309 }
3310 }
3311
3312 // Finish the control flow if we needed it.
3313 if (shouldCopy && !provablyNonNull) {
3314 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
3315 CGF.EmitBlock(contBB);
3316
3317 // Make a phi for the value to intrinsically use.
3318 if (valueToUse) {
3319 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
3320 "icr.to-use");
3321 phiToUse->addIncoming(valueToUse, copyBB);
3322 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
3323 originBB);
3324 valueToUse = phiToUse;
3325 }
3326
3327 condEval.end(CGF);
3328 }
3329
3330 args.addWriteback(srcLV, temp, valueToUse);
3331 args.add(RValue::get(finalArgument), CRE->getType());
3332}
3333
3334void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
3335 assert(!StackBase)(static_cast <bool> (!StackBase) ? void (0) : __assert_fail
("!StackBase", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3335, __extension__ __PRETTY_FUNCTION__))
;
3336
3337 // Save the stack.
3338 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
3339 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
3340}
3341
3342void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
3343 if (StackBase) {
3344 // Restore the stack after the call.
3345 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
3346 CGF.Builder.CreateCall(F, StackBase);
3347 }
3348}
3349
3350void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
3351 SourceLocation ArgLoc,
3352 AbstractCallee AC,
3353 unsigned ParmNum) {
3354 if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
3355 SanOpts.has(SanitizerKind::NullabilityArg)))
3356 return;
3357
3358 // The param decl may be missing in a variadic function.
3359 auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr;
3360 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
3361
3362 // Prefer the nonnull attribute if it's present.
3363 const NonNullAttr *NNAttr = nullptr;
3364 if (SanOpts.has(SanitizerKind::NonnullAttribute))
3365 NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
3366
3367 bool CanCheckNullability = false;
3368 if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD) {
3369 auto Nullability = PVD->getType()->getNullability(getContext());
3370 CanCheckNullability = Nullability &&
3371 *Nullability == NullabilityKind::NonNull &&
3372 PVD->getTypeSourceInfo();
3373 }
3374
3375 if (!NNAttr && !CanCheckNullability)
3376 return;
3377
3378 SourceLocation AttrLoc;
3379 SanitizerMask CheckKind;
3380 SanitizerHandler Handler;
3381 if (NNAttr) {
3382 AttrLoc = NNAttr->getLocation();
3383 CheckKind = SanitizerKind::NonnullAttribute;
3384 Handler = SanitizerHandler::NonnullArg;
3385 } else {
3386 AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
3387 CheckKind = SanitizerKind::NullabilityArg;
3388 Handler = SanitizerHandler::NullabilityArg;
3389 }
3390
3391 SanitizerScope SanScope(this);
3392 assert(RV.isScalar())(static_cast <bool> (RV.isScalar()) ? void (0) : __assert_fail
("RV.isScalar()", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3392, __extension__ __PRETTY_FUNCTION__))
;
3393 llvm::Value *V = RV.getScalarVal();
3394 llvm::Value *Cond =
3395 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
3396 llvm::Constant *StaticData[] = {
3397 EmitCheckSourceLocation(ArgLoc), EmitCheckSourceLocation(AttrLoc),
3398 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
3399 };
3400 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, None);
3401}
3402
3403void CodeGenFunction::EmitCallArgs(
3404 CallArgList &Args, ArrayRef<QualType> ArgTypes,
3405 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3406 AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
3407 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()))(static_cast <bool> ((int)ArgTypes.size() == (ArgRange.
end() - ArgRange.begin())) ? void (0) : __assert_fail ("(int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin())"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3407, __extension__ __PRETTY_FUNCTION__))
;
3408
3409 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
3410 // because arguments are destroyed left to right in the callee. As a special
3411 // case, there are certain language constructs that require left-to-right
3412 // evaluation, and in those cases we consider the evaluation order requirement
3413 // to trump the "destruction order is reverse construction order" guarantee.
3414 bool LeftToRight =
3415 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
3416 ? Order == EvaluationOrder::ForceLeftToRight
3417 : Order != EvaluationOrder::ForceRightToLeft;
3418
3419 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
3420 RValue EmittedArg) {
3421 if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
3422 return;
3423 auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
3424 if (PS == nullptr)
3425 return;
3426
3427 const auto &Context = getContext();
3428 auto SizeTy = Context.getSizeType();
3429 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
3430 assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?")(static_cast <bool> (EmittedArg.getScalarVal() &&
"We emitted nothing for the arg?") ? void (0) : __assert_fail
("EmittedArg.getScalarVal() && \"We emitted nothing for the arg?\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3430, __extension__ __PRETTY_FUNCTION__))
;
3431 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
3432 EmittedArg.getScalarVal());
3433 Args.add(RValue::get(V), SizeTy);
3434 // If we're emitting args in reverse, be sure to do so with
3435 // pass_object_size, as well.
3436 if (!LeftToRight)
3437 std::swap(Args.back(), *(&Args.back() - 1));
3438 };
3439
3440 // Insert a stack save if we're going to need any inalloca args.
3441 bool HasInAllocaArgs = false;
3442 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
3443 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
3444 I != E && !HasInAllocaArgs; ++I)
3445 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
3446 if (HasInAllocaArgs) {
3447 assert(getTarget().getTriple().getArch() == llvm::Triple::x86)(static_cast <bool> (getTarget().getTriple().getArch() ==
llvm::Triple::x86) ? void (0) : __assert_fail ("getTarget().getTriple().getArch() == llvm::Triple::x86"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3447, __extension__ __PRETTY_FUNCTION__))
;
3448 Args.allocateArgumentMemory(*this);
3449 }
3450 }
3451
3452 // Evaluate each argument in the appropriate order.
3453 size_t CallArgsStart = Args.size();
3454 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
3455 unsigned Idx = LeftToRight ? I : E - I - 1;
3456 CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
3457 unsigned InitialArgSize = Args.size();
3458 // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of
3459 // the argument and parameter match or the objc method is parameterized.
3460 assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) ||(static_cast <bool> ((!isa<ObjCIndirectCopyRestoreExpr
>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->
getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl
()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl
>(AC.getDecl())))) && "Argument and parameter types don't match"
) ? void (0) : __assert_fail ("(!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && \"Argument and parameter types don't match\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3465, __extension__ __PRETTY_FUNCTION__))
3461 getContext().hasSameUnqualifiedType((*Arg)->getType(),(static_cast <bool> ((!isa<ObjCIndirectCopyRestoreExpr
>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->
getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl
()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl
>(AC.getDecl())))) && "Argument and parameter types don't match"
) ? void (0) : __assert_fail ("(!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && \"Argument and parameter types don't match\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3465, __extension__ __PRETTY_FUNCTION__))
3462 ArgTypes[Idx]) ||(static_cast <bool> ((!isa<ObjCIndirectCopyRestoreExpr
>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->
getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl
()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl
>(AC.getDecl())))) && "Argument and parameter types don't match"
) ? void (0) : __assert_fail ("(!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && \"Argument and parameter types don't match\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3465, __extension__ __PRETTY_FUNCTION__))
3463 (isa<ObjCMethodDecl>(AC.getDecl()) &&(static_cast <bool> ((!isa<ObjCIndirectCopyRestoreExpr
>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->
getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl
()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl
>(AC.getDecl())))) && "Argument and parameter types don't match"
) ? void (0) : __assert_fail ("(!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && \"Argument and parameter types don't match\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3465, __extension__ __PRETTY_FUNCTION__))
3464 isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) &&(static_cast <bool> ((!isa<ObjCIndirectCopyRestoreExpr
>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->
getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl
()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl
>(AC.getDecl())))) && "Argument and parameter types don't match"
) ? void (0) : __assert_fail ("(!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && \"Argument and parameter types don't match\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3465, __extension__ __PRETTY_FUNCTION__))
3465 "Argument and parameter types don't match")(static_cast <bool> ((!isa<ObjCIndirectCopyRestoreExpr
>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->
getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl
()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl
>(AC.getDecl())))) && "Argument and parameter types don't match"
) ? void (0) : __assert_fail ("(!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && \"Argument and parameter types don't match\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3465, __extension__ __PRETTY_FUNCTION__))
;
3466 EmitCallArg(Args, *Arg, ArgTypes[Idx]);
3467 // In particular, we depend on it being the last arg in Args, and the
3468 // objectsize bits depend on there only being one arg if !LeftToRight.
3469 assert(InitialArgSize + 1 == Args.size() &&(static_cast <bool> (InitialArgSize + 1 == Args.size() &&
"The code below depends on only adding one arg per EmitCallArg"
) ? void (0) : __assert_fail ("InitialArgSize + 1 == Args.size() && \"The code below depends on only adding one arg per EmitCallArg\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3470, __extension__ __PRETTY_FUNCTION__))
3470 "The code below depends on only adding one arg per EmitCallArg")(static_cast <bool> (InitialArgSize + 1 == Args.size() &&
"The code below depends on only adding one arg per EmitCallArg"
) ? void (0) : __assert_fail ("InitialArgSize + 1 == Args.size() && \"The code below depends on only adding one arg per EmitCallArg\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3470, __extension__ __PRETTY_FUNCTION__))
;
3471 (void)InitialArgSize;
3472 // Since pointer argument are never emitted as LValue, it is safe to emit
3473 // non-null argument check for r-value only.
3474 if (!Args.back().hasLValue()) {
3475 RValue RVArg = Args.back().getKnownRValue();
3476 EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
3477 ParamsToSkip + Idx);
3478 // @llvm.objectsize should never have side-effects and shouldn't need
3479 // destruction/cleanups, so we can safely "emit" it after its arg,
3480 // regardless of right-to-leftness
3481 MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
3482 }
3483 }
3484
3485 if (!LeftToRight) {
3486 // Un-reverse the arguments we just evaluated so they match up with the LLVM
3487 // IR function.
3488 std::reverse(Args.begin() + CallArgsStart, Args.end());
3489 }
3490}
3491
3492namespace {
3493
3494struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
3495 DestroyUnpassedArg(Address Addr, QualType Ty)
3496 : Addr(Addr), Ty(Ty) {}
3497
3498 Address Addr;
3499 QualType Ty;
3500
3501 void Emit(CodeGenFunction &CGF, Flags flags) override {
3502 QualType::DestructionKind DtorKind = Ty.isDestructedType();
3503 if (DtorKind == QualType::DK_cxx_destructor) {
3504 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
3505 assert(!Dtor->isTrivial())(static_cast <bool> (!Dtor->isTrivial()) ? void (0) :
__assert_fail ("!Dtor->isTrivial()", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3505, __extension__ __PRETTY_FUNCTION__))
;
3506 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
3507 /*Delegating=*/false, Addr);
3508 } else {
3509 CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty));
3510 }
3511 }
3512};
3513
3514struct DisableDebugLocationUpdates {
3515 CodeGenFunction &CGF;
3516 bool disabledDebugInfo;
3517 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
3518 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
3519 CGF.disableDebugInfo();
3520 }
3521 ~DisableDebugLocationUpdates() {
3522 if (disabledDebugInfo)
3523 CGF.enableDebugInfo();
3524 }
3525};
3526
3527} // end anonymous namespace
3528
3529RValue CallArg::getRValue(CodeGenFunction &CGF) const {
3530 if (!HasLV)
3531 return RV;
3532 LValue Copy = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty), Ty);
3533 CGF.EmitAggregateCopy(Copy, LV, Ty, AggValueSlot::DoesNotOverlap,
3534 LV.isVolatile());
3535 IsUsed = true;
3536 return RValue::getAggregate(Copy.getAddress());
3537}
3538
3539void CallArg::copyInto(CodeGenFunction &CGF, Address Addr) const {
3540 LValue Dst = CGF.MakeAddrLValue(Addr, Ty);
3541 if (!HasLV && RV.isScalar())
3542 CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*init=*/true);
3543 else if (!HasLV && RV.isComplex())
3544 CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true);
3545 else {
3546 auto Addr = HasLV ? LV.getAddress() : RV.getAggregateAddress();
3547 LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty);
3548 // We assume that call args are never copied into subobjects.
3549 CGF.EmitAggregateCopy(Dst, SrcLV, Ty, AggValueSlot::DoesNotOverlap,
3550 HasLV ? LV.isVolatileQualified()
3551 : RV.isVolatileQualified());
3552 }
3553 IsUsed = true;
3554}
3555
3556void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
3557 QualType type) {
3558 DisableDebugLocationUpdates Dis(*this, E);
3559 if (const ObjCIndirectCopyRestoreExpr *CRE
3560 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
3561 assert(getLangOpts().ObjCAutoRefCount)(static_cast <bool> (getLangOpts().ObjCAutoRefCount) ? void
(0) : __assert_fail ("getLangOpts().ObjCAutoRefCount", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3561, __extension__ __PRETTY_FUNCTION__))
;
3562 return emitWritebackArg(*this, args, CRE);
3563 }
3564
3565 assert(type->isReferenceType() == E->isGLValue() &&(static_cast <bool> (type->isReferenceType() == E->
isGLValue() && "reference binding to unmaterialized r-value!"
) ? void (0) : __assert_fail ("type->isReferenceType() == E->isGLValue() && \"reference binding to unmaterialized r-value!\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3566, __extension__ __PRETTY_FUNCTION__))
3566 "reference binding to unmaterialized r-value!")(static_cast <bool> (type->isReferenceType() == E->
isGLValue() && "reference binding to unmaterialized r-value!"
) ? void (0) : __assert_fail ("type->isReferenceType() == E->isGLValue() && \"reference binding to unmaterialized r-value!\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3566, __extension__ __PRETTY_FUNCTION__))
;
3567
3568 if (E->isGLValue()) {
3569 assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary
) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3569, __extension__ __PRETTY_FUNCTION__))
;
3570 return args.add(EmitReferenceBindingToExpr(E), type);
3571 }
3572
3573 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
3574
3575 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
3576 // However, we still have to push an EH-only cleanup in case we unwind before
3577 // we make it to the call.
3578 if (HasAggregateEvalKind &&
3579 type->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
3580 // If we're using inalloca, use the argument memory. Otherwise, use a
3581 // temporary.
3582 AggValueSlot Slot;
3583 if (args.isUsingInAlloca())
3584 Slot = createPlaceholderSlot(*this, type);
3585 else
3586 Slot = CreateAggTemp(type, "agg.tmp");
3587
3588 bool DestroyedInCallee = true, NeedsEHCleanup = true;
3589 if (const auto *RD = type->getAsCXXRecordDecl())
3590 DestroyedInCallee = RD->hasNonTrivialDestructor();
3591 else
3592 NeedsEHCleanup = needsEHCleanup(type.isDestructedType());
3593
3594 if (DestroyedInCallee)
3595 Slot.setExternallyDestructed();
3596
3597 EmitAggExpr(E, Slot);
3598 RValue RV = Slot.asRValue();
3599 args.add(RV, type);
3600
3601 if (DestroyedInCallee && NeedsEHCleanup) {
3602 // Create a no-op GEP between the placeholder and the cleanup so we can
3603 // RAUW it successfully. It also serves as a marker of the first
3604 // instruction where the cleanup is active.
3605 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
3606 type);
3607 // This unreachable is a temporary marker which will be removed later.
3608 llvm::Instruction *IsActive = Builder.CreateUnreachable();
3609 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
3610 }
3611 return;
3612 }
3613
3614 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
3615 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
3616 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
3617 assert(L.isSimple())(static_cast <bool> (L.isSimple()) ? void (0) : __assert_fail
("L.isSimple()", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3617, __extension__ __PRETTY_FUNCTION__))
;
3618 args.addUncopiedAggregate(L, type);
3619 return;
3620 }
3621
3622 args.add(EmitAnyExprToTemp(E), type);
3623}
3624
3625QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
3626 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
3627 // implicitly widens null pointer constants that are arguments to varargs
3628 // functions to pointer-sized ints.
3629 if (!getTarget().getTriple().isOSWindows())
3630 return Arg->getType();
3631
3632 if (Arg->getType()->isIntegerType() &&
3633 getContext().getTypeSize(Arg->getType()) <
3634 getContext().getTargetInfo().getPointerWidth(0) &&
3635 Arg->isNullPointerConstant(getContext(),
3636 Expr::NPC_ValueDependentIsNotNull)) {
3637 return getContext().getIntPtrType();
3638 }
3639
3640 return Arg->getType();
3641}
3642
3643// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3644// optimizer it can aggressively ignore unwind edges.
3645void
3646CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
3647 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3648 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
3649 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
3650 CGM.getNoObjCARCExceptionsMetadata());
3651}
3652
3653/// Emits a call to the given no-arguments nounwind runtime function.
3654llvm::CallInst *
3655CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3656 const llvm::Twine &name) {
3657 return EmitNounwindRuntimeCall(callee, None, name);
3658}
3659
3660/// Emits a call to the given nounwind runtime function.
3661llvm::CallInst *
3662CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3663 ArrayRef<llvm::Value*> args,
3664 const llvm::Twine &name) {
3665 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
3666 call->setDoesNotThrow();
3667 return call;
3668}
3669
3670/// Emits a simple call (never an invoke) to the given no-arguments
3671/// runtime function.
3672llvm::CallInst *
3673CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3674 const llvm::Twine &name) {
3675 return EmitRuntimeCall(callee, None, name);
3676}
3677
3678// Calls which may throw must have operand bundles indicating which funclet
3679// they are nested within.
3680SmallVector<llvm::OperandBundleDef, 1>
3681CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) {
3682 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3683 // There is no need for a funclet operand bundle if we aren't inside a
3684 // funclet.
3685 if (!CurrentFuncletPad)
3686 return BundleList;
3687
3688 // Skip intrinsics which cannot throw.
3689 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
3690 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
3691 return BundleList;
3692
3693 BundleList.emplace_back("funclet", CurrentFuncletPad);
3694 return BundleList;
3695}
3696
3697/// Emits a simple call (never an invoke) to the given runtime function.
3698llvm::CallInst *
3699CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3700 ArrayRef<llvm::Value*> args,
3701 const llvm::Twine &name) {
3702 llvm::CallInst *call =
3703 Builder.CreateCall(callee, args, getBundlesForFunclet(callee), name);
3704 call->setCallingConv(getRuntimeCC());
3705 return call;
3706}
3707
3708/// Emits a call or invoke to the given noreturn runtime function.
3709void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3710 ArrayRef<llvm::Value*> args) {
3711 SmallVector<llvm::OperandBundleDef, 1> BundleList =
3712 getBundlesForFunclet(callee);
3713
3714 if (getInvokeDest()) {
3715 llvm::InvokeInst *invoke =
3716 Builder.CreateInvoke(callee,
3717 getUnreachableBlock(),
3718 getInvokeDest(),
3719 args,
3720 BundleList);
3721 invoke->setDoesNotReturn();
3722 invoke->setCallingConv(getRuntimeCC());
3723 } else {
3724 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
3725 call->setDoesNotReturn();
3726 call->setCallingConv(getRuntimeCC());
3727 Builder.CreateUnreachable();
3728 }
3729}
3730
3731/// Emits a call or invoke instruction to the given nullary runtime function.
3732llvm::CallSite
3733CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3734 const Twine &name) {
3735 return EmitRuntimeCallOrInvoke(callee, None, name);
3736}
3737
3738/// Emits a call or invoke instruction to the given runtime function.
3739llvm::CallSite
3740CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3741 ArrayRef<llvm::Value*> args,
3742 const Twine &name) {
3743 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
3744 callSite.setCallingConv(getRuntimeCC());
3745 return callSite;
3746}
3747
3748/// Emits a call or invoke instruction to the given function, depending
3749/// on the current state of the EH stack.
3750llvm::CallSite
3751CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
3752 ArrayRef<llvm::Value *> Args,
3753 const Twine &Name) {
3754 llvm::BasicBlock *InvokeDest = getInvokeDest();
3755 SmallVector<llvm::OperandBundleDef, 1> BundleList =
3756 getBundlesForFunclet(Callee);
3757
3758 llvm::Instruction *Inst;
3759 if (!InvokeDest)
3760 Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
3761 else {
3762 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
3763 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
3764 Name);
3765 EmitBlock(ContBB);
3766 }
3767
3768 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3769 // optimizer it can aggressively ignore unwind edges.
3770 if (CGM.getLangOpts().ObjCAutoRefCount)
3771 AddObjCARCExceptionMetadata(Inst);
3772
3773 return llvm::CallSite(Inst);
3774}
3775
3776void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
3777 llvm::Value *New) {
3778 DeferredReplacements.push_back(std::make_pair(Old, New));
3779}
3780
3781RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
3782 const CGCallee &Callee,
3783 ReturnValueSlot ReturnValue,
3784 const CallArgList &CallArgs,
3785 llvm::Instruction **callOrInvoke,
3786 SourceLocation Loc) {
3787 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
3788
3789 assert(Callee.isOrdinary() || Callee.isVirtual())(static_cast <bool> (Callee.isOrdinary() || Callee.isVirtual
()) ? void (0) : __assert_fail ("Callee.isOrdinary() || Callee.isVirtual()"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3789, __extension__ __PRETTY_FUNCTION__))
;
3790
3791 // Handle struct-return functions by passing a pointer to the
3792 // location that we would like to return into.
3793 QualType RetTy = CallInfo.getReturnType();
3794 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
3795
3796 llvm::FunctionType *IRFuncTy = Callee.getFunctionType();
3797
3798 // 1. Set up the arguments.
3799
3800 // If we're using inalloca, insert the allocation after the stack save.
3801 // FIXME: Do this earlier rather than hacking it in here!
3802 Address ArgMemory = Address::invalid();
3803 const llvm::StructLayout *ArgMemoryLayout = nullptr;
3804 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
3805 const llvm::DataLayout &DL = CGM.getDataLayout();
3806 ArgMemoryLayout = DL.getStructLayout(ArgStruct);
3807 llvm::Instruction *IP = CallArgs.getStackBase();
3808 llvm::AllocaInst *AI;
3809 if (IP) {
3810 IP = IP->getNextNode();
3811 AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(),
3812 "argmem", IP);
3813 } else {
3814 AI = CreateTempAlloca(ArgStruct, "argmem");
3815 }
3816 auto Align = CallInfo.getArgStructAlignment();
3817 AI->setAlignment(Align.getQuantity());
3818 AI->setUsedWithInAlloca(true);
3819 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca())(static_cast <bool> (AI->isUsedWithInAlloca() &&
!AI->isStaticAlloca()) ? void (0) : __assert_fail ("AI->isUsedWithInAlloca() && !AI->isStaticAlloca()"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3819, __extension__ __PRETTY_FUNCTION__))
;
3820 ArgMemory = Address(AI, Align);
3821 }
3822
3823 // Helper function to drill into the inalloca allocation.
3824 auto createInAllocaStructGEP = [&](unsigned FieldIndex) -> Address {
3825 auto FieldOffset =
3826 CharUnits::fromQuantity(ArgMemoryLayout->getElementOffset(FieldIndex));
3827 return Builder.CreateStructGEP(ArgMemory, FieldIndex, FieldOffset);
3828 };
3829
3830 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
3831 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3832
3833 // If the call returns a temporary with struct return, create a temporary
3834 // alloca to hold the result, unless one is given to us.
3835 Address SRetPtr = Address::invalid();
3836 Address SRetAlloca = Address::invalid();
3837 llvm::Value *UnusedReturnSizePtr = nullptr;
3838 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
3839 if (!ReturnValue.isNull()) {
3840 SRetPtr = ReturnValue.getValue();
3841 } else {
3842 SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca);
3843 if (HaveInsertPoint() && ReturnValue.isUnused()) {
3844 uint64_t size =
3845 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
3846 UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer());
3847 }
3848 }
3849 if (IRFunctionArgs.hasSRetArg()) {
3850 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
3851 } else if (RetAI.isInAlloca()) {
3852 Address Addr = createInAllocaStructGEP(RetAI.getInAllocaFieldIndex());
3853 Builder.CreateStore(SRetPtr.getPointer(), Addr);
3854 }
3855 }
3856
3857 Address swiftErrorTemp = Address::invalid();
3858 Address swiftErrorArg = Address::invalid();
3859
3860 // Translate all of the arguments as necessary to match the IR lowering.
3861 assert(CallInfo.arg_size() == CallArgs.size() &&(static_cast <bool> (CallInfo.arg_size() == CallArgs.size
() && "Mismatch between function signature & arguments."
) ? void (0) : __assert_fail ("CallInfo.arg_size() == CallArgs.size() && \"Mismatch between function signature & arguments.\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3862, __extension__ __PRETTY_FUNCTION__))
3862 "Mismatch between function signature & arguments.")(static_cast <bool> (CallInfo.arg_size() == CallArgs.size
() && "Mismatch between function signature & arguments."
) ? void (0) : __assert_fail ("CallInfo.arg_size() == CallArgs.size() && \"Mismatch between function signature & arguments.\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3862, __extension__ __PRETTY_FUNCTION__))
;
3863 unsigned ArgNo = 0;
3864 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
3865 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
3866 I != E; ++I, ++info_it, ++ArgNo) {
3867 const ABIArgInfo &ArgInfo = info_it->info;
3868
3869 // Insert a padding argument to ensure proper alignment.
3870 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3871 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3872 llvm::UndefValue::get(ArgInfo.getPaddingType());
3873
3874 unsigned FirstIRArg, NumIRArgs;
3875 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
3876
3877 switch (ArgInfo.getKind()) {
3878 case ABIArgInfo::InAlloca: {
3879 assert(NumIRArgs == 0)(static_cast <bool> (NumIRArgs == 0) ? void (0) : __assert_fail
("NumIRArgs == 0", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3879, __extension__ __PRETTY_FUNCTION__))
;
3880 assert(getTarget().getTriple().getArch() == llvm::Triple::x86)(static_cast <bool> (getTarget().getTriple().getArch() ==
llvm::Triple::x86) ? void (0) : __assert_fail ("getTarget().getTriple().getArch() == llvm::Triple::x86"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3880, __extension__ __PRETTY_FUNCTION__))
;
3881 if (I->isAggregate()) {
3882 // Replace the placeholder with the appropriate argument slot GEP.
3883 Address Addr = I->hasLValue()
3884 ? I->getKnownLValue().getAddress()
3885 : I->getKnownRValue().getAggregateAddress();
3886 llvm::Instruction *Placeholder =
3887 cast<llvm::Instruction>(Addr.getPointer());
3888 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3889 Builder.SetInsertPoint(Placeholder);
3890 Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
3891 Builder.restoreIP(IP);
3892 deferPlaceholderReplacement(Placeholder, Addr.getPointer());
3893 } else {
3894 // Store the RValue into the argument struct.
3895 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
3896 unsigned AS = Addr.getType()->getPointerAddressSpace();
3897 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3898 // There are some cases where a trivial bitcast is not avoidable. The
3899 // definition of a type later in a translation unit may change it's type
3900 // from {}* to (%struct.foo*)*.
3901 if (Addr.getType() != MemType)
3902 Addr = Builder.CreateBitCast(Addr, MemType);
3903 I->copyInto(*this, Addr);
3904 }
3905 break;
3906 }
3907
3908 case ABIArgInfo::Indirect: {
3909 assert(NumIRArgs == 1)(static_cast <bool> (NumIRArgs == 1) ? void (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3909, __extension__ __PRETTY_FUNCTION__))
;
3910 if (!I->isAggregate()) {
3911 // Make a temporary alloca to pass the argument.
3912 Address Addr = CreateMemTempWithoutCast(
3913 I->Ty, ArgInfo.getIndirectAlign(), "indirect-arg-temp");
3914 IRCallArgs[FirstIRArg] = Addr.getPointer();
3915
3916 I->copyInto(*this, Addr);
3917 } else {
3918 // We want to avoid creating an unnecessary temporary+copy here;
3919 // however, we need one in three cases:
3920 // 1. If the argument is not byval, and we are required to copy the
3921 // source. (This case doesn't occur on any common architecture.)
3922 // 2. If the argument is byval, RV is not sufficiently aligned, and
3923 // we cannot force it to be sufficiently aligned.
3924 // 3. If the argument is byval, but RV is not located in default
3925 // or alloca address space.
3926 Address Addr = I->hasLValue()
3927 ? I->getKnownLValue().getAddress()
3928 : I->getKnownRValue().getAggregateAddress();
3929 llvm::Value *V = Addr.getPointer();
3930 CharUnits Align = ArgInfo.getIndirectAlign();
3931 const llvm::DataLayout *TD = &CGM.getDataLayout();
3932
3933 assert((FirstIRArg >= IRFuncTy->getNumParams() ||(static_cast <bool> ((FirstIRArg >= IRFuncTy->getNumParams
() || IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace
() == TD->getAllocaAddrSpace()) && "indirect argument must be in alloca address space"
) ? void (0) : __assert_fail ("(FirstIRArg >= IRFuncTy->getNumParams() || IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() == TD->getAllocaAddrSpace()) && \"indirect argument must be in alloca address space\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3936, __extension__ __PRETTY_FUNCTION__))
3934 IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() ==(static_cast <bool> ((FirstIRArg >= IRFuncTy->getNumParams
() || IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace
() == TD->getAllocaAddrSpace()) && "indirect argument must be in alloca address space"
) ? void (0) : __assert_fail ("(FirstIRArg >= IRFuncTy->getNumParams() || IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() == TD->getAllocaAddrSpace()) && \"indirect argument must be in alloca address space\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3936, __extension__ __PRETTY_FUNCTION__))
3935 TD->getAllocaAddrSpace()) &&(static_cast <bool> ((FirstIRArg >= IRFuncTy->getNumParams
() || IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace
() == TD->getAllocaAddrSpace()) && "indirect argument must be in alloca address space"
) ? void (0) : __assert_fail ("(FirstIRArg >= IRFuncTy->getNumParams() || IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() == TD->getAllocaAddrSpace()) && \"indirect argument must be in alloca address space\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3936, __extension__ __PRETTY_FUNCTION__))
3936 "indirect argument must be in alloca address space")(static_cast <bool> ((FirstIRArg >= IRFuncTy->getNumParams
() || IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace
() == TD->getAllocaAddrSpace()) && "indirect argument must be in alloca address space"
) ? void (0) : __assert_fail ("(FirstIRArg >= IRFuncTy->getNumParams() || IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() == TD->getAllocaAddrSpace()) && \"indirect argument must be in alloca address space\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3936, __extension__ __PRETTY_FUNCTION__))
;
3937
3938 bool NeedCopy = false;
3939
3940 if (Addr.getAlignment() < Align &&
3941 llvm::getOrEnforceKnownAlignment(V, Align.getQuantity(), *TD) <
3942 Align.getQuantity()) {
3943 NeedCopy = true;
3944 } else if (I->hasLValue()) {
3945 auto LV = I->getKnownLValue();
3946 auto AS = LV.getAddressSpace();
3947 if ((!ArgInfo.getIndirectByVal() &&
3948 (LV.getAlignment() >=
3949 getContext().getTypeAlignInChars(I->Ty))) ||
3950 (ArgInfo.getIndirectByVal() &&
3951 ((AS != LangAS::Default && AS != LangAS::opencl_private &&
3952 AS != CGM.getASTAllocaAddressSpace())))) {
3953 NeedCopy = true;
3954 }
3955 }
3956 if (NeedCopy) {
3957 // Create an aligned temporary, and copy to it.
3958 Address AI = CreateMemTempWithoutCast(
3959 I->Ty, ArgInfo.getIndirectAlign(), "byval-temp");
3960 IRCallArgs[FirstIRArg] = AI.getPointer();
3961 I->copyInto(*this, AI);
3962 } else {
3963 // Skip the extra memcpy call.
3964 auto *T = V->getType()->getPointerElementType()->getPointerTo(
3965 CGM.getDataLayout().getAllocaAddrSpace());
3966 IRCallArgs[FirstIRArg] = getTargetHooks().performAddrSpaceCast(
3967 *this, V, LangAS::Default, CGM.getASTAllocaAddressSpace(), T,
3968 true);
3969 }
3970 }
3971 break;
3972 }
3973
3974 case ABIArgInfo::Ignore:
3975 assert(NumIRArgs == 0)(static_cast <bool> (NumIRArgs == 0) ? void (0) : __assert_fail
("NumIRArgs == 0", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3975, __extension__ __PRETTY_FUNCTION__))
;
3976 break;
3977
3978 case ABIArgInfo::Extend:
3979 case ABIArgInfo::Direct: {
3980 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
3981 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3982 ArgInfo.getDirectOffset() == 0) {
3983 assert(NumIRArgs == 1)(static_cast <bool> (NumIRArgs == 1) ? void (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3983, __extension__ __PRETTY_FUNCTION__))
;
3984 llvm::Value *V;
3985 if (!I->isAggregate())
3986 V = I->getKnownRValue().getScalarVal();
3987 else
3988 V = Builder.CreateLoad(
3989 I->hasLValue() ? I->getKnownLValue().getAddress()
3990 : I->getKnownRValue().getAggregateAddress());
3991
3992 // Implement swifterror by copying into a new swifterror argument.
3993 // We'll write back in the normal path out of the call.
3994 if (CallInfo.getExtParameterInfo(ArgNo).getABI()
3995 == ParameterABI::SwiftErrorResult) {
3996 assert(!swiftErrorTemp.isValid() && "multiple swifterror args")(static_cast <bool> (!swiftErrorTemp.isValid() &&
"multiple swifterror args") ? void (0) : __assert_fail ("!swiftErrorTemp.isValid() && \"multiple swifterror args\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 3996, __extension__ __PRETTY_FUNCTION__))
;
3997
3998 QualType pointeeTy = I->Ty->getPointeeType();
3999 swiftErrorArg =
4000 Address(V, getContext().getTypeAlignInChars(pointeeTy));
4001
4002 swiftErrorTemp =
4003 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
4004 V = swiftErrorTemp.getPointer();
4005 cast<llvm::AllocaInst>(V)->setSwiftError(true);
4006
4007 llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
4008 Builder.CreateStore(errorValue, swiftErrorTemp);
4009 }
4010
4011 // We might have to widen integers, but we should never truncate.
4012 if (ArgInfo.getCoerceToType() != V->getType() &&
4013 V->getType()->isIntegerTy())
4014 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
4015
4016 // If the argument doesn't match, perform a bitcast to coerce it. This
4017 // can happen due to trivial type mismatches.
4018 if (FirstIRArg < IRFuncTy->getNumParams() &&
4019 V->getType() != IRFuncTy->getParamType(FirstIRArg))
4020 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
4021
4022 IRCallArgs[FirstIRArg] = V;
4023 break;
4024 }
4025
4026 // FIXME: Avoid the conversion through memory if possible.
4027 Address Src = Address::invalid();
4028 if (!I->isAggregate()) {
4029 Src = CreateMemTemp(I->Ty, "coerce");
4030 I->copyInto(*this, Src);
4031 } else {
4032 Src = I->hasLValue() ? I->getKnownLValue().getAddress()
4033 : I->getKnownRValue().getAggregateAddress();
4034 }
4035
4036 // If the value is offset in memory, apply the offset now.
4037 Src = emitAddressAtOffset(*this, Src, ArgInfo);
4038
4039 // Fast-isel and the optimizer generally like scalar values better than
4040 // FCAs, so we flatten them if this is safe to do for this argument.
4041 llvm::StructType *STy =
4042 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
4043 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
4044 llvm::Type *SrcTy = Src.getType()->getElementType();
4045 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
4046 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
4047
4048 // If the source type is smaller than the destination type of the
4049 // coerce-to logic, copy the source value into a temp alloca the size
4050 // of the destination type to allow loading all of it. The bits past
4051 // the source value are left undef.
4052 if (SrcSize < DstSize) {
4053 Address TempAlloca
4054 = CreateTempAlloca(STy, Src.getAlignment(),
4055 Src.getName() + ".coerce");
4056 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
4057 Src = TempAlloca;
4058 } else {
4059 Src = Builder.CreateBitCast(Src,
4060 STy->getPointerTo(Src.getAddressSpace()));
4061 }
4062
4063 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
4064 assert(NumIRArgs == STy->getNumElements())(static_cast <bool> (NumIRArgs == STy->getNumElements
()) ? void (0) : __assert_fail ("NumIRArgs == STy->getNumElements()"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 4064, __extension__ __PRETTY_FUNCTION__))
;
4065 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
4066 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
4067 Address EltPtr = Builder.CreateStructGEP(Src, i, Offset);
4068 llvm::Value *LI = Builder.CreateLoad(EltPtr);
4069 IRCallArgs[FirstIRArg + i] = LI;
4070 }
4071 } else {
4072 // In the simple case, just pass the coerced loaded value.
4073 assert(NumIRArgs == 1)(static_cast <bool> (NumIRArgs == 1) ? void (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 4073, __extension__ __PRETTY_FUNCTION__))
;
4074 IRCallArgs[FirstIRArg] =
4075 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
4076 }
4077
4078 break;
4079 }
4080
4081 case ABIArgInfo::CoerceAndExpand: {
4082 auto coercionType = ArgInfo.getCoerceAndExpandType();
4083 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
4084
4085 llvm::Value *tempSize = nullptr;
4086 Address addr = Address::invalid();
4087 Address AllocaAddr = Address::invalid();
4088 if (I->isAggregate()) {
4089 addr = I->hasLValue() ? I->getKnownLValue().getAddress()
4090 : I->getKnownRValue().getAggregateAddress();
4091
4092 } else {
4093 RValue RV = I->getKnownRValue();
4094 assert(RV.isScalar())(static_cast <bool> (RV.isScalar()) ? void (0) : __assert_fail
("RV.isScalar()", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 4094, __extension__ __PRETTY_FUNCTION__))
; // complex should always just be direct
4095
4096 llvm::Type *scalarType = RV.getScalarVal()->getType();
4097 auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
4098 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType);
4099
4100 // Materialize to a temporary.
4101 addr = CreateTempAlloca(RV.getScalarVal()->getType(),
4102 CharUnits::fromQuantity(std::max(
4103 layout->getAlignment(), scalarAlign)),
4104 "tmp",
4105 /*ArraySize=*/nullptr, &AllocaAddr);
4106 tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer());
4107
4108 Builder.CreateStore(RV.getScalarVal(), addr);
4109 }
4110
4111 addr = Builder.CreateElementBitCast(addr, coercionType);
4112
4113 unsigned IRArgPos = FirstIRArg;
4114 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
4115 llvm::Type *eltType = coercionType->getElementType(i);
4116 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
4117 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
4118 llvm::Value *elt = Builder.CreateLoad(eltAddr);
4119 IRCallArgs[IRArgPos++] = elt;
4120 }
4121 assert(IRArgPos == FirstIRArg + NumIRArgs)(static_cast <bool> (IRArgPos == FirstIRArg + NumIRArgs
) ? void (0) : __assert_fail ("IRArgPos == FirstIRArg + NumIRArgs"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 4121, __extension__ __PRETTY_FUNCTION__))
;
4122
4123 if (tempSize) {
4124 EmitLifetimeEnd(tempSize, AllocaAddr.getPointer());
4125 }
4126
4127 break;
4128 }
4129
4130 case ABIArgInfo::Expand:
4131 unsigned IRArgPos = FirstIRArg;
4132 ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos);
4133 assert(IRArgPos == FirstIRArg + NumIRArgs)(static_cast <bool> (IRArgPos == FirstIRArg + NumIRArgs
) ? void (0) : __assert_fail ("IRArgPos == FirstIRArg + NumIRArgs"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 4133, __extension__ __PRETTY_FUNCTION__))
;
4134 break;
4135 }
4136 }
4137
4138 const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this);
4139 llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer();
4140
4141 // If we're using inalloca, set up that argument.
4142 if (ArgMemory.isValid()) {
4143 llvm::Value *Arg = ArgMemory.getPointer();
4144 if (CallInfo.isVariadic()) {
4145 // When passing non-POD arguments by value to variadic functions, we will
4146 // end up with a variadic prototype and an inalloca call site. In such
4147 // cases, we can't do any parameter mismatch checks. Give up and bitcast
4148 // the callee.
4149 unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace();
4150 auto FnTy = getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS);
4151 CalleePtr = Builder.CreateBitCast(CalleePtr, FnTy);
4152 } else {
4153 llvm::Type *LastParamTy =
4154 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
4155 if (Arg->getType() != LastParamTy) {
4156#ifndef NDEBUG
4157 // Assert that these structs have equivalent element types.
4158 llvm::StructType *FullTy = CallInfo.getArgStruct();
4159 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
4160 cast<llvm::PointerType>(LastParamTy)->getElementType());
4161 assert(DeclaredTy->getNumElements() == FullTy->getNumElements())(static_cast <bool> (DeclaredTy->getNumElements() ==
FullTy->getNumElements()) ? void (0) : __assert_fail ("DeclaredTy->getNumElements() == FullTy->getNumElements()"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 4161, __extension__ __PRETTY_FUNCTION__))
;
4162 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
4163 DE = DeclaredTy->element_end(),
4164 FI = FullTy->element_begin();
4165 DI != DE; ++DI, ++FI)
4166 assert(*DI == *FI)(static_cast <bool> (*DI == *FI) ? void (0) : __assert_fail
("*DI == *FI", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 4166, __extension__ __PRETTY_FUNCTION__))
;
4167#endif
4168 Arg = Builder.CreateBitCast(Arg, LastParamTy);
4169 }
4170 }
4171 assert(IRFunctionArgs.hasInallocaArg())(static_cast <bool> (IRFunctionArgs.hasInallocaArg()) ?
void (0) : __assert_fail ("IRFunctionArgs.hasInallocaArg()",
"/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 4171, __extension__ __PRETTY_FUNCTION__))
;
4172 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
4173 }
4174
4175 // 2. Prepare the function pointer.
4176
4177 // If the callee is a bitcast of a non-variadic function to have a
4178 // variadic function pointer type, check to see if we can remove the
4179 // bitcast. This comes up with unprototyped functions.
4180 //
4181 // This makes the IR nicer, but more importantly it ensures that we
4182 // can inline the function at -O0 if it is marked always_inline.
4183 auto simplifyVariadicCallee = [](llvm::Value *Ptr) -> llvm::Value* {
4184 llvm::FunctionType *CalleeFT =
4185 cast<llvm::FunctionType>(Ptr->getType()->getPointerElementType());
4186 if (!CalleeFT->isVarArg())
4187 return Ptr;
4188
4189 llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr);
4190 if (!CE || CE->getOpcode() != llvm::Instruction::BitCast)
4191 return Ptr;
4192
4193 llvm::Function *OrigFn = dyn_cast<llvm::Function>(CE->getOperand(0));
4194 if (!OrigFn)
4195 return Ptr;
4196
4197 llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
4198
4199 // If the original type is variadic, or if any of the component types
4200 // disagree, we cannot remove the cast.
4201 if (OrigFT->isVarArg() ||
4202 OrigFT->getNumParams() != CalleeFT->getNumParams() ||
4203 OrigFT->getReturnType() != CalleeFT->getReturnType())
4204 return Ptr;
4205
4206 for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
4207 if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
4208 return Ptr;
4209
4210 return OrigFn;
4211 };
4212 CalleePtr = simplifyVariadicCallee(CalleePtr);
4213
4214 // 3. Perform the actual call.
4215
4216 // Deactivate any cleanups that we're supposed to do immediately before
4217 // the call.
4218 if (!CallArgs.getCleanupsToDeactivate().empty())
4219 deactivateArgCleanupsBeforeCall(*this, CallArgs);
4220
4221 // Assert that the arguments we computed match up. The IR verifier
4222 // will catch this, but this is a common enough source of problems
4223 // during IRGen changes that it's way better for debugging to catch
4224 // it ourselves here.
4225#ifndef NDEBUG
4226 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg())(static_cast <bool> (IRCallArgs.size() == IRFuncTy->
getNumParams() || IRFuncTy->isVarArg()) ? void (0) : __assert_fail
("IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg()"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 4226, __extension__ __PRETTY_FUNCTION__))
;
4227 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
4228 // Inalloca argument can have different type.
4229 if (IRFunctionArgs.hasInallocaArg() &&
4230 i == IRFunctionArgs.getInallocaArgNo())
4231 continue;
4232 if (i < IRFuncTy->getNumParams())
4233 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i))(static_cast <bool> (IRCallArgs[i]->getType() == IRFuncTy
->getParamType(i)) ? void (0) : __assert_fail ("IRCallArgs[i]->getType() == IRFuncTy->getParamType(i)"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 4233, __extension__ __PRETTY_FUNCTION__))
;
4234 }
4235#endif
4236
4237 // Compute the calling convention and attributes.
4238 unsigned CallingConv;
4239 llvm::AttributeList Attrs;
4240 CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
4241 Callee.getAbstractInfo(), Attrs, CallingConv,
4242 /*AttrOnCallSite=*/true);
4243
4244 // Apply some call-site-specific attributes.
4245 // TODO: work this into building the attribute set.
4246
4247 // Apply always_inline to all calls within flatten functions.
4248 // FIXME: should this really take priority over __try, below?
4249 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
4250 !(Callee.getAbstractInfo().getCalleeDecl() &&
4251 Callee.getAbstractInfo().getCalleeDecl()->hasAttr<NoInlineAttr>())) {
4252 Attrs =
4253 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
4254 llvm::Attribute::AlwaysInline);
4255 }
4256
4257 // Disable inlining inside SEH __try blocks.
4258 if (isSEHTryScope()) {
4259 Attrs =
4260 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
4261 llvm::Attribute::NoInline);
4262 }
4263
4264 // Decide whether to use a call or an invoke.
4265 bool CannotThrow;
4266 if (currentFunctionUsesSEHTry()) {
4267 // SEH cares about asynchronous exceptions, so everything can "throw."
4268 CannotThrow = false;
4269 } else if (isCleanupPadScope() &&
4270 EHPersonality::get(*this).isMSVCXXPersonality()) {
4271 // The MSVC++ personality will implicitly terminate the program if an
4272 // exception is thrown during a cleanup outside of a try/catch.
4273 // We don't need to model anything in IR to get this behavior.
4274 CannotThrow = true;
4275 } else {
4276 // Otherwise, nounwind call sites will never throw.
4277 CannotThrow = Attrs.hasAttribute(llvm::AttributeList::FunctionIndex,
4278 llvm::Attribute::NoUnwind);
4279 }
4280
4281 // If we made a temporary, be sure to clean up after ourselves. Note that we
4282 // can't depend on being inside of an ExprWithCleanups, so we need to manually
4283 // pop this cleanup later on. Being eager about this is OK, since this
4284 // temporary is 'invisible' outside of the callee.
4285 if (UnusedReturnSizePtr)
4286 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca,
4287 UnusedReturnSizePtr);
4288
4289 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
4290
4291 SmallVector<llvm::OperandBundleDef, 1> BundleList =
4292 getBundlesForFunclet(CalleePtr);
4293
4294 // Emit the actual call/invoke instruction.
4295 llvm::CallSite CS;
4296 if (!InvokeDest) {
4297 CS = Builder.CreateCall(CalleePtr, IRCallArgs, BundleList);
4298 } else {
4299 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
4300 CS = Builder.CreateInvoke(CalleePtr, Cont, InvokeDest, IRCallArgs,
4301 BundleList);
4302 EmitBlock(Cont);
4303 }
4304 llvm::Instruction *CI = CS.getInstruction();
4305 if (callOrInvoke)
4306 *callOrInvoke = CI;
4307
4308 // Apply the attributes and calling convention.
4309 CS.setAttributes(Attrs);
4310 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
4311
4312 // Apply various metadata.
4313
4314 if (!CI->getType()->isVoidTy())
4315 CI->setName("call");
4316
4317 // Insert instrumentation or attach profile metadata at indirect call sites.
4318 // For more details, see the comment before the definition of
4319 // IPVK_IndirectCallTarget in InstrProfData.inc.
4320 if (!CS.getCalledFunction())
4321 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
4322 CI, CalleePtr);
4323
4324 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4325 // optimizer it can aggressively ignore unwind edges.
4326 if (CGM.getLangOpts().ObjCAutoRefCount)
4327 AddObjCARCExceptionMetadata(CI);
4328
4329 // Suppress tail calls if requested.
4330 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
4331 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl();
4332 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
4333 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
4334 }
4335
4336 // 4. Finish the call.
4337
4338 // If the call doesn't return, finish the basic block and clear the
4339 // insertion point; this allows the rest of IRGen to discard
4340 // unreachable code.
4341 if (CS.doesNotReturn()) {
4342 if (UnusedReturnSizePtr)
4343 PopCleanupBlock();
4344
4345 // Strip away the noreturn attribute to better diagnose unreachable UB.
4346 if (SanOpts.has(SanitizerKind::Unreachable)) {
4347 if (auto *F = CS.getCalledFunction())
4348 F->removeFnAttr(llvm::Attribute::NoReturn);
4349 CS.removeAttribute(llvm::AttributeList::FunctionIndex,
4350 llvm::Attribute::NoReturn);
4351 }
4352
4353 EmitUnreachable(Loc);
4354 Builder.ClearInsertionPoint();
4355
4356 // FIXME: For now, emit a dummy basic block because expr emitters in
4357 // generally are not ready to handle emitting expressions at unreachable
4358 // points.
4359 EnsureInsertPoint();
4360
4361 // Return a reasonable RValue.
4362 return GetUndefRValue(RetTy);
4363 }
4364
4365 // Perform the swifterror writeback.
4366 if (swiftErrorTemp.isValid()) {
4367 llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
4368 Builder.CreateStore(errorResult, swiftErrorArg);
4369 }
4370
4371 // Emit any call-associated writebacks immediately. Arguably this
4372 // should happen after any return-value munging.
4373 if (CallArgs.hasWritebacks())
4374 emitWritebacks(*this, CallArgs);
4375
4376 // The stack cleanup for inalloca arguments has to run out of the normal
4377 // lexical order, so deactivate it and run it manually here.
4378 CallArgs.freeArgumentMemory(*this);
4379
4380 // Extract the return value.
4381 RValue Ret = [&] {
4382 switch (RetAI.getKind()) {
4383 case ABIArgInfo::CoerceAndExpand: {
4384 auto coercionType = RetAI.getCoerceAndExpandType();
4385 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
4386
4387 Address addr = SRetPtr;
4388 addr = Builder.CreateElementBitCast(addr, coercionType);
4389
4390 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType())(static_cast <bool> (CI->getType() == RetAI.getUnpaddedCoerceAndExpandType
()) ? void (0) : __assert_fail ("CI->getType() == RetAI.getUnpaddedCoerceAndExpandType()"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 4390, __extension__ __PRETTY_FUNCTION__))
;
4391 bool requiresExtract = isa<llvm::StructType>(CI->getType());
4392
4393 unsigned unpaddedIndex = 0;
4394 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
4395 llvm::Type *eltType = coercionType->getElementType(i);
4396 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
4397 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
4398 llvm::Value *elt = CI;
4399 if (requiresExtract)
4400 elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
4401 else
4402 assert(unpaddedIndex == 0)(static_cast <bool> (unpaddedIndex == 0) ? void (0) : __assert_fail
("unpaddedIndex == 0", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 4402, __extension__ __PRETTY_FUNCTION__))
;
4403 Builder.CreateStore(elt, eltAddr);
4404 }
4405 // FALLTHROUGH
4406 LLVM_FALLTHROUGH[[clang::fallthrough]];
4407 }
4408
4409 case ABIArgInfo::InAlloca:
4410 case ABIArgInfo::Indirect: {
4411 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
4412 if (UnusedReturnSizePtr)
4413 PopCleanupBlock();
4414 return ret;
4415 }
4416
4417 case ABIArgInfo::Ignore:
4418 // If we are ignoring an argument that had a result, make sure to
4419 // construct the appropriate return value for our caller.
4420 return GetUndefRValue(RetTy);
4421
4422 case ABIArgInfo::Extend:
4423 case ABIArgInfo::Direct: {
4424 llvm::Type *RetIRTy = ConvertType(RetTy);
4425 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
4426 switch (getEvaluationKind(RetTy)) {
4427 case TEK_Complex: {
4428 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
4429 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
4430 return RValue::getComplex(std::make_pair(Real, Imag));
4431 }
4432 case TEK_Aggregate: {
4433 Address DestPtr = ReturnValue.getValue();
4434 bool DestIsVolatile = ReturnValue.isVolatile();
4435
4436 if (!DestPtr.isValid()) {
4437 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
4438 DestIsVolatile = false;
4439 }
4440 BuildAggStore(*this, CI, DestPtr, DestIsVolatile);
4441 return RValue::getAggregate(DestPtr);
4442 }
4443 case TEK_Scalar: {
4444 // If the argument doesn't match, perform a bitcast to coerce it. This
4445 // can happen due to trivial type mismatches.
4446 llvm::Value *V = CI;
4447 if (V->getType() != RetIRTy)
4448 V = Builder.CreateBitCast(V, RetIRTy);
4449 return RValue::get(V);
4450 }
4451 }
4452 llvm_unreachable("bad evaluation kind")::llvm::llvm_unreachable_internal("bad evaluation kind", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 4452)
;
4453 }
4454
4455 Address DestPtr = ReturnValue.getValue();
4456 bool DestIsVolatile = ReturnValue.isVolatile();
4457
4458 if (!DestPtr.isValid()) {
4459 DestPtr = CreateMemTemp(RetTy, "coerce");
4460 DestIsVolatile = false;
4461 }
4462
4463 // If the value is offset in memory, apply the offset now.
4464 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
4465 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
4466
4467 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
4468 }
4469
4470 case ABIArgInfo::Expand:
4471 llvm_unreachable("Invalid ABI kind for return argument")::llvm::llvm_unreachable_internal("Invalid ABI kind for return argument"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 4471)
;
4472 }
4473
4474 llvm_unreachable("Unhandled ABIArgInfo::Kind")::llvm::llvm_unreachable_internal("Unhandled ABIArgInfo::Kind"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/CodeGen/CGCall.cpp"
, 4474)
;
4475 } ();
4476
4477 // Emit the assume_aligned check on the return value.
4478 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl();
4479 if (Ret.isScalar() && TargetDecl) {
4480 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
4481 llvm::Value *OffsetValue = nullptr;
4482 if (const auto *Offset = AA->getOffset())
4483 OffsetValue = EmitScalarExpr(Offset);
4484
4485 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
4486 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
4487 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
4488 OffsetValue);
4489 } else if (const auto *AA = TargetDecl->getAttr<AllocAlignAttr>()) {
4490 llvm::Value *ParamVal =
4491 CallArgs[AA->getParamIndex().getLLVMIndex()].getRValue(
4492 *this).getScalarVal();
4493 EmitAlignmentAssumption(Ret.getScalarVal(), ParamVal);
4494 }
4495 }
4496
4497 return Ret;
4498}
4499
4500CGCallee CGCallee::prepareConcreteCallee(CodeGenFunction &CGF) const {
4501 if (isVirtual()) {
4502 const CallExpr *CE = getVirtualCallExpr();
4503 return CGF.CGM.getCXXABI().getVirtualFunctionPointer(
4504 CGF, getVirtualMethodDecl(), getThisAddress(),
4505 getFunctionType(), CE ? CE->getLocStart() : SourceLocation());
4506 }
4507
4508 return *this;
4509}
4510
4511/* VarArg handling */
4512
4513Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
4514 VAListAddr = VE->isMicrosoftABI()
4515 ? EmitMSVAListRef(VE->getSubExpr())
4516 : EmitVAListRef(VE->getSubExpr());
4517 QualType Ty = VE->getType();
4518 if (VE->isMicrosoftABI())
4519 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
4520 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
4521}