clang 19.0.0git
CGCall.cpp
Go to the documentation of this file.
1//===--- CGCall.cpp - Encapsulate calling convention details --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// These classes wrap the information about a call or function
10// definition used to handle ABI compliancy.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGCall.h"
15#include "ABIInfo.h"
16#include "ABIInfoImpl.h"
17#include "CGBlocks.h"
18#include "CGCXXABI.h"
19#include "CGCleanup.h"
20#include "CGRecordLayout.h"
21#include "CodeGenFunction.h"
22#include "CodeGenModule.h"
23#include "TargetInfo.h"
24#include "clang/AST/Attr.h"
25#include "clang/AST/Decl.h"
26#include "clang/AST/DeclCXX.h"
27#include "clang/AST/DeclObjC.h"
32#include "llvm/ADT/StringExtras.h"
33#include "llvm/Analysis/ValueTracking.h"
34#include "llvm/IR/Assumptions.h"
35#include "llvm/IR/AttributeMask.h"
36#include "llvm/IR/Attributes.h"
37#include "llvm/IR/CallingConv.h"
38#include "llvm/IR/DataLayout.h"
39#include "llvm/IR/InlineAsm.h"
40#include "llvm/IR/IntrinsicInst.h"
41#include "llvm/IR/Intrinsics.h"
42#include "llvm/IR/Type.h"
43#include "llvm/Transforms/Utils/Local.h"
44#include <optional>
45using namespace clang;
46using namespace CodeGen;
47
48/***/
49
51 switch (CC) {
52 default: return llvm::CallingConv::C;
53 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
54 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
55 case CC_X86RegCall: return llvm::CallingConv::X86_RegCall;
56 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
57 case CC_Win64: return llvm::CallingConv::Win64;
58 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
59 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
60 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
61 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
62 // TODO: Add support for __pascal to LLVM.
63 case CC_X86Pascal: return llvm::CallingConv::C;
64 // TODO: Add support for __vectorcall to LLVM.
65 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
66 case CC_AArch64VectorCall: return llvm::CallingConv::AArch64_VectorCall;
67 case CC_AArch64SVEPCS: return llvm::CallingConv::AArch64_SVE_VectorCall;
68 case CC_AMDGPUKernelCall: return llvm::CallingConv::AMDGPU_KERNEL;
69 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
71 case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
72 case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
73 case CC_Swift: return llvm::CallingConv::Swift;
74 case CC_SwiftAsync: return llvm::CallingConv::SwiftTail;
75 case CC_M68kRTD: return llvm::CallingConv::M68k_RTD;
76 case CC_PreserveNone: return llvm::CallingConv::PreserveNone;
77 // clang-format off
78 case CC_RISCVVectorCall: return llvm::CallingConv::RISCV_VectorCall;
79 // clang-format on
80 }
81}
82
83/// Derives the 'this' type for codegen purposes, i.e. ignoring method CVR
84/// qualification. Either or both of RD and MD may be null. A null RD indicates
85/// that there is no meaningful 'this' type, and a null MD can occur when
86/// calling a method pointer.
88 const CXXMethodDecl *MD) {
89 QualType RecTy;
90 if (RD)
91 RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
92 else
93 RecTy = Context.VoidTy;
94
95 if (MD)
96 RecTy = Context.getAddrSpaceQualType(RecTy, MD->getMethodQualifiers().getAddressSpace());
97 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
98}
99
100/// Returns the canonical formal type of the given C++ method.
104}
105
106/// Returns the "extra-canonicalized" return type, which discards
107/// qualifiers on the return type. Codegen doesn't care about them,
108/// and it makes ABI code a little easier to be able to assume that
109/// all parameter and return types are top-level unqualified.
112}
113
114/// Arrange the argument and result information for a value of the given
115/// unprototyped freestanding function type.
116const CGFunctionInfo &
118 // When translating an unprototyped function type, always use a
119 // variadic type.
120 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
121 FnInfoOpts::None, std::nullopt,
122 FTNP->getExtInfo(), {}, RequiredArgs(0));
123}
124
127 const FunctionProtoType *proto,
128 unsigned prefixArgs,
129 unsigned totalArgs) {
130 assert(proto->hasExtParameterInfos());
131 assert(paramInfos.size() <= prefixArgs);
132 assert(proto->getNumParams() + prefixArgs <= totalArgs);
133
134 paramInfos.reserve(totalArgs);
135
136 // Add default infos for any prefix args that don't already have infos.
137 paramInfos.resize(prefixArgs);
138
139 // Add infos for the prototype.
140 for (const auto &ParamInfo : proto->getExtParameterInfos()) {
141 paramInfos.push_back(ParamInfo);
142 // pass_object_size params have no parameter info.
143 if (ParamInfo.hasPassObjectSize())
144 paramInfos.emplace_back();
145 }
146
147 assert(paramInfos.size() <= totalArgs &&
148 "Did we forget to insert pass_object_size args?");
149 // Add default infos for the variadic and/or suffix arguments.
150 paramInfos.resize(totalArgs);
151}
152
153/// Adds the formal parameters in FPT to the given prefix. If any parameter in
154/// FPT has pass_object_size attrs, then we'll add parameters for those, too.
155static void appendParameterTypes(const CodeGenTypes &CGT,
159 // Fast path: don't touch param info if we don't need to.
160 if (!FPT->hasExtParameterInfos()) {
161 assert(paramInfos.empty() &&
162 "We have paramInfos, but the prototype doesn't?");
163 prefix.append(FPT->param_type_begin(), FPT->param_type_end());
164 return;
165 }
166
167 unsigned PrefixSize = prefix.size();
168 // In the vast majority of cases, we'll have precisely FPT->getNumParams()
169 // parameters; the only thing that can change this is the presence of
170 // pass_object_size. So, we preallocate for the common case.
171 prefix.reserve(prefix.size() + FPT->getNumParams());
172
173 auto ExtInfos = FPT->getExtParameterInfos();
174 assert(ExtInfos.size() == FPT->getNumParams());
175 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
176 prefix.push_back(FPT->getParamType(I));
177 if (ExtInfos[I].hasPassObjectSize())
178 prefix.push_back(CGT.getContext().getSizeType());
179 }
180
181 addExtParameterInfosForCall(paramInfos, FPT.getTypePtr(), PrefixSize,
182 prefix.size());
183}
184
185/// Arrange the LLVM function layout for a value of the given function
186/// type, on top of any implicit parameters already stored.
187static const CGFunctionInfo &
188arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
193 // FIXME: Kill copy.
194 appendParameterTypes(CGT, prefix, paramInfos, FTP);
195 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
196
197 FnInfoOpts opts =
199 return CGT.arrangeLLVMFunctionInfo(resultType, opts, prefix,
200 FTP->getExtInfo(), paramInfos, Required);
201}
202
203/// Arrange the argument and result information for a value of the
204/// given freestanding function type.
205const CGFunctionInfo &
208 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
209 FTP);
210}
211
213 bool IsWindows) {
214 // Set the appropriate calling convention for the Function.
215 if (D->hasAttr<StdCallAttr>())
216 return CC_X86StdCall;
217
218 if (D->hasAttr<FastCallAttr>())
219 return CC_X86FastCall;
220
221 if (D->hasAttr<RegCallAttr>())
222 return CC_X86RegCall;
223
224 if (D->hasAttr<ThisCallAttr>())
225 return CC_X86ThisCall;
226
227 if (D->hasAttr<VectorCallAttr>())
228 return CC_X86VectorCall;
229
230 if (D->hasAttr<PascalAttr>())
231 return CC_X86Pascal;
232
233 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
234 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
235
236 if (D->hasAttr<AArch64VectorPcsAttr>())
238
239 if (D->hasAttr<AArch64SVEPcsAttr>())
240 return CC_AArch64SVEPCS;
241
242 if (D->hasAttr<AMDGPUKernelCallAttr>())
243 return CC_AMDGPUKernelCall;
244
245 if (D->hasAttr<IntelOclBiccAttr>())
246 return CC_IntelOclBicc;
247
248 if (D->hasAttr<MSABIAttr>())
249 return IsWindows ? CC_C : CC_Win64;
250
251 if (D->hasAttr<SysVABIAttr>())
252 return IsWindows ? CC_X86_64SysV : CC_C;
253
254 if (D->hasAttr<PreserveMostAttr>())
255 return CC_PreserveMost;
256
257 if (D->hasAttr<PreserveAllAttr>())
258 return CC_PreserveAll;
259
260 if (D->hasAttr<M68kRTDAttr>())
261 return CC_M68kRTD;
262
263 if (D->hasAttr<PreserveNoneAttr>())
264 return CC_PreserveNone;
265
266 if (D->hasAttr<RISCVVectorCCAttr>())
267 return CC_RISCVVectorCall;
268
269 return CC_C;
270}
271
272/// Arrange the argument and result information for a call to an
273/// unknown C++ non-static member function of the given abstract type.
274/// (A null RD means we don't have any meaningful "this" argument type,
275/// so fall back to a generic pointer type).
276/// The member function must be an ordinary function, i.e. not a
277/// constructor or destructor.
278const CGFunctionInfo &
280 const FunctionProtoType *FTP,
281 const CXXMethodDecl *MD) {
283
284 // Add the 'this' pointer.
285 argTypes.push_back(DeriveThisType(RD, MD));
286
287 return ::arrangeLLVMFunctionInfo(
288 *this, /*instanceMethod=*/true, argTypes,
290}
291
292/// Set calling convention for CUDA/HIP kernel.
294 const FunctionDecl *FD) {
295 if (FD->hasAttr<CUDAGlobalAttr>()) {
296 const FunctionType *FT = FTy->getAs<FunctionType>();
298 FTy = FT->getCanonicalTypeUnqualified();
299 }
300}
301
302/// Arrange the argument and result information for a declaration or
303/// definition of the given C++ non-static member function. The
304/// member function must be an ordinary function, i.e. not a
305/// constructor or destructor.
306const CGFunctionInfo &
308 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
309 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
310
313 auto prototype = FT.getAs<FunctionProtoType>();
314
316 // The abstract case is perfectly fine.
317 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
318 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
319 }
320
321 return arrangeFreeFunctionType(prototype);
322}
323
325 const InheritedConstructor &Inherited, CXXCtorType Type) {
326 // Parameters are unnecessary if we're constructing a base class subobject
327 // and the inherited constructor lives in a virtual base.
328 return Type == Ctor_Complete ||
329 !Inherited.getShadowDecl()->constructsVirtualBase() ||
330 !Target.getCXXABI().hasConstructorVariants();
331}
332
333const CGFunctionInfo &
335 auto *MD = cast<CXXMethodDecl>(GD.getDecl());
336
339
340 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(GD);
341 argTypes.push_back(DeriveThisType(ThisType, MD));
342
343 bool PassParams = true;
344
345 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
346 // A base class inheriting constructor doesn't get forwarded arguments
347 // needed to construct a virtual base (or base class thereof).
348 if (auto Inherited = CD->getInheritedConstructor())
349 PassParams = inheritingCtorHasParams(Inherited, GD.getCtorType());
350 }
351
353
354 // Add the formal parameters.
355 if (PassParams)
356 appendParameterTypes(*this, argTypes, paramInfos, FTP);
357
359 TheCXXABI.buildStructorSignature(GD, argTypes);
360 if (!paramInfos.empty()) {
361 // Note: prefix implies after the first param.
362 if (AddedArgs.Prefix)
363 paramInfos.insert(paramInfos.begin() + 1, AddedArgs.Prefix,
365 if (AddedArgs.Suffix)
366 paramInfos.append(AddedArgs.Suffix,
368 }
369
370 RequiredArgs required =
371 (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
373
374 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
375 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
376 ? argTypes.front()
377 : TheCXXABI.hasMostDerivedReturn(GD)
378 ? CGM.getContext().VoidPtrTy
379 : Context.VoidTy;
381 argTypes, extInfo, paramInfos, required);
382}
383
387 for (auto &arg : args)
388 argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
389 return argTypes;
390}
391
395 for (auto &arg : args)
396 argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
397 return argTypes;
398}
399
402 unsigned prefixArgs, unsigned totalArgs) {
404 if (proto->hasExtParameterInfos()) {
405 addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
406 }
407 return result;
408}
409
410/// Arrange a call to a C++ method, passing the given arguments.
411///
412/// ExtraPrefixArgs is the number of ABI-specific args passed after the `this`
413/// parameter.
414/// ExtraSuffixArgs is the number of ABI-specific args passed at the end of
415/// args.
416/// PassProtoArgs indicates whether `args` has args for the parameters in the
417/// given CXXConstructorDecl.
418const CGFunctionInfo &
420 const CXXConstructorDecl *D,
421 CXXCtorType CtorKind,
422 unsigned ExtraPrefixArgs,
423 unsigned ExtraSuffixArgs,
424 bool PassProtoArgs) {
425 // FIXME: Kill copy.
427 for (const auto &Arg : args)
428 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
429
430 // +1 for implicit this, which should always be args[0].
431 unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs;
432
434 RequiredArgs Required = PassProtoArgs
436 FPT, TotalPrefixArgs + ExtraSuffixArgs)
438
439 GlobalDecl GD(D, CtorKind);
440 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
441 ? ArgTypes.front()
442 : TheCXXABI.hasMostDerivedReturn(GD)
443 ? CGM.getContext().VoidPtrTy
444 : Context.VoidTy;
445
446 FunctionType::ExtInfo Info = FPT->getExtInfo();
448 // If the prototype args are elided, we should only have ABI-specific args,
449 // which never have param info.
450 if (PassProtoArgs && FPT->hasExtParameterInfos()) {
451 // ABI-specific suffix arguments are treated the same as variadic arguments.
452 addExtParameterInfosForCall(ParamInfos, FPT.getTypePtr(), TotalPrefixArgs,
453 ArgTypes.size());
454 }
455
457 ArgTypes, Info, ParamInfos, Required);
458}
459
460/// Arrange the argument and result information for the declaration or
461/// definition of the given function.
462const CGFunctionInfo &
464 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
465 if (MD->isImplicitObjectMemberFunction())
467
469
470 assert(isa<FunctionType>(FTy));
471 setCUDAKernelCallingConvention(FTy, CGM, FD);
472
473 // When declaring a function without a prototype, always use a
474 // non-variadic type.
476 return arrangeLLVMFunctionInfo(noProto->getReturnType(), FnInfoOpts::None,
477 std::nullopt, noProto->getExtInfo(), {},
479 }
480
482}
483
484/// Arrange the argument and result information for the declaration or
485/// definition of an Objective-C method.
486const CGFunctionInfo &
488 // It happens that this is the same as a call with no optional
489 // arguments, except also using the formal 'self' type.
491}
492
493/// Arrange the argument and result information for the function type
494/// through which to perform a send to the given Objective-C method,
495/// using the given receiver type. The receiver type is not always
496/// the 'self' type of the method or even an Objective-C pointer type.
497/// This is *not* the right method for actually performing such a
498/// message send, due to the possibility of optional arguments.
499const CGFunctionInfo &
501 QualType receiverType) {
504 MD->isDirectMethod() ? 1 : 2);
505 argTys.push_back(Context.getCanonicalParamType(receiverType));
506 if (!MD->isDirectMethod())
507 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
508 // FIXME: Kill copy?
509 for (const auto *I : MD->parameters()) {
510 argTys.push_back(Context.getCanonicalParamType(I->getType()));
512 I->hasAttr<NoEscapeAttr>());
513 extParamInfos.push_back(extParamInfo);
514 }
515
517 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
518 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
519
520 if (getContext().getLangOpts().ObjCAutoRefCount &&
521 MD->hasAttr<NSReturnsRetainedAttr>())
522 einfo = einfo.withProducesResult(true);
523
524 RequiredArgs required =
525 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
526
528 FnInfoOpts::None, argTys, einfo, extParamInfos,
529 required);
530}
531
532const CGFunctionInfo &
534 const CallArgList &args) {
535 auto argTypes = getArgTypesForCall(Context, args);
537
539 argTypes, einfo, {}, RequiredArgs::All);
540}
541
542const CGFunctionInfo &
544 // FIXME: Do we need to handle ObjCMethodDecl?
545 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
546
547 if (isa<CXXConstructorDecl>(GD.getDecl()) ||
548 isa<CXXDestructorDecl>(GD.getDecl()))
550
552}
553
554/// Arrange a thunk that takes 'this' as the first parameter followed by
555/// varargs. Return a void pointer, regardless of the actual return type.
556/// The body of the thunk will end in a musttail call to a function of the
557/// correct type, and the caller will bitcast the function to the correct
558/// prototype.
559const CGFunctionInfo &
561 assert(MD->isVirtual() && "only methods have thunks");
563 CanQualType ArgTys[] = {DeriveThisType(MD->getParent(), MD)};
564 return arrangeLLVMFunctionInfo(Context.VoidTy, FnInfoOpts::None, ArgTys,
565 FTP->getExtInfo(), {}, RequiredArgs(1));
566}
567
568const CGFunctionInfo &
570 CXXCtorType CT) {
571 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
572
575 const CXXRecordDecl *RD = CD->getParent();
576 ArgTys.push_back(DeriveThisType(RD, CD));
577 if (CT == Ctor_CopyingClosure)
578 ArgTys.push_back(*FTP->param_type_begin());
579 if (RD->getNumVBases() > 0)
580 ArgTys.push_back(Context.IntTy);
582 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
584 ArgTys, FunctionType::ExtInfo(CC), {},
586}
587
588/// Arrange a call as unto a free function, except possibly with an
589/// additional number of formal parameters considered required.
590static const CGFunctionInfo &
592 CodeGenModule &CGM,
593 const CallArgList &args,
594 const FunctionType *fnType,
595 unsigned numExtraRequiredArgs,
596 bool chainCall) {
597 assert(args.size() >= numExtraRequiredArgs);
598
600
601 // In most cases, there are no optional arguments.
603
604 // If we have a variadic prototype, the required arguments are the
605 // extra prefix plus the arguments in the prototype.
606 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
607 if (proto->isVariadic())
608 required = RequiredArgs::forPrototypePlus(proto, numExtraRequiredArgs);
609
610 if (proto->hasExtParameterInfos())
611 addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
612 args.size());
613
614 // If we don't have a prototype at all, but we're supposed to
615 // explicitly use the variadic convention for unprototyped calls,
616 // treat all of the arguments as required but preserve the nominal
617 // possibility of variadics.
618 } else if (CGM.getTargetCodeGenInfo()
620 cast<FunctionNoProtoType>(fnType))) {
621 required = RequiredArgs(args.size());
622 }
623
624 // FIXME: Kill copy.
626 for (const auto &arg : args)
627 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
630 opts, argTypes, fnType->getExtInfo(),
631 paramInfos, required);
632}
633
634/// Figure out the rules for calling a function with the given formal
635/// type using the given arguments. The arguments are necessary
636/// because the function might be unprototyped, in which case it's
637/// target-dependent in crazy ways.
638const CGFunctionInfo &
640 const FunctionType *fnType,
641 bool chainCall) {
642 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
643 chainCall ? 1 : 0, chainCall);
644}
645
646/// A block function is essentially a free function with an
647/// extra implicit argument.
648const CGFunctionInfo &
650 const FunctionType *fnType) {
651 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
652 /*chainCall=*/false);
653}
654
655const CGFunctionInfo &
657 const FunctionArgList &params) {
658 auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
659 auto argTypes = getArgTypesForDeclaration(Context, params);
660
662 FnInfoOpts::None, argTypes,
663 proto->getExtInfo(), paramInfos,
665}
666
667const CGFunctionInfo &
669 const CallArgList &args) {
670 // FIXME: Kill copy.
672 for (const auto &Arg : args)
673 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
675 argTypes, FunctionType::ExtInfo(),
676 /*paramInfos=*/{}, RequiredArgs::All);
677}
678
679const CGFunctionInfo &
681 const FunctionArgList &args) {
682 auto argTypes = getArgTypesForDeclaration(Context, args);
683
685 argTypes, FunctionType::ExtInfo(), {},
687}
688
689const CGFunctionInfo &
691 ArrayRef<CanQualType> argTypes) {
692 return arrangeLLVMFunctionInfo(resultType, FnInfoOpts::None, argTypes,
695}
696
697/// Arrange a call to a C++ method, passing the given arguments.
698///
699/// numPrefixArgs is the number of ABI-specific prefix arguments we have. It
700/// does not count `this`.
701const CGFunctionInfo &
703 const FunctionProtoType *proto,
704 RequiredArgs required,
705 unsigned numPrefixArgs) {
706 assert(numPrefixArgs + 1 <= args.size() &&
707 "Emitting a call with less args than the required prefix?");
708 // Add one to account for `this`. It's a bit awkward here, but we don't count
709 // `this` in similar places elsewhere.
710 auto paramInfos =
711 getExtParameterInfosForCall(proto, numPrefixArgs + 1, args.size());
712
713 // FIXME: Kill copy.
714 auto argTypes = getArgTypesForCall(Context, args);
715
716 FunctionType::ExtInfo info = proto->getExtInfo();
718 FnInfoOpts::IsInstanceMethod, argTypes, info,
719 paramInfos, required);
720}
721
724 std::nullopt, FunctionType::ExtInfo(), {},
726}
727
728const CGFunctionInfo &
730 const CallArgList &args) {
731 assert(signature.arg_size() <= args.size());
732 if (signature.arg_size() == args.size())
733 return signature;
734
736 auto sigParamInfos = signature.getExtParameterInfos();
737 if (!sigParamInfos.empty()) {
738 paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
739 paramInfos.resize(args.size());
740 }
741
742 auto argTypes = getArgTypesForCall(Context, args);
743
744 assert(signature.getRequiredArgs().allowsOptionalArgs());
746 if (signature.isInstanceMethod())
748 if (signature.isChainCall())
750 if (signature.isDelegateCall())
752 return arrangeLLVMFunctionInfo(signature.getReturnType(), opts, argTypes,
753 signature.getExtInfo(), paramInfos,
754 signature.getRequiredArgs());
755}
756
757namespace clang {
758namespace CodeGen {
760}
761}
762
763/// Arrange the argument and result information for an abstract value
764/// of a given function type. This is the method which all of the
765/// above functions ultimately defer to.
767 CanQualType resultType, FnInfoOpts opts, ArrayRef<CanQualType> argTypes,
770 RequiredArgs required) {
771 assert(llvm::all_of(argTypes,
772 [](CanQualType T) { return T.isCanonicalAsParam(); }));
773
774 // Lookup or create unique function info.
775 llvm::FoldingSetNodeID ID;
776 bool isInstanceMethod =
778 bool isChainCall =
780 bool isDelegateCall =
782 CGFunctionInfo::Profile(ID, isInstanceMethod, isChainCall, isDelegateCall,
783 info, paramInfos, required, resultType, argTypes);
784
785 void *insertPos = nullptr;
786 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
787 if (FI)
788 return *FI;
789
790 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
791
792 // Construct the function info. We co-allocate the ArgInfos.
793 FI = CGFunctionInfo::create(CC, isInstanceMethod, isChainCall, isDelegateCall,
794 info, paramInfos, resultType, argTypes, required);
795 FunctionInfos.InsertNode(FI, insertPos);
796
797 bool inserted = FunctionsBeingProcessed.insert(FI).second;
798 (void)inserted;
799 assert(inserted && "Recursively being processed?");
800
801 // Compute ABI information.
802 if (CC == llvm::CallingConv::SPIR_KERNEL) {
803 // Force target independent argument handling for the host visible
804 // kernel functions.
805 computeSPIRKernelABIInfo(CGM, *FI);
806 } else if (info.getCC() == CC_Swift || info.getCC() == CC_SwiftAsync) {
808 } else {
809 getABIInfo().computeInfo(*FI);
810 }
811
812 // Loop over all of the computed argument and return value info. If any of
813 // them are direct or extend without a specified coerce type, specify the
814 // default now.
815 ABIArgInfo &retInfo = FI->getReturnInfo();
816 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
818
819 for (auto &I : FI->arguments())
820 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
821 I.info.setCoerceToType(ConvertType(I.type));
822
823 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
824 assert(erased && "Not in set?");
825
826 return *FI;
827}
828
829CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC, bool instanceMethod,
830 bool chainCall, bool delegateCall,
831 const FunctionType::ExtInfo &info,
833 CanQualType resultType,
834 ArrayRef<CanQualType> argTypes,
835 RequiredArgs required) {
836 assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
837 assert(!required.allowsOptionalArgs() ||
838 required.getNumRequiredArgs() <= argTypes.size());
839
840 void *buffer =
841 operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
842 argTypes.size() + 1, paramInfos.size()));
843
844 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
845 FI->CallingConvention = llvmCC;
846 FI->EffectiveCallingConvention = llvmCC;
847 FI->ASTCallingConvention = info.getCC();
848 FI->InstanceMethod = instanceMethod;
849 FI->ChainCall = chainCall;
850 FI->DelegateCall = delegateCall;
851 FI->CmseNSCall = info.getCmseNSCall();
852 FI->NoReturn = info.getNoReturn();
853 FI->ReturnsRetained = info.getProducesResult();
854 FI->NoCallerSavedRegs = info.getNoCallerSavedRegs();
855 FI->NoCfCheck = info.getNoCfCheck();
856 FI->Required = required;
857 FI->HasRegParm = info.getHasRegParm();
858 FI->RegParm = info.getRegParm();
859 FI->ArgStruct = nullptr;
860 FI->ArgStructAlign = 0;
861 FI->NumArgs = argTypes.size();
862 FI->HasExtParameterInfos = !paramInfos.empty();
863 FI->getArgsBuffer()[0].type = resultType;
864 FI->MaxVectorWidth = 0;
865 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
866 FI->getArgsBuffer()[i + 1].type = argTypes[i];
867 for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
868 FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
869 return FI;
870}
871
872/***/
873
874namespace {
875// ABIArgInfo::Expand implementation.
876
877// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
878struct TypeExpansion {
879 enum TypeExpansionKind {
880 // Elements of constant arrays are expanded recursively.
881 TEK_ConstantArray,
882 // Record fields are expanded recursively (but if record is a union, only
883 // the field with the largest size is expanded).
884 TEK_Record,
885 // For complex types, real and imaginary parts are expanded recursively.
887 // All other types are not expandable.
888 TEK_None
889 };
890
891 const TypeExpansionKind Kind;
892
893 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
894 virtual ~TypeExpansion() {}
895};
896
897struct ConstantArrayExpansion : TypeExpansion {
898 QualType EltTy;
899 uint64_t NumElts;
900
901 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
902 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
903 static bool classof(const TypeExpansion *TE) {
904 return TE->Kind == TEK_ConstantArray;
905 }
906};
907
908struct RecordExpansion : TypeExpansion {
910
912
913 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
915 : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
916 Fields(std::move(Fields)) {}
917 static bool classof(const TypeExpansion *TE) {
918 return TE->Kind == TEK_Record;
919 }
920};
921
922struct ComplexExpansion : TypeExpansion {
923 QualType EltTy;
924
925 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
926 static bool classof(const TypeExpansion *TE) {
927 return TE->Kind == TEK_Complex;
928 }
929};
930
931struct NoExpansion : TypeExpansion {
932 NoExpansion() : TypeExpansion(TEK_None) {}
933 static bool classof(const TypeExpansion *TE) {
934 return TE->Kind == TEK_None;
935 }
936};
937} // namespace
938
939static std::unique_ptr<TypeExpansion>
941 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
942 return std::make_unique<ConstantArrayExpansion>(AT->getElementType(),
943 AT->getZExtSize());
944 }
945 if (const RecordType *RT = Ty->getAs<RecordType>()) {
948 const RecordDecl *RD = RT->getDecl();
949 assert(!RD->hasFlexibleArrayMember() &&
950 "Cannot expand structure with flexible array.");
951 if (RD->isUnion()) {
952 // Unions can be here only in degenerative cases - all the fields are same
953 // after flattening. Thus we have to use the "largest" field.
954 const FieldDecl *LargestFD = nullptr;
955 CharUnits UnionSize = CharUnits::Zero();
956
957 for (const auto *FD : RD->fields()) {
958 if (FD->isZeroLengthBitField(Context))
959 continue;
960 assert(!FD->isBitField() &&
961 "Cannot expand structure with bit-field members.");
962 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
963 if (UnionSize < FieldSize) {
964 UnionSize = FieldSize;
965 LargestFD = FD;
966 }
967 }
968 if (LargestFD)
969 Fields.push_back(LargestFD);
970 } else {
971 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
972 assert(!CXXRD->isDynamicClass() &&
973 "cannot expand vtable pointers in dynamic classes");
974 llvm::append_range(Bases, llvm::make_pointer_range(CXXRD->bases()));
975 }
976
977 for (const auto *FD : RD->fields()) {
978 if (FD->isZeroLengthBitField(Context))
979 continue;
980 assert(!FD->isBitField() &&
981 "Cannot expand structure with bit-field members.");
982 Fields.push_back(FD);
983 }
984 }
985 return std::make_unique<RecordExpansion>(std::move(Bases),
986 std::move(Fields));
987 }
988 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
989 return std::make_unique<ComplexExpansion>(CT->getElementType());
990 }
991 return std::make_unique<NoExpansion>();
992}
993
994static int getExpansionSize(QualType Ty, const ASTContext &Context) {
995 auto Exp = getTypeExpansion(Ty, Context);
996 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
997 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
998 }
999 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1000 int Res = 0;
1001 for (auto BS : RExp->Bases)
1002 Res += getExpansionSize(BS->getType(), Context);
1003 for (auto FD : RExp->Fields)
1004 Res += getExpansionSize(FD->getType(), Context);
1005 return Res;
1006 }
1007 if (isa<ComplexExpansion>(Exp.get()))
1008 return 2;
1009 assert(isa<NoExpansion>(Exp.get()));
1010 return 1;
1011}
1012
1013void
1016 auto Exp = getTypeExpansion(Ty, Context);
1017 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1018 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
1019 getExpandedTypes(CAExp->EltTy, TI);
1020 }
1021 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1022 for (auto BS : RExp->Bases)
1023 getExpandedTypes(BS->getType(), TI);
1024 for (auto FD : RExp->Fields)
1025 getExpandedTypes(FD->getType(), TI);
1026 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
1027 llvm::Type *EltTy = ConvertType(CExp->EltTy);
1028 *TI++ = EltTy;
1029 *TI++ = EltTy;
1030 } else {
1031 assert(isa<NoExpansion>(Exp.get()));
1032 *TI++ = ConvertType(Ty);
1033 }
1034}
1035
1037 ConstantArrayExpansion *CAE,
1038 Address BaseAddr,
1039 llvm::function_ref<void(Address)> Fn) {
1040 for (int i = 0, n = CAE->NumElts; i < n; i++) {
1041 Address EltAddr = CGF.Builder.CreateConstGEP2_32(BaseAddr, 0, i);
1042 Fn(EltAddr);
1043 }
1044}
1045
1046void CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
1047 llvm::Function::arg_iterator &AI) {
1048 assert(LV.isSimple() &&
1049 "Unexpected non-simple lvalue during struct expansion.");
1050
1051 auto Exp = getTypeExpansion(Ty, getContext());
1052 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1054 *this, CAExp, LV.getAddress(), [&](Address EltAddr) {
1055 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
1056 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
1057 });
1058 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1059 Address This = LV.getAddress();
1060 for (const CXXBaseSpecifier *BS : RExp->Bases) {
1061 // Perform a single step derived-to-base conversion.
1062 Address Base =
1063 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1064 /*NullCheckValue=*/false, SourceLocation());
1065 LValue SubLV = MakeAddrLValue(Base, BS->getType());
1066
1067 // Recurse onto bases.
1068 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
1069 }
1070 for (auto FD : RExp->Fields) {
1071 // FIXME: What are the right qualifiers here?
1073 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
1074 }
1075 } else if (isa<ComplexExpansion>(Exp.get())) {
1076 auto realValue = &*AI++;
1077 auto imagValue = &*AI++;
1078 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
1079 } else {
1080 // Call EmitStoreOfScalar except when the lvalue is a bitfield to emit a
1081 // primitive store.
1082 assert(isa<NoExpansion>(Exp.get()));
1083 llvm::Value *Arg = &*AI++;
1084 if (LV.isBitField()) {
1086 } else {
1087 // TODO: currently there are some places are inconsistent in what LLVM
1088 // pointer type they use (see D118744). Once clang uses opaque pointers
1089 // all LLVM pointer types will be the same and we can remove this check.
1090 if (Arg->getType()->isPointerTy()) {
1091 Address Addr = LV.getAddress();
1092 Arg = Builder.CreateBitCast(Arg, Addr.getElementType());
1093 }
1094 EmitStoreOfScalar(Arg, LV);
1095 }
1096 }
1097}
1098
1099void CodeGenFunction::ExpandTypeToArgs(
1100 QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
1101 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
1102 auto Exp = getTypeExpansion(Ty, getContext());
1103 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1104 Address Addr = Arg.hasLValue() ? Arg.getKnownLValue().getAddress()
1107 *this, CAExp, Addr, [&](Address EltAddr) {
1108 CallArg EltArg = CallArg(
1109 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation()),
1110 CAExp->EltTy);
1111 ExpandTypeToArgs(CAExp->EltTy, EltArg, IRFuncTy, IRCallArgs,
1112 IRCallArgPos);
1113 });
1114 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1117 for (const CXXBaseSpecifier *BS : RExp->Bases) {
1118 // Perform a single step derived-to-base conversion.
1119 Address Base =
1120 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1121 /*NullCheckValue=*/false, SourceLocation());
1122 CallArg BaseArg = CallArg(RValue::getAggregate(Base), BS->getType());
1123
1124 // Recurse onto bases.
1125 ExpandTypeToArgs(BS->getType(), BaseArg, IRFuncTy, IRCallArgs,
1126 IRCallArgPos);
1127 }
1128
1129 LValue LV = MakeAddrLValue(This, Ty);
1130 for (auto FD : RExp->Fields) {
1131 CallArg FldArg =
1132 CallArg(EmitRValueForField(LV, FD, SourceLocation()), FD->getType());
1133 ExpandTypeToArgs(FD->getType(), FldArg, IRFuncTy, IRCallArgs,
1134 IRCallArgPos);
1135 }
1136 } else if (isa<ComplexExpansion>(Exp.get())) {
1138 IRCallArgs[IRCallArgPos++] = CV.first;
1139 IRCallArgs[IRCallArgPos++] = CV.second;
1140 } else {
1141 assert(isa<NoExpansion>(Exp.get()));
1142 auto RV = Arg.getKnownRValue();
1143 assert(RV.isScalar() &&
1144 "Unexpected non-scalar rvalue during struct expansion.");
1145
1146 // Insert a bitcast as needed.
1147 llvm::Value *V = RV.getScalarVal();
1148 if (IRCallArgPos < IRFuncTy->getNumParams() &&
1149 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
1150 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
1151
1152 IRCallArgs[IRCallArgPos++] = V;
1153 }
1154}
1155
1156/// Create a temporary allocation for the purposes of coercion.
1158 llvm::Type *Ty,
1159 CharUnits MinAlign,
1160 const Twine &Name = "tmp") {
1161 // Don't use an alignment that's worse than what LLVM would prefer.
1162 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(Ty);
1163 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
1164
1165 return CGF.CreateTempAlloca(Ty, Align, Name + ".coerce");
1166}
1167
1168/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
1169/// accessing some number of bytes out of it, try to gep into the struct to get
1170/// at its inner goodness. Dive as deep as possible without entering an element
1171/// with an in-memory size smaller than DstSize.
1172static Address
1174 llvm::StructType *SrcSTy,
1175 uint64_t DstSize, CodeGenFunction &CGF) {
1176 // We can't dive into a zero-element struct.
1177 if (SrcSTy->getNumElements() == 0) return SrcPtr;
1178
1179 llvm::Type *FirstElt = SrcSTy->getElementType(0);
1180
1181 // If the first elt is at least as large as what we're looking for, or if the
1182 // first element is the same size as the whole struct, we can enter it. The
1183 // comparison must be made on the store size and not the alloca size. Using
1184 // the alloca size may overstate the size of the load.
1185 uint64_t FirstEltSize =
1186 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
1187 if (FirstEltSize < DstSize &&
1188 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
1189 return SrcPtr;
1190
1191 // GEP into the first element.
1192 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, "coerce.dive");
1193
1194 // If the first element is a struct, recurse.
1195 llvm::Type *SrcTy = SrcPtr.getElementType();
1196 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
1197 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
1198
1199 return SrcPtr;
1200}
1201
1202/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1203/// are either integers or pointers. This does a truncation of the value if it
1204/// is too large or a zero extension if it is too small.
1205///
1206/// This behaves as if the value were coerced through memory, so on big-endian
1207/// targets the high bits are preserved in a truncation, while little-endian
1208/// targets preserve the low bits.
1209static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
1210 llvm::Type *Ty,
1211 CodeGenFunction &CGF) {
1212 if (Val->getType() == Ty)
1213 return Val;
1214
1215 if (isa<llvm::PointerType>(Val->getType())) {
1216 // If this is Pointer->Pointer avoid conversion to and from int.
1217 if (isa<llvm::PointerType>(Ty))
1218 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
1219
1220 // Convert the pointer to an integer so we can play with its width.
1221 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
1222 }
1223
1224 llvm::Type *DestIntTy = Ty;
1225 if (isa<llvm::PointerType>(DestIntTy))
1226 DestIntTy = CGF.IntPtrTy;
1227
1228 if (Val->getType() != DestIntTy) {
1229 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
1230 if (DL.isBigEndian()) {
1231 // Preserve the high bits on big-endian targets.
1232 // That is what memory coercion does.
1233 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1234 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1235
1236 if (SrcSize > DstSize) {
1237 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
1238 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
1239 } else {
1240 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
1241 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
1242 }
1243 } else {
1244 // Little-endian targets preserve the low bits. No shifts required.
1245 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
1246 }
1247 }
1248
1249 if (isa<llvm::PointerType>(Ty))
1250 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
1251 return Val;
1252}
1253
1254
1255
1256/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
1257/// a pointer to an object of type \arg Ty, known to be aligned to
1258/// \arg SrcAlign bytes.
1259///
1260/// This safely handles the case when the src type is smaller than the
1261/// destination type; in this situation the values of bits which not
1262/// present in the src are undefined.
1263static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
1264 CodeGenFunction &CGF) {
1265 llvm::Type *SrcTy = Src.getElementType();
1266
1267 // If SrcTy and Ty are the same, just do a load.
1268 if (SrcTy == Ty)
1269 return CGF.Builder.CreateLoad(Src);
1270
1271 llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
1272
1273 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
1274 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy,
1275 DstSize.getFixedValue(), CGF);
1276 SrcTy = Src.getElementType();
1277 }
1278
1279 llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
1280
1281 // If the source and destination are integer or pointer types, just do an
1282 // extension or truncation to the desired type.
1283 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
1284 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
1285 llvm::Value *Load = CGF.Builder.CreateLoad(Src);
1286 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
1287 }
1288
1289 // If load is legal, just bitcast the src pointer.
1290 if (!SrcSize.isScalable() && !DstSize.isScalable() &&
1291 SrcSize.getFixedValue() >= DstSize.getFixedValue()) {
1292 // Generally SrcSize is never greater than DstSize, since this means we are
1293 // losing bits. However, this can happen in cases where the structure has
1294 // additional padding, for example due to a user specified alignment.
1295 //
1296 // FIXME: Assert that we aren't truncating non-padding bits when have access
1297 // to that information.
1298 Src = Src.withElementType(Ty);
1299 return CGF.Builder.CreateLoad(Src);
1300 }
1301
1302 // If coercing a fixed vector to a scalable vector for ABI compatibility, and
1303 // the types match, use the llvm.vector.insert intrinsic to perform the
1304 // conversion.
1305 if (auto *ScalableDstTy = dyn_cast<llvm::ScalableVectorType>(Ty)) {
1306 if (auto *FixedSrcTy = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
1307 // If we are casting a fixed i8 vector to a scalable i1 predicate
1308 // vector, use a vector insert and bitcast the result.
1309 if (ScalableDstTy->getElementType()->isIntegerTy(1) &&
1310 ScalableDstTy->getElementCount().isKnownMultipleOf(8) &&
1311 FixedSrcTy->getElementType()->isIntegerTy(8)) {
1312 ScalableDstTy = llvm::ScalableVectorType::get(
1313 FixedSrcTy->getElementType(),
1314 ScalableDstTy->getElementCount().getKnownMinValue() / 8);
1315 }
1316 if (ScalableDstTy->getElementType() == FixedSrcTy->getElementType()) {
1317 auto *Load = CGF.Builder.CreateLoad(Src);
1318 auto *UndefVec = llvm::UndefValue::get(ScalableDstTy);
1319 auto *Zero = llvm::Constant::getNullValue(CGF.CGM.Int64Ty);
1320 llvm::Value *Result = CGF.Builder.CreateInsertVector(
1321 ScalableDstTy, UndefVec, Load, Zero, "cast.scalable");
1322 if (ScalableDstTy != Ty)
1323 Result = CGF.Builder.CreateBitCast(Result, Ty);
1324 return Result;
1325 }
1326 }
1327 }
1328
1329 // Otherwise do coercion through memory. This is stupid, but simple.
1330 RawAddress Tmp =
1331 CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment(), Src.getName());
1333 Tmp.getPointer(), Tmp.getAlignment().getAsAlign(),
1334 Src.emitRawPointer(CGF), Src.getAlignment().getAsAlign(),
1335 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize.getKnownMinValue()));
1336 return CGF.Builder.CreateLoad(Tmp);
1337}
1338
1339// Function to store a first-class aggregate into memory. We prefer to
1340// store the elements rather than the aggregate to be more friendly to
1341// fast-isel.
1342// FIXME: Do we need to recurse here?
1343void CodeGenFunction::EmitAggregateStore(llvm::Value *Val, Address Dest,
1344 bool DestIsVolatile) {
1345 // Prefer scalar stores to first-class aggregate stores.
1346 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(Val->getType())) {
1347 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1348 Address EltPtr = Builder.CreateStructGEP(Dest, i);
1349 llvm::Value *Elt = Builder.CreateExtractValue(Val, i);
1350 Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
1351 }
1352 } else {
1353 Builder.CreateStore(Val, Dest, DestIsVolatile);
1354 }
1355}
1356
1357/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
1358/// where the source and destination may have different types. The
1359/// destination is known to be aligned to \arg DstAlign bytes.
1360///
1361/// This safely handles the case when the src type is larger than the
1362/// destination type; the upper bits of the src will be lost.
1363static void CreateCoercedStore(llvm::Value *Src,
1364 Address Dst,
1365 bool DstIsVolatile,
1366 CodeGenFunction &CGF) {
1367 llvm::Type *SrcTy = Src->getType();
1368 llvm::Type *DstTy = Dst.getElementType();
1369 if (SrcTy == DstTy) {
1370 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1371 return;
1372 }
1373
1374 llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
1375
1376 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
1377 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy,
1378 SrcSize.getFixedValue(), CGF);
1379 DstTy = Dst.getElementType();
1380 }
1381
1382 llvm::PointerType *SrcPtrTy = llvm::dyn_cast<llvm::PointerType>(SrcTy);
1383 llvm::PointerType *DstPtrTy = llvm::dyn_cast<llvm::PointerType>(DstTy);
1384 if (SrcPtrTy && DstPtrTy &&
1385 SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace()) {
1386 Src = CGF.Builder.CreateAddrSpaceCast(Src, DstTy);
1387 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1388 return;
1389 }
1390
1391 // If the source and destination are integer or pointer types, just do an
1392 // extension or truncation to the desired type.
1393 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1394 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1395 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
1396 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1397 return;
1398 }
1399
1400 llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
1401
1402 // If store is legal, just bitcast the src pointer.
1403 if (isa<llvm::ScalableVectorType>(SrcTy) ||
1404 isa<llvm::ScalableVectorType>(DstTy) ||
1405 SrcSize.getFixedValue() <= DstSize.getFixedValue()) {
1406 Dst = Dst.withElementType(SrcTy);
1407 CGF.EmitAggregateStore(Src, Dst, DstIsVolatile);
1408 } else {
1409 // Otherwise do coercion through memory. This is stupid, but
1410 // simple.
1411
1412 // Generally SrcSize is never greater than DstSize, since this means we are
1413 // losing bits. However, this can happen in cases where the structure has
1414 // additional padding, for example due to a user specified alignment.
1415 //
1416 // FIXME: Assert that we aren't truncating non-padding bits when have access
1417 // to that information.
1418 RawAddress Tmp =
1419 CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1420 CGF.Builder.CreateStore(Src, Tmp);
1422 Dst.emitRawPointer(CGF), Dst.getAlignment().getAsAlign(),
1423 Tmp.getPointer(), Tmp.getAlignment().getAsAlign(),
1424 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize.getFixedValue()));
1425 }
1426}
1427
1429 const ABIArgInfo &info) {
1430 if (unsigned offset = info.getDirectOffset()) {
1431 addr = addr.withElementType(CGF.Int8Ty);
1432 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1433 CharUnits::fromQuantity(offset));
1434 addr = addr.withElementType(info.getCoerceToType());
1435 }
1436 return addr;
1437}
1438
1439namespace {
1440
1441/// Encapsulates information about the way function arguments from
1442/// CGFunctionInfo should be passed to actual LLVM IR function.
1443class ClangToLLVMArgMapping {
1444 static const unsigned InvalidIndex = ~0U;
1445 unsigned InallocaArgNo;
1446 unsigned SRetArgNo;
1447 unsigned TotalIRArgs;
1448
1449 /// Arguments of LLVM IR function corresponding to single Clang argument.
1450 struct IRArgs {
1451 unsigned PaddingArgIndex;
1452 // Argument is expanded to IR arguments at positions
1453 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1454 unsigned FirstArgIndex;
1455 unsigned NumberOfArgs;
1456
1457 IRArgs()
1458 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1459 NumberOfArgs(0) {}
1460 };
1461
1462 SmallVector<IRArgs, 8> ArgInfo;
1463
1464public:
1465 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1466 bool OnlyRequiredArgs = false)
1467 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1468 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1469 construct(Context, FI, OnlyRequiredArgs);
1470 }
1471
1472 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1473 unsigned getInallocaArgNo() const {
1474 assert(hasInallocaArg());
1475 return InallocaArgNo;
1476 }
1477
1478 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1479 unsigned getSRetArgNo() const {
1480 assert(hasSRetArg());
1481 return SRetArgNo;
1482 }
1483
1484 unsigned totalIRArgs() const { return TotalIRArgs; }
1485
1486 bool hasPaddingArg(unsigned ArgNo) const {
1487 assert(ArgNo < ArgInfo.size());
1488 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1489 }
1490 unsigned getPaddingArgNo(unsigned ArgNo) const {
1491 assert(hasPaddingArg(ArgNo));
1492 return ArgInfo[ArgNo].PaddingArgIndex;
1493 }
1494
1495 /// Returns index of first IR argument corresponding to ArgNo, and their
1496 /// quantity.
1497 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1498 assert(ArgNo < ArgInfo.size());
1499 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1500 ArgInfo[ArgNo].NumberOfArgs);
1501 }
1502
1503private:
1504 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1505 bool OnlyRequiredArgs);
1506};
1507
1508void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1509 const CGFunctionInfo &FI,
1510 bool OnlyRequiredArgs) {
1511 unsigned IRArgNo = 0;
1512 bool SwapThisWithSRet = false;
1513 const ABIArgInfo &RetAI = FI.getReturnInfo();
1514
1515 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1516 SwapThisWithSRet = RetAI.isSRetAfterThis();
1517 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1518 }
1519
1520 unsigned ArgNo = 0;
1521 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1522 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1523 ++I, ++ArgNo) {
1524 assert(I != FI.arg_end());
1525 QualType ArgType = I->type;
1526 const ABIArgInfo &AI = I->info;
1527 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1528 auto &IRArgs = ArgInfo[ArgNo];
1529
1530 if (AI.getPaddingType())
1531 IRArgs.PaddingArgIndex = IRArgNo++;
1532
1533 switch (AI.getKind()) {
1534 case ABIArgInfo::Extend:
1535 case ABIArgInfo::Direct: {
1536 // FIXME: handle sseregparm someday...
1537 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1538 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1539 IRArgs.NumberOfArgs = STy->getNumElements();
1540 } else {
1541 IRArgs.NumberOfArgs = 1;
1542 }
1543 break;
1544 }
1547 IRArgs.NumberOfArgs = 1;
1548 break;
1549 case ABIArgInfo::Ignore:
1551 // ignore and inalloca doesn't have matching LLVM parameters.
1552 IRArgs.NumberOfArgs = 0;
1553 break;
1555 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1556 break;
1557 case ABIArgInfo::Expand:
1558 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1559 break;
1560 }
1561
1562 if (IRArgs.NumberOfArgs > 0) {
1563 IRArgs.FirstArgIndex = IRArgNo;
1564 IRArgNo += IRArgs.NumberOfArgs;
1565 }
1566
1567 // Skip over the sret parameter when it comes second. We already handled it
1568 // above.
1569 if (IRArgNo == 1 && SwapThisWithSRet)
1570 IRArgNo++;
1571 }
1572 assert(ArgNo == ArgInfo.size());
1573
1574 if (FI.usesInAlloca())
1575 InallocaArgNo = IRArgNo++;
1576
1577 TotalIRArgs = IRArgNo;
1578}
1579} // namespace
1580
1581/***/
1582
1584 const auto &RI = FI.getReturnInfo();
1585 return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet());
1586}
1587
1589 const auto &RI = FI.getReturnInfo();
1590 return RI.getInReg();
1591}
1592
1594 return ReturnTypeUsesSRet(FI) &&
1596}
1597
1599 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1600 switch (BT->getKind()) {
1601 default:
1602 return false;
1603 case BuiltinType::Float:
1605 case BuiltinType::Double:
1607 case BuiltinType::LongDouble:
1609 }
1610 }
1611
1612 return false;
1613}
1614
1616 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1617 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1618 if (BT->getKind() == BuiltinType::LongDouble)
1620 }
1621 }
1622
1623 return false;
1624}
1625
1628 return GetFunctionType(FI);
1629}
1630
1631llvm::FunctionType *
1633
1634 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1635 (void)Inserted;
1636 assert(Inserted && "Recursively being processed?");
1637
1638 llvm::Type *resultType = nullptr;
1639 const ABIArgInfo &retAI = FI.getReturnInfo();
1640 switch (retAI.getKind()) {
1641 case ABIArgInfo::Expand:
1643 llvm_unreachable("Invalid ABI kind for return argument");
1644
1645 case ABIArgInfo::Extend:
1646 case ABIArgInfo::Direct:
1647 resultType = retAI.getCoerceToType();
1648 break;
1649
1651 if (retAI.getInAllocaSRet()) {
1652 // sret things on win32 aren't void, they return the sret pointer.
1653 QualType ret = FI.getReturnType();
1654 unsigned addressSpace = CGM.getTypes().getTargetAddressSpace(ret);
1655 resultType = llvm::PointerType::get(getLLVMContext(), addressSpace);
1656 } else {
1657 resultType = llvm::Type::getVoidTy(getLLVMContext());
1658 }
1659 break;
1660
1662 case ABIArgInfo::Ignore:
1663 resultType = llvm::Type::getVoidTy(getLLVMContext());
1664 break;
1665
1667 resultType = retAI.getUnpaddedCoerceAndExpandType();
1668 break;
1669 }
1670
1671 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1672 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1673
1674 // Add type for sret argument.
1675 if (IRFunctionArgs.hasSRetArg()) {
1676 QualType Ret = FI.getReturnType();
1677 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(Ret);
1678 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1679 llvm::PointerType::get(getLLVMContext(), AddressSpace);
1680 }
1681
1682 // Add type for inalloca argument.
1683 if (IRFunctionArgs.hasInallocaArg())
1684 ArgTypes[IRFunctionArgs.getInallocaArgNo()] =
1685 llvm::PointerType::getUnqual(getLLVMContext());
1686
1687 // Add in all of the required arguments.
1688 unsigned ArgNo = 0;
1690 ie = it + FI.getNumRequiredArgs();
1691 for (; it != ie; ++it, ++ArgNo) {
1692 const ABIArgInfo &ArgInfo = it->info;
1693
1694 // Insert a padding type to ensure proper alignment.
1695 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1696 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1697 ArgInfo.getPaddingType();
1698
1699 unsigned FirstIRArg, NumIRArgs;
1700 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1701
1702 switch (ArgInfo.getKind()) {
1703 case ABIArgInfo::Ignore:
1705 assert(NumIRArgs == 0);
1706 break;
1707
1709 assert(NumIRArgs == 1);
1710 // indirect arguments are always on the stack, which is alloca addr space.
1711 ArgTypes[FirstIRArg] = llvm::PointerType::get(
1712 getLLVMContext(), CGM.getDataLayout().getAllocaAddrSpace());
1713 break;
1715 assert(NumIRArgs == 1);
1716 ArgTypes[FirstIRArg] = llvm::PointerType::get(
1718 break;
1719 case ABIArgInfo::Extend:
1720 case ABIArgInfo::Direct: {
1721 // Fast-isel and the optimizer generally like scalar values better than
1722 // FCAs, so we flatten them if this is safe to do for this argument.
1723 llvm::Type *argType = ArgInfo.getCoerceToType();
1724 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
1725 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1726 assert(NumIRArgs == st->getNumElements());
1727 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
1728 ArgTypes[FirstIRArg + i] = st->getElementType(i);
1729 } else {
1730 assert(NumIRArgs == 1);
1731 ArgTypes[FirstIRArg] = argType;
1732 }
1733 break;
1734 }
1735
1737 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1738 for (auto *EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1739 *ArgTypesIter++ = EltTy;
1740 }
1741 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1742 break;
1743 }
1744
1745 case ABIArgInfo::Expand:
1746 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1747 getExpandedTypes(it->type, ArgTypesIter);
1748 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1749 break;
1750 }
1751 }
1752
1753 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1754 assert(Erased && "Not in set?");
1755
1756 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
1757}
1758
1760 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1761 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1762
1763 if (!isFuncTypeConvertible(FPT))
1764 return llvm::StructType::get(getLLVMContext());
1765
1766 return GetFunctionType(GD);
1767}
1768
1770 llvm::AttrBuilder &FuncAttrs,
1771 const FunctionProtoType *FPT) {
1772 if (!FPT)
1773 return;
1774
1776 FPT->isNothrow())
1777 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1778
1779 unsigned SMEBits = FPT->getAArch64SMEAttributes();
1781 FuncAttrs.addAttribute("aarch64_pstate_sm_enabled");
1783 FuncAttrs.addAttribute("aarch64_pstate_sm_compatible");
1784
1785 // ZA
1787 FuncAttrs.addAttribute("aarch64_preserves_za");
1789 FuncAttrs.addAttribute("aarch64_in_za");
1791 FuncAttrs.addAttribute("aarch64_out_za");
1793 FuncAttrs.addAttribute("aarch64_inout_za");
1794
1795 // ZT0
1797 FuncAttrs.addAttribute("aarch64_preserves_zt0");
1799 FuncAttrs.addAttribute("aarch64_in_zt0");
1801 FuncAttrs.addAttribute("aarch64_out_zt0");
1803 FuncAttrs.addAttribute("aarch64_inout_zt0");
1804}
1805
1806static void AddAttributesFromOMPAssumes(llvm::AttrBuilder &FuncAttrs,
1807 const Decl *Callee) {
1808 if (!Callee)
1809 return;
1810
1812
1813 for (const OMPAssumeAttr *AA : Callee->specific_attrs<OMPAssumeAttr>())
1814 AA->getAssumption().split(Attrs, ",");
1815
1816 if (!Attrs.empty())
1817 FuncAttrs.addAttribute(llvm::AssumptionAttrKey,
1818 llvm::join(Attrs.begin(), Attrs.end(), ","));
1819}
1820
1822 QualType ReturnType) const {
1823 // We can't just discard the return value for a record type with a
1824 // complex destructor or a non-trivially copyable type.
1825 if (const RecordType *RT =
1826 ReturnType.getCanonicalType()->getAs<RecordType>()) {
1827 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1828 return ClassDecl->hasTrivialDestructor();
1829 }
1830 return ReturnType.isTriviallyCopyableType(Context);
1831}
1832
1834 const Decl *TargetDecl) {
1835 // As-is msan can not tolerate noundef mismatch between caller and
1836 // implementation. Mismatch is possible for e.g. indirect calls from C-caller
1837 // into C++. Such mismatches lead to confusing false reports. To avoid
1838 // expensive workaround on msan we enforce initialization event in uncommon
1839 // cases where it's allowed.
1840 if (Module.getLangOpts().Sanitize.has(SanitizerKind::Memory))
1841 return true;
1842 // C++ explicitly makes returning undefined values UB. C's rule only applies
1843 // to used values, so we never mark them noundef for now.
1844 if (!Module.getLangOpts().CPlusPlus)
1845 return false;
1846 if (TargetDecl) {
1847 if (const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(TargetDecl)) {
1848 if (FDecl->isExternC())
1849 return false;
1850 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(TargetDecl)) {
1851 // Function pointer.
1852 if (VDecl->isExternC())
1853 return false;
1854 }
1855 }
1856
1857 // We don't want to be too aggressive with the return checking, unless
1858 // it's explicit in the code opts or we're using an appropriate sanitizer.
1859 // Try to respect what the programmer intended.
1860 return Module.getCodeGenOpts().StrictReturn ||
1861 !Module.MayDropFunctionReturn(Module.getContext(), RetTy) ||
1862 Module.getLangOpts().Sanitize.has(SanitizerKind::Return);
1863}
1864
1865/// Add denormal-fp-math and denormal-fp-math-f32 as appropriate for the
1866/// requested denormal behavior, accounting for the overriding behavior of the
1867/// -f32 case.
1868static void addDenormalModeAttrs(llvm::DenormalMode FPDenormalMode,
1869 llvm::DenormalMode FP32DenormalMode,
1870 llvm::AttrBuilder &FuncAttrs) {
1871 if (FPDenormalMode != llvm::DenormalMode::getDefault())
1872 FuncAttrs.addAttribute("denormal-fp-math", FPDenormalMode.str());
1873
1874 if (FP32DenormalMode != FPDenormalMode && FP32DenormalMode.isValid())
1875 FuncAttrs.addAttribute("denormal-fp-math-f32", FP32DenormalMode.str());
1876}
1877
1878/// Add default attributes to a function, which have merge semantics under
1879/// -mlink-builtin-bitcode and should not simply overwrite any existing
1880/// attributes in the linked library.
1881static void
1883 llvm::AttrBuilder &FuncAttrs) {
1884 addDenormalModeAttrs(CodeGenOpts.FPDenormalMode, CodeGenOpts.FP32DenormalMode,
1885 FuncAttrs);
1886}
1887
1889 StringRef Name, bool HasOptnone, const CodeGenOptions &CodeGenOpts,
1890 const LangOptions &LangOpts, bool AttrOnCallSite,
1891 llvm::AttrBuilder &FuncAttrs) {
1892 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1893 if (!HasOptnone) {
1894 if (CodeGenOpts.OptimizeSize)
1895 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1896 if (CodeGenOpts.OptimizeSize == 2)
1897 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1898 }
1899
1900 if (CodeGenOpts.DisableRedZone)
1901 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
1902 if (CodeGenOpts.IndirectTlsSegRefs)
1903 FuncAttrs.addAttribute("indirect-tls-seg-refs");
1904 if (CodeGenOpts.NoImplicitFloat)
1905 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
1906
1907 if (AttrOnCallSite) {
1908 // Attributes that should go on the call site only.
1909 // FIXME: Look for 'BuiltinAttr' on the function rather than re-checking
1910 // the -fno-builtin-foo list.
1911 if (!CodeGenOpts.SimplifyLibCalls || LangOpts.isNoBuiltinFunc(Name))
1912 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
1913 if (!CodeGenOpts.TrapFuncName.empty())
1914 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
1915 } else {
1916 switch (CodeGenOpts.getFramePointer()) {
1918 // This is the default behavior.
1919 break;
1922 FuncAttrs.addAttribute("frame-pointer",
1924 CodeGenOpts.getFramePointer()));
1925 }
1926
1927 if (CodeGenOpts.LessPreciseFPMAD)
1928 FuncAttrs.addAttribute("less-precise-fpmad", "true");
1929
1930 if (CodeGenOpts.NullPointerIsValid)
1931 FuncAttrs.addAttribute(llvm::Attribute::NullPointerIsValid);
1932
1934 FuncAttrs.addAttribute("no-trapping-math", "true");
1935
1936 // TODO: Are these all needed?
1937 // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
1938 if (LangOpts.NoHonorInfs)
1939 FuncAttrs.addAttribute("no-infs-fp-math", "true");
1940 if (LangOpts.NoHonorNaNs)
1941 FuncAttrs.addAttribute("no-nans-fp-math", "true");
1942 if (LangOpts.ApproxFunc)
1943 FuncAttrs.addAttribute("approx-func-fp-math", "true");
1944 if (LangOpts.AllowFPReassoc && LangOpts.AllowRecip &&
1945 LangOpts.NoSignedZero && LangOpts.ApproxFunc &&
1946 (LangOpts.getDefaultFPContractMode() ==
1948 LangOpts.getDefaultFPContractMode() ==
1950 FuncAttrs.addAttribute("unsafe-fp-math", "true");
1951 if (CodeGenOpts.SoftFloat)
1952 FuncAttrs.addAttribute("use-soft-float", "true");
1953 FuncAttrs.addAttribute("stack-protector-buffer-size",
1954 llvm::utostr(CodeGenOpts.SSPBufferSize));
1955 if (LangOpts.NoSignedZero)
1956 FuncAttrs.addAttribute("no-signed-zeros-fp-math", "true");
1957
1958 // TODO: Reciprocal estimate codegen options should apply to instructions?
1959 const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals;
1960 if (!Recips.empty())
1961 FuncAttrs.addAttribute("reciprocal-estimates",
1962 llvm::join(Recips, ","));
1963
1964 if (!CodeGenOpts.PreferVectorWidth.empty() &&
1965 CodeGenOpts.PreferVectorWidth != "none")
1966 FuncAttrs.addAttribute("prefer-vector-width",
1967 CodeGenOpts.PreferVectorWidth);
1968
1969 if (CodeGenOpts.StackRealignment)
1970 FuncAttrs.addAttribute("stackrealign");
1971 if (CodeGenOpts.Backchain)
1972 FuncAttrs.addAttribute("backchain");
1973 if (CodeGenOpts.EnableSegmentedStacks)
1974 FuncAttrs.addAttribute("split-stack");
1975
1976 if (CodeGenOpts.SpeculativeLoadHardening)
1977 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
1978
1979 // Add zero-call-used-regs attribute.
1980 switch (CodeGenOpts.getZeroCallUsedRegs()) {
1981 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Skip:
1982 FuncAttrs.removeAttribute("zero-call-used-regs");
1983 break;
1984 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPRArg:
1985 FuncAttrs.addAttribute("zero-call-used-regs", "used-gpr-arg");
1986 break;
1987 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPR:
1988 FuncAttrs.addAttribute("zero-call-used-regs", "used-gpr");
1989 break;
1990 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedArg:
1991 FuncAttrs.addAttribute("zero-call-used-regs", "used-arg");
1992 break;
1993 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Used:
1994 FuncAttrs.addAttribute("zero-call-used-regs", "used");
1995 break;
1996 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPRArg:
1997 FuncAttrs.addAttribute("zero-call-used-regs", "all-gpr-arg");
1998 break;
1999 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPR:
2000 FuncAttrs.addAttribute("zero-call-used-regs", "all-gpr");
2001 break;
2002 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllArg:
2003 FuncAttrs.addAttribute("zero-call-used-regs", "all-arg");
2004 break;
2005 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::All:
2006 FuncAttrs.addAttribute("zero-call-used-regs", "all");
2007 break;
2008 }
2009 }
2010
2011 if (LangOpts.assumeFunctionsAreConvergent()) {
2012 // Conservatively, mark all functions and calls in CUDA and OpenCL as
2013 // convergent (meaning, they may call an intrinsically convergent op, such
2014 // as __syncthreads() / barrier(), and so can't have certain optimizations
2015 // applied around them). LLVM will remove this attribute where it safely
2016 // can.
2017 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
2018 }
2019
2020 // TODO: NoUnwind attribute should be added for other GPU modes HIP,
2021 // OpenMP offload. AFAIK, neither of them support exceptions in device code.
2022 if ((LangOpts.CUDA && LangOpts.CUDAIsDevice) || LangOpts.OpenCL ||
2023 LangOpts.SYCLIsDevice) {
2024 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2025 }
2026
2027 for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) {
2028 StringRef Var, Value;
2029 std::tie(Var, Value) = Attr.split('=');
2030 FuncAttrs.addAttribute(Var, Value);
2031 }
2032}
2033
2034/// Merges `target-features` from \TargetOpts and \F, and sets the result in
2035/// \FuncAttr
2036/// * features from \F are always kept
2037/// * a feature from \TargetOpts is kept if itself and its opposite are absent
2038/// from \F
2039static void
2041 const llvm::Function &F,
2042 const TargetOptions &TargetOpts) {
2043 auto FFeatures = F.getFnAttribute("target-features");
2044
2045 llvm::StringSet<> MergedNames;
2046 SmallVector<StringRef> MergedFeatures;
2047 MergedFeatures.reserve(TargetOpts.Features.size());
2048
2049 auto AddUnmergedFeatures = [&](auto &&FeatureRange) {
2050 for (StringRef Feature : FeatureRange) {
2051 if (Feature.empty())
2052 continue;
2053 assert(Feature[0] == '+' || Feature[0] == '-');
2054 StringRef Name = Feature.drop_front(1);
2055 bool Merged = !MergedNames.insert(Name).second;
2056 if (!Merged)
2057 MergedFeatures.push_back(Feature);
2058 }
2059 };
2060
2061 if (FFeatures.isValid())
2062 AddUnmergedFeatures(llvm::split(FFeatures.getValueAsString(), ','));
2063 AddUnmergedFeatures(TargetOpts.Features);
2064
2065 if (!MergedFeatures.empty()) {
2066 llvm::sort(MergedFeatures);
2067 FuncAttr.addAttribute("target-features", llvm::join(MergedFeatures, ","));
2068 }
2069}
2070
2072 llvm::Function &F, const CodeGenOptions &CodeGenOpts,
2073 const LangOptions &LangOpts, const TargetOptions &TargetOpts,
2074 bool WillInternalize) {
2075
2076 llvm::AttrBuilder FuncAttrs(F.getContext());
2077 // Here we only extract the options that are relevant compared to the version
2078 // from GetCPUAndFeaturesAttributes.
2079 if (!TargetOpts.CPU.empty())
2080 FuncAttrs.addAttribute("target-cpu", TargetOpts.CPU);
2081 if (!TargetOpts.TuneCPU.empty())
2082 FuncAttrs.addAttribute("tune-cpu", TargetOpts.TuneCPU);
2083
2084 ::getTrivialDefaultFunctionAttributes(F.getName(), F.hasOptNone(),
2085 CodeGenOpts, LangOpts,
2086 /*AttrOnCallSite=*/false, FuncAttrs);
2087
2088 if (!WillInternalize && F.isInterposable()) {
2089 // Do not promote "dynamic" denormal-fp-math to this translation unit's
2090 // setting for weak functions that won't be internalized. The user has no
2091 // real control for how builtin bitcode is linked, so we shouldn't assume
2092 // later copies will use a consistent mode.
2093 F.addFnAttrs(FuncAttrs);
2094 return;
2095 }
2096
2097 llvm::AttributeMask AttrsToRemove;
2098
2099 llvm::DenormalMode DenormModeToMerge = F.getDenormalModeRaw();
2100 llvm::DenormalMode DenormModeToMergeF32 = F.getDenormalModeF32Raw();
2101 llvm::DenormalMode Merged =
2102 CodeGenOpts.FPDenormalMode.mergeCalleeMode(DenormModeToMerge);
2103 llvm::DenormalMode MergedF32 = CodeGenOpts.FP32DenormalMode;
2104
2105 if (DenormModeToMergeF32.isValid()) {
2106 MergedF32 =
2107 CodeGenOpts.FP32DenormalMode.mergeCalleeMode(DenormModeToMergeF32);
2108 }
2109
2110 if (Merged == llvm::DenormalMode::getDefault()) {
2111 AttrsToRemove.addAttribute("denormal-fp-math");
2112 } else if (Merged != DenormModeToMerge) {
2113 // Overwrite existing attribute
2114 FuncAttrs.addAttribute("denormal-fp-math",
2115 CodeGenOpts.FPDenormalMode.str());
2116 }
2117
2118 if (MergedF32 == llvm::DenormalMode::getDefault()) {
2119 AttrsToRemove.addAttribute("denormal-fp-math-f32");
2120 } else if (MergedF32 != DenormModeToMergeF32) {
2121 // Overwrite existing attribute
2122 FuncAttrs.addAttribute("denormal-fp-math-f32",
2123 CodeGenOpts.FP32DenormalMode.str());
2124 }
2125
2126 F.removeFnAttrs(AttrsToRemove);
2127 addDenormalModeAttrs(Merged, MergedF32, FuncAttrs);
2128
2129 overrideFunctionFeaturesWithTargetFeatures(FuncAttrs, F, TargetOpts);
2130
2131 F.addFnAttrs(FuncAttrs);
2132}
2133
2134void CodeGenModule::getTrivialDefaultFunctionAttributes(
2135 StringRef Name, bool HasOptnone, bool AttrOnCallSite,
2136 llvm::AttrBuilder &FuncAttrs) {
2137 ::getTrivialDefaultFunctionAttributes(Name, HasOptnone, getCodeGenOpts(),
2138 getLangOpts(), AttrOnCallSite,
2139 FuncAttrs);
2140}
2141
2142void CodeGenModule::getDefaultFunctionAttributes(StringRef Name,
2143 bool HasOptnone,
2144 bool AttrOnCallSite,
2145 llvm::AttrBuilder &FuncAttrs) {
2146 getTrivialDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite,
2147 FuncAttrs);
2148 // If we're just getting the default, get the default values for mergeable
2149 // attributes.
2150 if (!AttrOnCallSite)
2151 addMergableDefaultFunctionAttributes(CodeGenOpts, FuncAttrs);
2152}
2153
2155 llvm::AttrBuilder &attrs) {
2156 getDefaultFunctionAttributes(/*function name*/ "", /*optnone*/ false,
2157 /*for call*/ false, attrs);
2158 GetCPUAndFeaturesAttributes(GlobalDecl(), attrs);
2159}
2160
2161static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs,
2162 const LangOptions &LangOpts,
2163 const NoBuiltinAttr *NBA = nullptr) {
2164 auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) {
2165 SmallString<32> AttributeName;
2166 AttributeName += "no-builtin-";
2167 AttributeName += BuiltinName;
2168 FuncAttrs.addAttribute(AttributeName);
2169 };
2170
2171 // First, handle the language options passed through -fno-builtin.
2172 if (LangOpts.NoBuiltin) {
2173 // -fno-builtin disables them all.
2174 FuncAttrs.addAttribute("no-builtins");
2175 return;
2176 }
2177
2178 // Then, add attributes for builtins specified through -fno-builtin-<name>.
2179 llvm::for_each(LangOpts.NoBuiltinFuncs, AddNoBuiltinAttr);
2180
2181 // Now, let's check the __attribute__((no_builtin("...")) attribute added to
2182 // the source.
2183 if (!NBA)
2184 return;
2185
2186 // If there is a wildcard in the builtin names specified through the
2187 // attribute, disable them all.
2188 if (llvm::is_contained(NBA->builtinNames(), "*")) {
2189 FuncAttrs.addAttribute("no-builtins");
2190 return;
2191 }
2192
2193 // And last, add the rest of the builtin names.
2194 llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr);
2195}
2196
2198 const llvm::DataLayout &DL, const ABIArgInfo &AI,
2199 bool CheckCoerce = true) {
2200 llvm::Type *Ty = Types.ConvertTypeForMem(QTy);
2201 if (AI.getKind() == ABIArgInfo::Indirect ||
2203 return true;
2204 if (AI.getKind() == ABIArgInfo::Extend)
2205 return true;
2206 if (!DL.typeSizeEqualsStoreSize(Ty))
2207 // TODO: This will result in a modest amount of values not marked noundef
2208 // when they could be. We care about values that *invisibly* contain undef
2209 // bits from the perspective of LLVM IR.
2210 return false;
2211 if (CheckCoerce && AI.canHaveCoerceToType()) {
2212 llvm::Type *CoerceTy = AI.getCoerceToType();
2213 if (llvm::TypeSize::isKnownGT(DL.getTypeSizeInBits(CoerceTy),
2214 DL.getTypeSizeInBits(Ty)))
2215 // If we're coercing to a type with a greater size than the canonical one,
2216 // we're introducing new undef bits.
2217 // Coercing to a type of smaller or equal size is ok, as we know that
2218 // there's no internal padding (typeSizeEqualsStoreSize).
2219 return false;
2220 }
2221 if (QTy->isBitIntType())
2222 return true;
2223 if (QTy->isReferenceType())
2224 return true;
2225 if (QTy->isNullPtrType())
2226 return false;
2227 if (QTy->isMemberPointerType())
2228 // TODO: Some member pointers are `noundef`, but it depends on the ABI. For
2229 // now, never mark them.
2230 return false;
2231 if (QTy->isScalarType()) {
2232 if (const ComplexType *Complex = dyn_cast<ComplexType>(QTy))
2233 return DetermineNoUndef(Complex->getElementType(), Types, DL, AI, false);
2234 return true;
2235 }
2236 if (const VectorType *Vector = dyn_cast<VectorType>(QTy))
2237 return DetermineNoUndef(Vector->getElementType(), Types, DL, AI, false);
2238 if (const MatrixType *Matrix = dyn_cast<MatrixType>(QTy))
2239 return DetermineNoUndef(Matrix->getElementType(), Types, DL, AI, false);
2240 if (const ArrayType *Array = dyn_cast<ArrayType>(QTy))
2241 return DetermineNoUndef(Array->getElementType(), Types, DL, AI, false);
2242
2243 // TODO: Some structs may be `noundef`, in specific situations.
2244 return false;
2245}
2246
2247/// Check if the argument of a function has maybe_undef attribute.
2248static bool IsArgumentMaybeUndef(const Decl *TargetDecl,
2249 unsigned NumRequiredArgs, unsigned ArgNo) {
2250 const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
2251 if (!FD)
2252 return false;
2253
2254 // Assume variadic arguments do not have maybe_undef attribute.
2255 if (ArgNo >= NumRequiredArgs)
2256 return false;
2257
2258 // Check if argument has maybe_undef attribute.
2259 if (ArgNo < FD->getNumParams()) {
2260 const ParmVarDecl *Param = FD->getParamDecl(ArgNo);
2261 if (Param && Param->hasAttr<MaybeUndefAttr>())
2262 return true;
2263 }
2264
2265 return false;
2266}
2267
2268/// Test if it's legal to apply nofpclass for the given parameter type and it's
2269/// lowered IR type.
2270static bool canApplyNoFPClass(const ABIArgInfo &AI, QualType ParamType,
2271 bool IsReturn) {
2272 // Should only apply to FP types in the source, not ABI promoted.
2273 if (!ParamType->hasFloatingRepresentation())
2274 return false;
2275
2276 // The promoted-to IR type also needs to support nofpclass.
2277 llvm::Type *IRTy = AI.getCoerceToType();
2278 if (llvm::AttributeFuncs::isNoFPClassCompatibleType(IRTy))
2279 return true;
2280
2281 if (llvm::StructType *ST = dyn_cast<llvm::StructType>(IRTy)) {
2282 return !IsReturn && AI.getCanBeFlattened() &&
2283 llvm::all_of(ST->elements(), [](llvm::Type *Ty) {
2284 return llvm::AttributeFuncs::isNoFPClassCompatibleType(Ty);
2285 });
2286 }
2287
2288 return false;
2289}
2290
2291/// Return the nofpclass mask that can be applied to floating-point parameters.
2292static llvm::FPClassTest getNoFPClassTestMask(const LangOptions &LangOpts) {
2293 llvm::FPClassTest Mask = llvm::fcNone;
2294 if (LangOpts.NoHonorInfs)
2295 Mask |= llvm::fcInf;
2296 if (LangOpts.NoHonorNaNs)
2297 Mask |= llvm::fcNan;
2298 return Mask;
2299}
2300
2302 CGCalleeInfo CalleeInfo,
2303 llvm::AttributeList &Attrs) {
2304 if (Attrs.getMemoryEffects().getModRef() == llvm::ModRefInfo::NoModRef) {
2305 Attrs = Attrs.removeFnAttribute(getLLVMContext(), llvm::Attribute::Memory);
2306 llvm::Attribute MemoryAttr = llvm::Attribute::getWithMemoryEffects(
2307 getLLVMContext(), llvm::MemoryEffects::writeOnly());
2308 Attrs = Attrs.addFnAttribute(getLLVMContext(), MemoryAttr);
2309 }
2310}
2311
2312/// Construct the IR attribute list of a function or call.
2313///
2314/// When adding an attribute, please consider where it should be handled:
2315///
2316/// - getDefaultFunctionAttributes is for attributes that are essentially
2317/// part of the global target configuration (but perhaps can be
2318/// overridden on a per-function basis). Adding attributes there
2319/// will cause them to also be set in frontends that build on Clang's
2320/// target-configuration logic, as well as for code defined in library
2321/// modules such as CUDA's libdevice.
2322///
2323/// - ConstructAttributeList builds on top of getDefaultFunctionAttributes
2324/// and adds declaration-specific, convention-specific, and
2325/// frontend-specific logic. The last is of particular importance:
2326/// attributes that restrict how the frontend generates code must be
2327/// added here rather than getDefaultFunctionAttributes.
2328///
2330 const CGFunctionInfo &FI,
2331 CGCalleeInfo CalleeInfo,
2332 llvm::AttributeList &AttrList,
2333 unsigned &CallingConv,
2334 bool AttrOnCallSite, bool IsThunk) {
2335 llvm::AttrBuilder FuncAttrs(getLLVMContext());
2336 llvm::AttrBuilder RetAttrs(getLLVMContext());
2337
2338 // Collect function IR attributes from the CC lowering.
2339 // We'll collect the paramete and result attributes later.
2341 if (FI.isNoReturn())
2342 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2343 if (FI.isCmseNSCall())
2344 FuncAttrs.addAttribute("cmse_nonsecure_call");
2345
2346 // Collect function IR attributes from the callee prototype if we have one.
2348 CalleeInfo.getCalleeFunctionProtoType());
2349
2350 const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl();
2351
2352 // Attach assumption attributes to the declaration. If this is a call
2353 // site, attach assumptions from the caller to the call as well.
2354 AddAttributesFromOMPAssumes(FuncAttrs, TargetDecl);
2355
2356 bool HasOptnone = false;
2357 // The NoBuiltinAttr attached to the target FunctionDecl.
2358 const NoBuiltinAttr *NBA = nullptr;
2359
2360 // Some ABIs may result in additional accesses to arguments that may
2361 // otherwise not be present.
2362 auto AddPotentialArgAccess = [&]() {
2363 llvm::Attribute A = FuncAttrs.getAttribute(llvm::Attribute::Memory);
2364 if (A.isValid())
2365 FuncAttrs.addMemoryAttr(A.getMemoryEffects() |
2366 llvm::MemoryEffects::argMemOnly());
2367 };
2368
2369 // Collect function IR attributes based on declaration-specific
2370 // information.
2371 // FIXME: handle sseregparm someday...
2372 if (TargetDecl) {
2373 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
2374 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
2375 if (TargetDecl->hasAttr<NoThrowAttr>())
2376 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2377 if (TargetDecl->hasAttr<NoReturnAttr>())
2378 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2379 if (TargetDecl->hasAttr<ColdAttr>())
2380 FuncAttrs.addAttribute(llvm::Attribute::Cold);
2381 if (TargetDecl->hasAttr<HotAttr>())
2382 FuncAttrs.addAttribute(llvm::Attribute::Hot);
2383 if (TargetDecl->hasAttr<NoDuplicateAttr>())
2384 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
2385 if (TargetDecl->hasAttr<ConvergentAttr>())
2386 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
2387
2388 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2390 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
2391 if (AttrOnCallSite && Fn->isReplaceableGlobalAllocationFunction()) {
2392 // A sane operator new returns a non-aliasing pointer.
2393 auto Kind = Fn->getDeclName().getCXXOverloadedOperator();
2394 if (getCodeGenOpts().AssumeSaneOperatorNew &&
2395 (Kind == OO_New || Kind == OO_Array_New))
2396 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2397 }
2398 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
2399 const bool IsVirtualCall = MD && MD->isVirtual();
2400 // Don't use [[noreturn]], _Noreturn or [[no_builtin]] for a call to a
2401 // virtual function. These attributes are not inherited by overloads.
2402 if (!(AttrOnCallSite && IsVirtualCall)) {
2403 if (Fn->isNoReturn())
2404 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2405 NBA = Fn->getAttr<NoBuiltinAttr>();
2406 }
2407 }
2408
2409 if (isa<FunctionDecl>(TargetDecl) || isa<VarDecl>(TargetDecl)) {
2410 // Only place nomerge attribute on call sites, never functions. This
2411 // allows it to work on indirect virtual function calls.
2412 if (AttrOnCallSite && TargetDecl->hasAttr<NoMergeAttr>())
2413 FuncAttrs.addAttribute(llvm::Attribute::NoMerge);
2414 }
2415
2416 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
2417 if (TargetDecl->hasAttr<ConstAttr>()) {
2418 FuncAttrs.addMemoryAttr(llvm::MemoryEffects::none());
2419 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2420 // gcc specifies that 'const' functions have greater restrictions than
2421 // 'pure' functions, so they also cannot have infinite loops.
2422 FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
2423 } else if (TargetDecl->hasAttr<PureAttr>()) {
2424 FuncAttrs.addMemoryAttr(llvm::MemoryEffects::readOnly());
2425 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2426 // gcc specifies that 'pure' functions cannot have infinite loops.
2427 FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
2428 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
2429 FuncAttrs.addMemoryAttr(llvm::MemoryEffects::inaccessibleOrArgMemOnly());
2430 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2431 }
2432 if (TargetDecl->hasAttr<RestrictAttr>())
2433 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2434 if (TargetDecl->hasAttr<ReturnsNonNullAttr>() &&
2435 !CodeGenOpts.NullPointerIsValid)
2436 RetAttrs.addAttribute(llvm::Attribute::NonNull);
2437 if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
2438 FuncAttrs.addAttribute("no_caller_saved_registers");
2439 if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>())
2440 FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck);
2441 if (TargetDecl->hasAttr<LeafAttr>())
2442 FuncAttrs.addAttribute(llvm::Attribute::NoCallback);
2443
2444 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
2445 if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
2446 std::optional<unsigned> NumElemsParam;
2447 if (AllocSize->getNumElemsParam().isValid())
2448 NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
2449 FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(),
2450 NumElemsParam);
2451 }
2452
2453 if (TargetDecl->hasAttr<OpenCLKernelAttr>()) {
2454 if (getLangOpts().OpenCLVersion <= 120) {
2455 // OpenCL v1.2 Work groups are always uniform
2456 FuncAttrs.addAttribute("uniform-work-group-size", "true");
2457 } else {
2458 // OpenCL v2.0 Work groups may be whether uniform or not.
2459 // '-cl-uniform-work-group-size' compile option gets a hint
2460 // to the compiler that the global work-size be a multiple of
2461 // the work-group size specified to clEnqueueNDRangeKernel
2462 // (i.e. work groups are uniform).
2463 FuncAttrs.addAttribute(
2464 "uniform-work-group-size",
2465 llvm::toStringRef(getLangOpts().OffloadUniformBlock));
2466 }
2467 }
2468
2469 if (TargetDecl->hasAttr<CUDAGlobalAttr>() &&
2470 getLangOpts().OffloadUniformBlock)
2471 FuncAttrs.addAttribute("uniform-work-group-size", "true");
2472
2473 if (TargetDecl->hasAttr<ArmLocallyStreamingAttr>())
2474 FuncAttrs.addAttribute("aarch64_pstate_sm_body");
2475 }
2476
2477 // Attach "no-builtins" attributes to:
2478 // * call sites: both `nobuiltin` and "no-builtins" or "no-builtin-<name>".
2479 // * definitions: "no-builtins" or "no-builtin-<name>" only.
2480 // The attributes can come from:
2481 // * LangOpts: -ffreestanding, -fno-builtin, -fno-builtin-<name>
2482 // * FunctionDecl attributes: __attribute__((no_builtin(...)))
2483 addNoBuiltinAttributes(FuncAttrs, getLangOpts(), NBA);
2484
2485 // Collect function IR attributes based on global settiings.
2486 getDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
2487
2488 // Override some default IR attributes based on declaration-specific
2489 // information.
2490 if (TargetDecl) {
2491 if (TargetDecl->hasAttr<NoSpeculativeLoadHardeningAttr>())
2492 FuncAttrs.removeAttribute(llvm::Attribute::SpeculativeLoadHardening);
2493 if (TargetDecl->hasAttr<SpeculativeLoadHardeningAttr>())
2494 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
2495 if (TargetDecl->hasAttr<NoSplitStackAttr>())
2496 FuncAttrs.removeAttribute("split-stack");
2497 if (TargetDecl->hasAttr<ZeroCallUsedRegsAttr>()) {
2498 // A function "__attribute__((...))" overrides the command-line flag.
2499 auto Kind =
2500 TargetDecl->getAttr<ZeroCallUsedRegsAttr>()->getZeroCallUsedRegs();
2501 FuncAttrs.removeAttribute("zero-call-used-regs");
2502 FuncAttrs.addAttribute(
2503 "zero-call-used-regs",
2504 ZeroCallUsedRegsAttr::ConvertZeroCallUsedRegsKindToStr(Kind));
2505 }
2506
2507 // Add NonLazyBind attribute to function declarations when -fno-plt
2508 // is used.
2509 // FIXME: what if we just haven't processed the function definition
2510 // yet, or if it's an external definition like C99 inline?
2511 if (CodeGenOpts.NoPLT) {
2512 if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2513 if (!Fn->isDefined() && !AttrOnCallSite) {
2514 FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind);
2515 }
2516 }
2517 }
2518 }
2519
2520 // Add "sample-profile-suffix-elision-policy" attribute for internal linkage
2521 // functions with -funique-internal-linkage-names.
2522 if (TargetDecl && CodeGenOpts.UniqueInternalLinkageNames) {
2523 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
2524 if (!FD->isExternallyVisible())
2525 FuncAttrs.addAttribute("sample-profile-suffix-elision-policy",
2526 "selected");
2527 }
2528 }
2529
2530 // Collect non-call-site function IR attributes from declaration-specific
2531 // information.
2532 if (!AttrOnCallSite) {
2533 if (TargetDecl && TargetDecl->hasAttr<CmseNSEntryAttr>())
2534 FuncAttrs.addAttribute("cmse_nonsecure_entry");
2535
2536 // Whether tail calls are enabled.
2537 auto shouldDisableTailCalls = [&] {
2538 // Should this be honored in getDefaultFunctionAttributes?
2539 if (CodeGenOpts.DisableTailCalls)
2540 return true;
2541
2542 if (!TargetDecl)
2543 return false;
2544
2545 if (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
2546 TargetDecl->hasAttr<AnyX86InterruptAttr>())
2547 return true;
2548
2549 if (CodeGenOpts.NoEscapingBlockTailCalls) {
2550 if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl))
2551 if (!BD->doesNotEscape())
2552 return true;
2553 }
2554
2555 return false;
2556 };
2557 if (shouldDisableTailCalls())
2558 FuncAttrs.addAttribute("disable-tail-calls", "true");
2559
2560 // CPU/feature overrides. addDefaultFunctionDefinitionAttributes
2561 // handles these separately to set them based on the global defaults.
2562 GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs);
2563 }
2564
2565 // Collect attributes from arguments and return values.
2566 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
2567
2568 QualType RetTy = FI.getReturnType();
2569 const ABIArgInfo &RetAI = FI.getReturnInfo();
2570 const llvm::DataLayout &DL = getDataLayout();
2571
2572 // Determine if the return type could be partially undef
2573 if (CodeGenOpts.EnableNoundefAttrs &&
2574 HasStrictReturn(*this, RetTy, TargetDecl)) {
2575 if (!RetTy->isVoidType() && RetAI.getKind() != ABIArgInfo::Indirect &&
2576 DetermineNoUndef(RetTy, getTypes(), DL, RetAI))
2577 RetAttrs.addAttribute(llvm::Attribute::NoUndef);
2578 }
2579
2580 switch (RetAI.getKind()) {
2581 case ABIArgInfo::Extend:
2582 if (RetAI.isSignExt())
2583 RetAttrs.addAttribute(llvm::Attribute::SExt);
2584 else
2585 RetAttrs.addAttribute(llvm::Attribute::ZExt);
2586 [[fallthrough]];
2587 case ABIArgInfo::Direct:
2588 if (RetAI.getInReg())
2589 RetAttrs.addAttribute(llvm::Attribute::InReg);
2590
2591 if (canApplyNoFPClass(RetAI, RetTy, true))
2592 RetAttrs.addNoFPClassAttr(getNoFPClassTestMask(getLangOpts()));
2593
2594 break;
2595 case ABIArgInfo::Ignore:
2596 break;
2597
2599 case ABIArgInfo::Indirect: {
2600 // inalloca and sret disable readnone and readonly
2601 AddPotentialArgAccess();
2602 break;
2603 }
2604
2606 break;
2607
2608 case ABIArgInfo::Expand:
2610 llvm_unreachable("Invalid ABI kind for return argument");
2611 }
2612
2613 if (!IsThunk) {
2614 // FIXME: fix this properly, https://reviews.llvm.org/D100388
2615 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
2616 QualType PTy = RefTy->getPointeeType();
2617 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2618 RetAttrs.addDereferenceableAttr(
2619 getMinimumObjectSize(PTy).getQuantity());
2620 if (getTypes().getTargetAddressSpace(PTy) == 0 &&
2621 !CodeGenOpts.NullPointerIsValid)
2622 RetAttrs.addAttribute(llvm::Attribute::NonNull);
2623 if (PTy->isObjectType()) {
2624 llvm::Align Alignment =
2626 RetAttrs.addAlignmentAttr(Alignment);
2627 }
2628 }
2629 }
2630
2631 bool hasUsedSRet = false;
2632 SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs());
2633
2634 // Attach attributes to sret.
2635 if (IRFunctionArgs.hasSRetArg()) {
2636 llvm::AttrBuilder SRETAttrs(getLLVMContext());
2637 SRETAttrs.addStructRetAttr(getTypes().ConvertTypeForMem(RetTy));
2638 SRETAttrs.addAttribute(llvm::Attribute::Writable);
2639 SRETAttrs.addAttribute(llvm::Attribute::DeadOnUnwind);
2640 hasUsedSRet = true;
2641 if (RetAI.getInReg())
2642 SRETAttrs.addAttribute(llvm::Attribute::InReg);
2643 SRETAttrs.addAlignmentAttr(RetAI.getIndirectAlign().getQuantity());
2644 ArgAttrs[IRFunctionArgs.getSRetArgNo()] =
2645 llvm::AttributeSet::get(getLLVMContext(), SRETAttrs);
2646 }
2647
2648 // Attach attributes to inalloca argument.
2649 if (IRFunctionArgs.hasInallocaArg()) {
2650 llvm::AttrBuilder Attrs(getLLVMContext());
2651 Attrs.addInAllocaAttr(FI.getArgStruct());
2652 ArgAttrs[IRFunctionArgs.getInallocaArgNo()] =
2653 llvm::AttributeSet::get(getLLVMContext(), Attrs);
2654 }
2655
2656 // Apply `nonnull`, `dereferencable(N)` and `align N` to the `this` argument,
2657 // unless this is a thunk function.
2658 // FIXME: fix this properly, https://reviews.llvm.org/D100388
2659 if (FI.isInstanceMethod() && !IRFunctionArgs.hasInallocaArg() &&
2660 !FI.arg_begin()->type->isVoidPointerType() && !IsThunk) {
2661 auto IRArgs = IRFunctionArgs.getIRArgs(0);
2662
2663 assert(IRArgs.second == 1 && "Expected only a single `this` pointer.");
2664
2665 llvm::AttrBuilder Attrs(getLLVMContext());
2666
2667 QualType ThisTy =
2669
2670 if (!CodeGenOpts.NullPointerIsValid &&
2671 getTypes().getTargetAddressSpace(FI.arg_begin()->type) == 0) {
2672 Attrs.addAttribute(llvm::Attribute::NonNull);
2673 Attrs.addDereferenceableAttr(getMinimumObjectSize(ThisTy).getQuantity());
2674 } else {
2675 // FIXME dereferenceable should be correct here, regardless of
2676 // NullPointerIsValid. However, dereferenceable currently does not always
2677 // respect NullPointerIsValid and may imply nonnull and break the program.
2678 // See https://reviews.llvm.org/D66618 for discussions.
2679 Attrs.addDereferenceableOrNullAttr(
2682 .getQuantity());
2683 }
2684
2685 llvm::Align Alignment =
2686 getNaturalTypeAlignment(ThisTy, /*BaseInfo=*/nullptr,
2687 /*TBAAInfo=*/nullptr, /*forPointeeType=*/true)
2688 .getAsAlign();
2689 Attrs.addAlignmentAttr(Alignment);
2690
2691 ArgAttrs[IRArgs.first] = llvm::AttributeSet::get(getLLVMContext(), Attrs);
2692 }
2693
2694 unsigned ArgNo = 0;
2696 E = FI.arg_end();
2697 I != E; ++I, ++ArgNo) {
2698 QualType ParamType = I->type;
2699 const ABIArgInfo &AI = I->info;
2700 llvm::AttrBuilder Attrs(getLLVMContext());
2701
2702 // Add attribute for padding argument, if necessary.
2703 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
2704 if (AI.getPaddingInReg()) {
2705 ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2706 llvm::AttributeSet::get(
2708 llvm::AttrBuilder(getLLVMContext()).addAttribute(llvm::Attribute::InReg));
2709 }
2710 }
2711
2712 // Decide whether the argument we're handling could be partially undef
2713 if (CodeGenOpts.EnableNoundefAttrs &&
2714 DetermineNoUndef(ParamType, getTypes(), DL, AI)) {
2715 Attrs.addAttribute(llvm::Attribute::NoUndef);
2716 }
2717
2718 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
2719 // have the corresponding parameter variable. It doesn't make
2720 // sense to do it here because parameters are so messed up.
2721 switch (AI.getKind()) {
2722 case ABIArgInfo::Extend:
2723 if (AI.isSignExt())
2724 Attrs.addAttribute(llvm::Attribute::SExt);
2725 else
2726 Attrs.addAttribute(llvm::Attribute::ZExt);
2727 [[fallthrough]];
2728 case ABIArgInfo::Direct:
2729 if (ArgNo == 0 && FI.isChainCall())
2730 Attrs.addAttribute(llvm::Attribute::Nest);
2731 else if (AI.getInReg())
2732 Attrs.addAttribute(llvm::Attribute::InReg);
2733 Attrs.addStackAlignmentAttr(llvm::MaybeAlign(AI.getDirectAlign()));
2734
2735 if (canApplyNoFPClass(AI, ParamType, false))
2736 Attrs.addNoFPClassAttr(getNoFPClassTestMask(getLangOpts()));
2737 break;
2738 case ABIArgInfo::Indirect: {
2739 if (AI.getInReg())
2740 Attrs.addAttribute(llvm::Attribute::InReg);
2741
2742 if (AI.getIndirectByVal())
2743 Attrs.addByValAttr(getTypes().ConvertTypeForMem(ParamType));
2744
2745 auto *Decl = ParamType->getAsRecordDecl();
2746 if (CodeGenOpts.PassByValueIsNoAlias && Decl &&
2747 Decl->getArgPassingRestrictions() ==
2749 // When calling the function, the pointer passed in will be the only
2750 // reference to the underlying object. Mark it accordingly.
2751 Attrs.addAttribute(llvm::Attribute::NoAlias);
2752
2753 // TODO: We could add the byref attribute if not byval, but it would
2754 // require updating many testcases.
2755
2756 CharUnits Align = AI.getIndirectAlign();
2757
2758 // In a byval argument, it is important that the required
2759 // alignment of the type is honored, as LLVM might be creating a
2760 // *new* stack object, and needs to know what alignment to give
2761 // it. (Sometimes it can deduce a sensible alignment on its own,
2762 // but not if clang decides it must emit a packed struct, or the
2763 // user specifies increased alignment requirements.)
2764 //
2765 // This is different from indirect *not* byval, where the object
2766 // exists already, and the align attribute is purely
2767 // informative.
2768 assert(!Align.isZero());
2769
2770 // For now, only add this when we have a byval argument.
2771 // TODO: be less lazy about updating test cases.
2772 if (AI.getIndirectByVal())
2773 Attrs.addAlignmentAttr(Align.getQuantity());
2774
2775 // byval disables readnone and readonly.
2776 AddPotentialArgAccess();
2777 break;
2778 }
2780 CharUnits Align = AI.getIndirectAlign();
2781 Attrs.addByRefAttr(getTypes().ConvertTypeForMem(ParamType));
2782 Attrs.addAlignmentAttr(Align.getQuantity());
2783 break;
2784 }
2785 case ABIArgInfo::Ignore:
2786 case ABIArgInfo::Expand:
2788 break;
2789
2791 // inalloca disables readnone and readonly.
2792 AddPotentialArgAccess();
2793 continue;
2794 }
2795
2796 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
2797 QualType PTy = RefTy->getPointeeType();
2798 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2799 Attrs.addDereferenceableAttr(
2800 getMinimumObjectSize(PTy).getQuantity());
2801 if (getTypes().getTargetAddressSpace(PTy) == 0 &&
2802 !CodeGenOpts.NullPointerIsValid)
2803 Attrs.addAttribute(llvm::Attribute::NonNull);
2804 if (PTy->isObjectType()) {
2805 llvm::Align Alignment =
2807 Attrs.addAlignmentAttr(Alignment);
2808 }
2809 }
2810
2811 // From OpenCL spec v3.0.10 section 6.3.5 Alignment of Types:
2812 // > For arguments to a __kernel function declared to be a pointer to a
2813 // > data type, the OpenCL compiler can assume that the pointee is always
2814 // > appropriately aligned as required by the data type.
2815 if (TargetDecl && TargetDecl->hasAttr<OpenCLKernelAttr>() &&
2816 ParamType->isPointerType()) {
2817 QualType PTy = ParamType->getPointeeType();
2818 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2819 llvm::Align Alignment =
2821 Attrs.addAlignmentAttr(Alignment);
2822 }
2823 }
2824
2825 switch (FI.getExtParameterInfo(ArgNo).getABI()) {
2827 break;
2828
2830 // Add 'sret' if we haven't already used it for something, but
2831 // only if the result is void.
2832 if (!hasUsedSRet && RetTy->isVoidType()) {
2833 Attrs.addStructRetAttr(getTypes().ConvertTypeForMem(ParamType));
2834 hasUsedSRet = true;
2835 }
2836
2837 // Add 'noalias' in either case.
2838 Attrs.addAttribute(llvm::Attribute::NoAlias);
2839
2840 // Add 'dereferenceable' and 'alignment'.
2841 auto PTy = ParamType->getPointeeType();
2842 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2843 auto info = getContext().getTypeInfoInChars(PTy);
2844 Attrs.addDereferenceableAttr(info.Width.getQuantity());
2845 Attrs.addAlignmentAttr(info.Align.getAsAlign());
2846 }
2847 break;
2848 }
2849
2851 Attrs.addAttribute(llvm::Attribute::SwiftError);
2852 break;
2853
2855 Attrs.addAttribute(llvm::Attribute::SwiftSelf);
2856 break;
2857
2859 Attrs.addAttribute(llvm::Attribute::SwiftAsync);
2860 break;
2861 }
2862
2863 if (FI.getExtParameterInfo(ArgNo).isNoEscape())
2864 Attrs.addAttribute(llvm::Attribute::NoCapture);
2865
2866 if (Attrs.hasAttributes()) {
2867 unsigned FirstIRArg, NumIRArgs;
2868 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2869 for (unsigned i = 0; i < NumIRArgs; i++)
2870 ArgAttrs[FirstIRArg + i] = ArgAttrs[FirstIRArg + i].addAttributes(
2871 getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), Attrs));
2872 }
2873 }
2874 assert(ArgNo == FI.arg_size());
2875
2876 AttrList = llvm::AttributeList::get(
2877 getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs),
2878 llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs);
2879}
2880
2881/// An argument came in as a promoted argument; demote it back to its
2882/// declared type.
2883static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
2884 const VarDecl *var,
2885 llvm::Value *value) {
2886 llvm::Type *varType = CGF.ConvertType(var->getType());
2887
2888 // This can happen with promotions that actually don't change the
2889 // underlying type, like the enum promotions.
2890 if (value->getType() == varType) return value;
2891
2892 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
2893 && "unexpected promotion type");
2894
2895 if (isa<llvm::IntegerType>(varType))
2896 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2897
2898 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2899}
2900
2901/// Returns the attribute (either parameter attribute, or function
2902/// attribute), which declares argument ArgNo to be non-null.
2903static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2904 QualType ArgType, unsigned ArgNo) {
2905 // FIXME: __attribute__((nonnull)) can also be applied to:
2906 // - references to pointers, where the pointee is known to be
2907 // nonnull (apparently a Clang extension)
2908 // - transparent unions containing pointers
2909 // In the former case, LLVM IR cannot represent the constraint. In
2910 // the latter case, we have no guarantee that the transparent union
2911 // is in fact passed as a pointer.
2912 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2913 return nullptr;
2914 // First, check attribute on parameter itself.
2915 if (PVD) {
2916 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2917 return ParmNNAttr;
2918 }
2919 // Check function attributes.
2920 if (!FD)
2921 return nullptr;
2922 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
2923 if (NNAttr->isNonNull(ArgNo))
2924 return NNAttr;
2925 }
2926 return nullptr;
2927}
2928
2929namespace {
2930 struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2931 Address Temp;
2932 Address Arg;
2933 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
2934 void Emit(CodeGenFunction &CGF, Flags flags) override {
2935 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2936 CGF.Builder.CreateStore(errorValue, Arg);
2937 }
2938 };
2939}
2940
2942 llvm::Function *Fn,
2943 const FunctionArgList &Args) {
2944 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
2945 // Naked functions don't have prologues.
2946 return;
2947
2948 // If this is an implicit-return-zero function, go ahead and
2949 // initialize the return value. TODO: it might be nice to have
2950 // a more general mechanism for this that didn't require synthesized
2951 // return statements.
2952 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
2953 if (FD->hasImplicitReturnZero()) {
2954 QualType RetTy = FD->getReturnType().getUnqualifiedType();
2955 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
2956 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
2958 }
2959 }
2960
2961 // FIXME: We no longer need the types from FunctionArgList; lift up and
2962 // simplify.
2963
2964 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
2965 assert(Fn->arg_size() == IRFunctionArgs.totalIRArgs());
2966
2967 // If we're using inalloca, all the memory arguments are GEPs off of the last
2968 // parameter, which is a pointer to the complete memory area.
2969 Address ArgStruct = Address::invalid();
2970 if (IRFunctionArgs.hasInallocaArg())
2971 ArgStruct = Address(Fn->getArg(IRFunctionArgs.getInallocaArgNo()),
2973
2974 // Name the struct return parameter.
2975 if (IRFunctionArgs.hasSRetArg()) {
2976 auto AI = Fn->getArg(IRFunctionArgs.getSRetArgNo());
2977 AI->setName("agg.result");
2978 AI->addAttr(llvm::Attribute::NoAlias);
2979 }
2980
2981 // Track if we received the parameter as a pointer (indirect, byval, or
2982 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
2983 // into a local alloca for us.
2985 ArgVals.reserve(Args.size());
2986
2987 // Create a pointer value for every parameter declaration. This usually
2988 // entails copying one or more LLVM IR arguments into an alloca. Don't push
2989 // any cleanups or do anything that might unwind. We do that separately, so
2990 // we can push the cleanups in the correct order for the ABI.
2991 assert(FI.arg_size() == Args.size() &&
2992 "Mismatch between function signature & arguments.");
2993 unsigned ArgNo = 0;
2995 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
2996 i != e; ++i, ++info_it, ++ArgNo) {
2997 const VarDecl *Arg = *i;
2998 const ABIArgInfo &ArgI = info_it->info;
2999
3000 bool isPromoted =
3001 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
3002 // We are converting from ABIArgInfo type to VarDecl type directly, unless
3003 // the parameter is promoted. In this case we convert to
3004 // CGFunctionInfo::ArgInfo type with subsequent argument demotion.
3005 QualType Ty = isPromoted ? info_it->type : Arg->getType();
3006 assert(hasScalarEvaluationKind(Ty) ==
3008
3009 unsigned FirstIRArg, NumIRArgs;
3010 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
3011
3012 switch (ArgI.getKind()) {
3013 case ABIArgInfo::InAlloca: {
3014 assert(NumIRArgs == 0);
3015 auto FieldIndex = ArgI.getInAllocaFieldIndex();
3016 Address V =
3017 Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName());
3018 if (ArgI.getInAllocaIndirect())
3020 getContext().getTypeAlignInChars(Ty));
3021 ArgVals.push_back(ParamValue::forIndirect(V));
3022 break;
3023 }
3024
3027 assert(NumIRArgs == 1);
3029 Fn->getArg(FirstIRArg), Ty, ArgI.getIndirectAlign(), false, nullptr,
3030 nullptr, KnownNonNull);
3031
3032 if (!hasScalarEvaluationKind(Ty)) {
3033 // Aggregates and complex variables are accessed by reference. All we
3034 // need to do is realign the value, if requested. Also, if the address
3035 // may be aliased, copy it to ensure that the parameter variable is
3036 // mutable and has a unique adress, as C requires.
3037 if (ArgI.getIndirectRealign() || ArgI.isIndirectAliased()) {
3038 RawAddress AlignedTemp = CreateMemTemp(Ty, "coerce");
3039
3040 // Copy from the incoming argument pointer to the temporary with the
3041 // appropriate alignment.
3042 //
3043 // FIXME: We should have a common utility for generating an aggregate
3044 // copy.
3047 AlignedTemp.getPointer(), AlignedTemp.getAlignment().getAsAlign(),
3048 ParamAddr.emitRawPointer(*this),
3049 ParamAddr.getAlignment().getAsAlign(),
3050 llvm::ConstantInt::get(IntPtrTy, Size.getQuantity()));
3051 ParamAddr = AlignedTemp;
3052 }
3053 ArgVals.push_back(ParamValue::forIndirect(ParamAddr));
3054 } else {
3055 // Load scalar value from indirect argument.
3056 llvm::Value *V =
3057 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc());
3058
3059 if (isPromoted)
3060 V = emitArgumentDemotion(*this, Arg, V);
3061 ArgVals.push_back(ParamValue::forDirect(V));
3062 }
3063 break;
3064 }
3065
3066 case ABIArgInfo::Extend:
3067 case ABIArgInfo::Direct: {
3068 auto AI = Fn->getArg(FirstIRArg);
3069 llvm::Type *LTy = ConvertType(Arg->getType());
3070
3071 // Prepare parameter attributes. So far, only attributes for pointer
3072 // parameters are prepared. See
3073 // http://llvm.org/docs/LangRef.html#paramattrs.
3074 if (ArgI.getDirectOffset() == 0 && LTy->isPointerTy() &&
3075 ArgI.getCoerceToType()->isPointerTy()) {
3076 assert(NumIRArgs == 1);
3077
3078 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
3079 // Set `nonnull` attribute if any.
3080 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
3081 PVD->getFunctionScopeIndex()) &&
3082 !CGM.getCodeGenOpts().NullPointerIsValid)
3083 AI->addAttr(llvm::Attribute::NonNull);
3084
3085 QualType OTy = PVD->getOriginalType();
3086 if (const auto *ArrTy =
3087 getContext().getAsConstantArrayType(OTy)) {
3088 // A C99 array parameter declaration with the static keyword also
3089 // indicates dereferenceability, and if the size is constant we can
3090 // use the dereferenceable attribute (which requires the size in
3091 // bytes).
3092 if (ArrTy->getSizeModifier() == ArraySizeModifier::Static) {
3093 QualType ETy = ArrTy->getElementType();
3094 llvm::Align Alignment =
3096 AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(Alignment));
3097 uint64_t ArrSize = ArrTy->getZExtSize();
3098 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
3099 ArrSize) {
3100 llvm::AttrBuilder Attrs(getLLVMContext());
3101 Attrs.addDereferenceableAttr(
3102 getContext().getTypeSizeInChars(ETy).getQuantity() *
3103 ArrSize);
3104 AI->addAttrs(Attrs);
3105 } else if (getContext().getTargetInfo().getNullPointerValue(
3106 ETy.getAddressSpace()) == 0 &&
3107 !CGM.getCodeGenOpts().NullPointerIsValid) {
3108 AI->addAttr(llvm::Attribute::NonNull);
3109 }
3110 }
3111 } else if (const auto *ArrTy =
3112 getContext().getAsVariableArrayType(OTy)) {
3113 // For C99 VLAs with the static keyword, we don't know the size so
3114 // we can't use the dereferenceable attribute, but in addrspace(0)
3115 // we know that it must be nonnull.
3116 if (ArrTy->getSizeModifier() == ArraySizeModifier::Static) {
3117 QualType ETy = ArrTy->getElementType();
3118 llvm::Align Alignment =
3120 AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(Alignment));
3121 if (!getTypes().getTargetAddressSpace(ETy) &&
3122 !CGM.getCodeGenOpts().NullPointerIsValid)
3123 AI->addAttr(llvm::Attribute::NonNull);
3124 }
3125 }
3126
3127 // Set `align` attribute if any.
3128 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
3129 if (!AVAttr)
3130 if (const auto *TOTy = OTy->getAs<TypedefType>())
3131 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
3132 if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) {
3133 // If alignment-assumption sanitizer is enabled, we do *not* add
3134 // alignment attribute here, but emit normal alignment assumption,
3135 // so the UBSAN check could function.
3136 llvm::ConstantInt *AlignmentCI =
3137 cast<llvm::ConstantInt>(EmitScalarExpr(AVAttr->getAlignment()));
3138 uint64_t AlignmentInt =
3139 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment);
3140 if (AI->getParamAlign().valueOrOne() < AlignmentInt) {
3141 AI->removeAttr(llvm::Attribute::AttrKind::Alignment);
3142 AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(
3143 llvm::Align(AlignmentInt)));
3144 }
3145 }
3146 }
3147
3148 // Set 'noalias' if an argument type has the `restrict` qualifier.
3149 if (Arg->getType().isRestrictQualified())
3150 AI->addAttr(llvm::Attribute::NoAlias);
3151 }
3152
3153 // Prepare the argument value. If we have the trivial case, handle it
3154 // with no muss and fuss.
3155 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
3156 ArgI.getCoerceToType() == ConvertType(Ty) &&
3157 ArgI.getDirectOffset() == 0) {
3158 assert(NumIRArgs == 1);
3159
3160 // LLVM expects swifterror parameters to be used in very restricted
3161 // ways. Copy the value into a less-restricted temporary.
3162 llvm::Value *V = AI;
3163 if (FI.getExtParameterInfo(ArgNo).getABI()
3165 QualType pointeeTy = Ty->getPointeeType();
3166 assert(pointeeTy->isPointerType());
3167 RawAddress temp =
3168 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
3170 V, pointeeTy, getContext().getTypeAlignInChars(pointeeTy));
3171 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
3172 Builder.CreateStore(incomingErrorValue, temp);
3173 V = temp.getPointer();
3174
3175 // Push a cleanup to copy the value back at the end of the function.
3176 // The convention does not guarantee that the value will be written
3177 // back if the function exits with an unwind exception.
3178 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
3179 }
3180
3181 // Ensure the argument is the correct type.
3182 if (V->getType() != ArgI.getCoerceToType())
3183 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
3184
3185 if (isPromoted)
3186 V = emitArgumentDemotion(*this, Arg, V);
3187
3188 // Because of merging of function types from multiple decls it is
3189 // possible for the type of an argument to not match the corresponding
3190 // type in the function type. Since we are codegening the callee
3191 // in here, add a cast to the argument type.
3192 llvm::Type *LTy = ConvertType(Arg->getType());
3193 if (V->getType() != LTy)
3194 V = Builder.CreateBitCast(V, LTy);
3195
3196 ArgVals.push_back(ParamValue::forDirect(V));
3197 break;
3198 }
3199
3200 // VLST arguments are coerced to VLATs at the function boundary for
3201 // ABI consistency. If this is a VLST that was coerced to
3202 // a VLAT at the function boundary and the types match up, use
3203 // llvm.vector.extract to convert back to the original VLST.
3204 if (auto *VecTyTo = dyn_cast<llvm::FixedVectorType>(ConvertType(Ty))) {
3205 llvm::Value *Coerced = Fn->getArg(FirstIRArg);
3206 if (auto *VecTyFrom =
3207 dyn_cast<llvm::ScalableVectorType>(Coerced->getType())) {
3208 // If we are casting a scalable i1 predicate vector to a fixed i8
3209 // vector, bitcast the source and use a vector extract.
3210 if (VecTyFrom->getElementType()->isIntegerTy(1) &&
3211 VecTyFrom->getElementCount().isKnownMultipleOf(8) &&
3212 VecTyTo->getElementType() == Builder.getInt8Ty()) {
3213 VecTyFrom = llvm::ScalableVectorType::get(
3214 VecTyTo->getElementType(),
3215 VecTyFrom->getElementCount().getKnownMinValue() / 8);
3216 Coerced = Builder.CreateBitCast(Coerced, VecTyFrom);
3217 }
3218 if (VecTyFrom->getElementType() == VecTyTo->getElementType()) {
3219 llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty);
3220
3221 assert(NumIRArgs == 1);
3222 Coerced->setName(Arg->getName() + ".coerce");
3223 ArgVals.push_back(ParamValue::forDirect(Builder.CreateExtractVector(
3224 VecTyTo, Coerced, Zero, "cast.fixed")));
3225 break;
3226 }
3227 }
3228 }
3229
3230 llvm::StructType *STy =
3231 dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
3232 if (ArgI.isDirect() && !ArgI.getCanBeFlattened() && STy &&
3233 STy->getNumElements() > 1) {
3234 [[maybe_unused]] llvm::TypeSize StructSize =
3235 CGM.getDataLayout().getTypeAllocSize(STy);
3236 [[maybe_unused]] llvm::TypeSize PtrElementSize =
3237 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(Ty));
3238 if (STy->containsHomogeneousScalableVectorTypes()) {
3239 assert(StructSize == PtrElementSize &&
3240 "Only allow non-fractional movement of structure with"
3241 "homogeneous scalable vector type");
3242
3243 ArgVals.push_back(ParamValue::forDirect(AI));
3244 break;
3245 }
3246 }
3247
3248 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
3249 Arg->getName());
3250
3251 // Pointer to store into.
3252 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
3253
3254 // Fast-isel and the optimizer generally like scalar values better than
3255 // FCAs, so we flatten them if this is safe to do for this argument.
3256 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
3257 STy->getNumElements() > 1) {
3258 llvm::TypeSize StructSize = CGM.getDataLayout().getTypeAllocSize(STy);
3259 llvm::TypeSize PtrElementSize =
3260 CGM.getDataLayout().getTypeAllocSize(Ptr.getElementType());
3261 if (StructSize.isScalable()) {
3262 assert(STy->containsHomogeneousScalableVectorTypes() &&
3263 "ABI only supports structure with homogeneous scalable vector "
3264 "type");
3265 assert(StructSize == PtrElementSize &&
3266 "Only allow non-fractional movement of structure with"
3267 "homogeneous scalable vector type");
3268 assert(STy->getNumElements() == NumIRArgs);
3269
3270 llvm::Value *LoadedStructValue = llvm::PoisonValue::get(STy);
3271 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3272 auto *AI = Fn->getArg(FirstIRArg + i);
3273 AI->setName(Arg->getName() + ".coerce" + Twine(i));
3274 LoadedStructValue =
3275 Builder.CreateInsertValue(LoadedStructValue, AI, i);
3276 }
3277
3278 Builder.CreateStore(LoadedStructValue, Ptr);
3279 } else {
3280 uint64_t SrcSize = StructSize.getFixedValue();
3281 uint64_t DstSize = PtrElementSize.getFixedValue();
3282
3283 Address AddrToStoreInto = Address::invalid();
3284 if (SrcSize <= DstSize) {
3285 AddrToStoreInto = Ptr.withElementType(STy);
3286 } else {
3287 AddrToStoreInto =
3288 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
3289 }
3290
3291 assert(STy->getNumElements() == NumIRArgs);
3292 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3293 auto AI = Fn->getArg(FirstIRArg + i);
3294 AI->setName(Arg->getName() + ".coerce" + Twine(i));
3295 Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i);
3296 Builder.CreateStore(AI, EltPtr);
3297 }
3298
3299 if (SrcSize > DstSize) {
3300 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
3301 }
3302 }
3303 } else {
3304 // Simple case, just do a coerced store of the argument into the alloca.
3305 assert(NumIRArgs == 1);
3306 auto AI = Fn->getArg(FirstIRArg);
3307 AI->setName(Arg->getName() + ".coerce");
3308 CreateCoercedStore(AI, Ptr, /*DstIsVolatile=*/false, *this);
3309 }
3310
3311 // Match to what EmitParmDecl is expecting for this type.
3313 llvm::Value *V =
3314 EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc());
3315 if (isPromoted)
3316 V = emitArgumentDemotion(*this, Arg, V);
3317 ArgVals.push_back(ParamValue::forDirect(V));
3318 } else {
3319 ArgVals.push_back(ParamValue::forIndirect(Alloca));
3320 }
3321 break;
3322 }
3323
3325 // Reconstruct into a temporary.
3326 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
3327 ArgVals.push_back(ParamValue::forIndirect(alloca));
3328
3329 auto coercionType = ArgI.getCoerceAndExpandType();
3330 alloca = alloca.withElementType(coercionType);
3331
3332 unsigned argIndex = FirstIRArg;
3333 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3334 llvm::Type *eltType = coercionType->getElementType(i);
3336 continue;
3337
3338 auto eltAddr = Builder.CreateStructGEP(alloca, i);
3339 auto elt = Fn->getArg(argIndex++);
3340 Builder.CreateStore(elt, eltAddr);
3341 }
3342 assert(argIndex == FirstIRArg + NumIRArgs);
3343 break;
3344 }
3345
3346 case ABIArgInfo::Expand: {
3347 // If this structure was expanded into multiple arguments then
3348 // we need to create a temporary and reconstruct it from the
3349 // arguments.
3350 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
3351 LValue LV = MakeAddrLValue(Alloca, Ty);
3352 ArgVals.push_back(ParamValue::forIndirect(Alloca));
3353
3354 auto FnArgIter = Fn->arg_begin() + FirstIRArg;
3355 ExpandTypeFromArgs(Ty, LV, FnArgIter);
3356 assert(FnArgIter == Fn->arg_begin() + FirstIRArg + NumIRArgs);
3357 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
3358 auto AI = Fn->getArg(FirstIRArg + i);
3359 AI->setName(Arg->getName() + "." + Twine(i));
3360 }
3361 break;
3362 }
3363
3364 case ABIArgInfo::Ignore:
3365 assert(NumIRArgs == 0);
3366 // Initialize the local variable appropriately.
3367 if (!hasScalarEvaluationKind(Ty)) {
3368 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
3369 } else {
3370 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
3371 ArgVals.push_back(ParamValue::forDirect(U));
3372 }
3373 break;
3374 }
3375 }
3376
3377 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3378 for (int I = Args.size() - 1; I >= 0; --I)
3379 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
3380 } else {
3381 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3382 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
3383 }
3384}
3385
3386static void eraseUnusedBitCasts(llvm::Instruction *insn) {
3387 while (insn->use_empty()) {
3388 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
3389 if (!bitcast) return;
3390
3391 // This is "safe" because we would have used a ConstantExpr otherwise.
3392 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
3393 bitcast->eraseFromParent();
3394 }
3395}
3396
3397/// Try to emit a fused autorelease of a return result.
3399 llvm::Value *result) {
3400 // We must be immediately followed the cast.
3401 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
3402 if (BB->empty()) return nullptr;
3403 if (&BB->back() != result) return nullptr;
3404
3405 llvm::Type *resultType = result->getType();
3406
3407 // result is in a BasicBlock and is therefore an Instruction.
3408 llvm::Instruction *generator = cast<llvm::Instruction>(result);
3409
3411
3412 // Look for:
3413 // %generator = bitcast %type1* %generator2 to %type2*
3414 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
3415 // We would have emitted this as a constant if the operand weren't
3416 // an Instruction.
3417 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
3418
3419 // Require the generator to be immediately followed by the cast.
3420 if (generator->getNextNode() != bitcast)
3421 return nullptr;
3422
3423 InstsToKill.push_back(bitcast);
3424 }
3425
3426 // Look for:
3427 // %generator = call i8* @objc_retain(i8* %originalResult)
3428 // or
3429 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
3430 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
3431 if (!call) return nullptr;
3432
3433 bool doRetainAutorelease;
3434
3435 if (call->getCalledOperand() == CGF.CGM.getObjCEntrypoints().objc_retain) {
3436 doRetainAutorelease = true;
3437 } else if (call->getCalledOperand() ==
3439 doRetainAutorelease = false;
3440
3441 // If we emitted an assembly marker for this call (and the
3442 // ARCEntrypoints field should have been set if so), go looking
3443 // for that call. If we can't find it, we can't do this
3444 // optimization. But it should always be the immediately previous
3445 // instruction, unless we needed bitcasts around the call.
3447 llvm::Instruction *prev = call->getPrevNode();
3448 assert(prev);
3449 if (isa<llvm::BitCastInst>(prev)) {
3450 prev = prev->getPrevNode();
3451 assert(prev);
3452 }
3453 assert(isa<llvm::CallInst>(prev));
3454 assert(cast<llvm::CallInst>(prev)->getCalledOperand() ==
3456 InstsToKill.push_back(prev);
3457 }
3458 } else {
3459 return nullptr;
3460 }
3461
3462 result = call->getArgOperand(0);
3463 InstsToKill.push_back(call);
3464
3465 // Keep killing bitcasts, for sanity. Note that we no longer care
3466 // about precise ordering as long as there's exactly one use.
3467 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
3468 if (!bitcast->hasOneUse()) break;
3469 InstsToKill.push_back(bitcast);
3470 result = bitcast->getOperand(0);
3471 }
3472
3473 // Delete all the unnecessary instructions, from latest to earliest.
3474 for (auto *I : InstsToKill)
3475 I->eraseFromParent();
3476
3477 // Do the fused retain/autorelease if we were asked to.
3478 if (doRetainAutorelease)
3479 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
3480
3481 // Cast back to the result type.
3482 return CGF.Builder.CreateBitCast(result, resultType);
3483}
3484
3485/// If this is a +1 of the value of an immutable 'self', remove it.
3487 llvm::Value *result) {
3488 // This is only applicable to a method with an immutable 'self'.
3489 const ObjCMethodDecl *method =
3490 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
3491 if (!method) return nullptr;
3492 const VarDecl *self = method->getSelfDecl();
3493 if (!self->getType().isConstQualified()) return nullptr;
3494
3495 // Look for a retain call. Note: stripPointerCasts looks through returned arg
3496 // functions, which would cause us to miss the retain.
3497 llvm::CallInst *retainCall = dyn_cast<llvm::CallInst>(result);
3498 if (!retainCall || retainCall->getCalledOperand() !=
3500 return nullptr;
3501
3502 // Look for an ordinary load of 'self'.
3503 llvm::Value *retainedValue = retainCall->getArgOperand(0);
3504 llvm::LoadInst *load =
3505 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
3506 if (!load || load->isAtomic() || load->isVolatile() ||
3507 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getBasePointer())
3508 return nullptr;
3509
3510 // Okay! Burn it all down. This relies for correctness on the
3511 // assumption that the retain is emitted as part of the return and
3512 // that thereafter everything is used "linearly".
3513 llvm::Type *resultType = result->getType();
3514 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
3515 assert(retainCall->use_empty());
3516 retainCall->eraseFromParent();
3517 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
3518
3519 return CGF.Builder.CreateBitCast(load, resultType);
3520}
3521
3522/// Emit an ARC autorelease of the result of a function.
3523///
3524/// \return the value to actually return from the function
3526 llvm::Value *result) {
3527 // If we're returning 'self', kill the initial retain. This is a
3528 // heuristic attempt to "encourage correctness" in the really unfortunate
3529 // case where we have a return of self during a dealloc and we desperately
3530 // need to avoid the possible autorelease.
3531 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
3532 return self;
3533
3534 // At -O0, try to emit a fused retain/autorelease.
3535 if (CGF.shouldUseFusedARCCalls())
3536 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
3537 return fused;
3538
3539 return CGF.EmitARCAutoreleaseReturnValue(result);
3540}
3541
3542/// Heuristically search for a dominating store to the return-value slot.
3544 llvm::Value *ReturnValuePtr = CGF.ReturnValue.getBasePointer();
3545
3546 // Check if a User is a store which pointerOperand is the ReturnValue.
3547 // We are looking for stores to the ReturnValue, not for stores of the
3548 // ReturnValue to some other location.
3549 auto GetStoreIfValid = [&CGF,
3550 ReturnValuePtr](llvm::User *U) -> llvm::StoreInst * {
3551 auto *SI = dyn_cast<llvm::StoreInst>(U);
3552 if (!SI || SI->getPointerOperand() != ReturnValuePtr ||
3553 SI->getValueOperand()->getType() != CGF.ReturnValue.getElementType())
3554 return nullptr;
3555 // These aren't actually possible for non-coerced returns, and we
3556 // only care about non-coerced returns on this code path.
3557 // All memory instructions inside __try block are volatile.
3558 assert(!SI->isAtomic() &&
3559 (!SI->isVolatile() || CGF.currentFunctionUsesSEHTry()));
3560 return SI;
3561 };
3562 // If there are multiple uses of the return-value slot, just check
3563 // for something immediately preceding the IP. Sometimes this can
3564 // happen with how we generate implicit-returns; it can also happen
3565 // with noreturn cleanups.
3566 if (!ReturnValuePtr->hasOneUse()) {
3567 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
3568 if (IP->empty()) return nullptr;
3569
3570 // Look at directly preceding instruction, skipping bitcasts and lifetime
3571 // markers.
3572 for (llvm::Instruction &I : make_range(IP->rbegin(), IP->rend())) {
3573 if (isa<llvm::BitCastInst>(&I))
3574 continue;
3575 if (auto *II = dyn_cast<llvm::IntrinsicInst>(&I))
3576 if (II->getIntrinsicID() == llvm::Intrinsic::lifetime_end)
3577 continue;
3578
3579 return GetStoreIfValid(&I);
3580 }
3581 return nullptr;
3582 }
3583
3584 llvm::StoreInst *store = GetStoreIfValid(ReturnValuePtr->user_back());
3585 if (!store) return nullptr;
3586
3587 // Now do a first-and-dirty dominance check: just walk up the
3588 // single-predecessors chain from the current insertion point.
3589 llvm::BasicBlock *StoreBB = store->getParent();
3590 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
3592 while (IP != StoreBB) {
3593 if (!SeenBBs.insert(IP).second || !(IP = IP->getSinglePredecessor()))
3594 return nullptr;
3595 }
3596
3597 // Okay, the store's basic block dominates the insertion point; we
3598 // can do our thing.
3599 return store;
3600}
3601
3602// Helper functions for EmitCMSEClearRecord
3603
3604// Set the bits corresponding to a field having width `BitWidth` and located at
3605// offset `BitOffset` (from the least significant bit) within a storage unit of
3606// `Bits.size()` bytes. Each element of `Bits` corresponds to one target byte.
3607// Use little-endian layout, i.e.`Bits[0]` is the LSB.
3608static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int BitOffset,
3609 int BitWidth, int CharWidth) {
3610 assert(CharWidth <= 64);
3611 assert(static_cast<unsigned>(BitWidth) <= Bits.size() * CharWidth);
3612
3613 int Pos = 0;
3614 if (BitOffset >= CharWidth) {
3615 Pos += BitOffset / CharWidth;
3616 BitOffset = BitOffset % CharWidth;
3617 }
3618
3619 const uint64_t Used = (uint64_t(1) << CharWidth) - 1;
3620 if (BitOffset + BitWidth >= CharWidth) {
3621 Bits[Pos++] |= (Used << BitOffset) & Used;
3622 BitWidth -= CharWidth - BitOffset;
3623 BitOffset = 0;
3624 }
3625
3626 while (BitWidth >= CharWidth) {
3627 Bits[Pos++] = Used;
3628 BitWidth -= CharWidth;
3629 }
3630
3631 if (BitWidth > 0)
3632 Bits[Pos++] |= (Used >> (CharWidth - BitWidth)) << BitOffset;
3633}
3634
3635// Set the bits corresponding to a field having width `BitWidth` and located at
3636// offset `BitOffset` (from the least significant bit) within a storage unit of
3637// `StorageSize` bytes, located at `StorageOffset` in `Bits`. Each element of
3638// `Bits` corresponds to one target byte. Use target endian layout.
3639static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int StorageOffset,
3640 int StorageSize, int BitOffset, int BitWidth,
3641 int CharWidth, bool BigEndian) {
3642
3643 SmallVector<uint64_t, 8> TmpBits(StorageSize);
3644 setBitRange(TmpBits, BitOffset, BitWidth, CharWidth);
3645
3646 if (BigEndian)
3647 std::reverse(TmpBits.begin(), TmpBits.end());
3648
3649 for (uint64_t V : TmpBits)
3650 Bits[StorageOffset++] |= V;
3651}
3652
3653static void setUsedBits(CodeGenModule &, QualType, int,
3655
3656// Set the bits in `Bits`, which correspond to the value representations of
3657// the actual members of the record type `RTy`. Note that this function does
3658// not handle base classes, virtual tables, etc, since they cannot happen in
3659// CMSE function arguments or return. The bit mask corresponds to the target
3660// memory layout, i.e. it's endian dependent.
3661static void setUsedBits(CodeGenModule &CGM, const RecordType *RTy, int Offset,
3663 ASTContext &Context = CGM.getContext();
3664 int CharWidth = Context.getCharWidth();
3665 const RecordDecl *RD = RTy->getDecl()->getDefinition();
3666 const ASTRecordLayout &ASTLayout = Context.getASTRecordLayout(RD);
3667 const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(RD);
3668
3669 int Idx = 0;
3670 for (auto I = RD->field_begin(), E = RD->field_end(); I != E; ++I, ++Idx) {
3671 const FieldDecl *F = *I;
3672
3673 if (F->isUnnamedBitField() || F->isZeroLengthBitField(Context) ||
3675 continue;
3676
3677 if (F->isBitField()) {
3678 const CGBitFieldInfo &BFI = Layout.getBitFieldInfo(F);
3679 setBitRange(Bits, Offset + BFI.StorageOffset.getQuantity(),
3680 BFI.StorageSize / CharWidth, BFI.Offset,
3681 BFI.Size, CharWidth,
3682 CGM.getDataLayout().isBigEndian());
3683 continue;
3684 }
3685
3686 setUsedBits(CGM, F->getType(),
3687 Offset + ASTLayout.getFieldOffset(Idx) / CharWidth, Bits);
3688 }
3689}
3690
3691// Set the bits in `Bits`, which correspond to the value representations of
3692// the elements of an array type `ATy`.
3693static void setUsedBits(CodeGenModule &CGM, const ConstantArrayType *ATy,
3694 int Offset, SmallVectorImpl<uint64_t> &Bits) {
3695 const ASTContext &Context = CGM.getContext();
3696
3697 QualType ETy = Context.getBaseElementType(ATy);
3698 int Size = Context.getTypeSizeInChars(ETy).getQuantity();
3699 SmallVector<uint64_t, 4> TmpBits(Size);
3700 setUsedBits(CGM, ETy, 0, TmpBits);
3701
3702 for (int I = 0, N = Context.getConstantArrayElementCount(ATy); I < N; ++I) {
3703 auto Src = TmpBits.begin();
3704 auto Dst = Bits.begin() + Offset + I * Size;
3705 for (int J = 0; J < Size; ++J)
3706 *Dst++ |= *Src++;
3707 }
3708}
3709
3710// Set the bits in `Bits`, which correspond to the value representations of
3711// the type `QTy`.
3712static void setUsedBits(CodeGenModule &CGM, QualType QTy, int Offset,
3714 if (const auto *RTy = QTy->getAs<RecordType>())
3715 return setUsedBits(CGM, RTy, Offset, Bits);
3716
3717 ASTContext &Context = CGM.getContext();
3718 if (const auto *ATy = Context.getAsConstantArrayType(QTy))
3719 return setUsedBits(CGM, ATy, Offset, Bits);
3720
3721 int Size = Context.getTypeSizeInChars(QTy).getQuantity();
3722 if (Size <= 0)
3723 return;
3724
3725 std::fill_n(Bits.begin() + Offset, Size,
3726 (uint64_t(1) << Context.getCharWidth()) - 1);
3727}
3728
3730 int Pos, int Size, int CharWidth,
3731 bool BigEndian) {
3732 assert(Size > 0);
3733 uint64_t Mask = 0;
3734 if (BigEndian) {
3735 for (auto P = Bits.begin() + Pos, E = Bits.begin() + Pos + Size; P != E;
3736 ++P)
3737 Mask = (Mask << CharWidth) | *P;
3738 } else {
3739 auto P = Bits.begin() + Pos + Size, End = Bits.begin() + Pos;
3740 do
3741 Mask = (Mask << CharWidth) | *--P;
3742 while (P != End);
3743 }
3744 return Mask;
3745}
3746
3747// Emit code to clear the bits in a record, which aren't a part of any user
3748// declared member, when the record is a function return.
3749llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3750 llvm::IntegerType *ITy,
3751 QualType QTy) {
3752 assert(Src->getType() == ITy);
3753 assert(ITy->getScalarSizeInBits() <= 64);
3754
3755 const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3756 int Size = DataLayout.getTypeStoreSize(ITy);
3757 SmallVector<uint64_t, 4> Bits(Size);
3758 setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
3759
3760 int CharWidth = CGM.getContext().getCharWidth();
3761 uint64_t Mask =
3762 buildMultiCharMask(Bits, 0, Size, CharWidth, DataLayout.isBigEndian());
3763
3764 return Builder.CreateAnd(Src, Mask, "cmse.clear");
3765}
3766
3767// Emit code to clear the bits in a record, which aren't a part of any user
3768// declared member, when the record is a function argument.
3769llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3770 llvm::ArrayType *ATy,
3771 QualType QTy) {
3772 const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3773 int Size = DataLayout.getTypeStoreSize(ATy);
3774 SmallVector<uint64_t, 16> Bits(Size);
3775 setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
3776
3777 // Clear each element of the LLVM array.
3778 int CharWidth = CGM.getContext().getCharWidth();
3779 int CharsPerElt =
3780 ATy->getArrayElementType()->getScalarSizeInBits() / CharWidth;
3781 int MaskIndex = 0;
3782 llvm::Value *R = llvm::PoisonValue::get(ATy);
3783 for (int I = 0, N = ATy->getArrayNumElements(); I != N; ++I) {
3784 uint64_t Mask = buildMultiCharMask(Bits, MaskIndex, CharsPerElt, CharWidth,
3785 DataLayout.isBigEndian());
3786 MaskIndex += CharsPerElt;
3787 llvm::Value *T0 = Builder.CreateExtractValue(Src, I);
3788 llvm::Value *T1 = Builder.CreateAnd(T0, Mask, "cmse.clear");
3789 R = Builder.CreateInsertValue(R, T1, I);
3790 }
3791
3792 return R;
3793}
3794
3796 bool EmitRetDbgLoc,
3797 SourceLocation EndLoc) {
3798 if (FI.isNoReturn()) {
3799 // Noreturn functions don't return.
3800 EmitUnreachable(EndLoc);
3801 return;
3802 }
3803
3804 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
3805 // Naked functions don't have epilogues.
3806 Builder.CreateUnreachable();
3807 return;
3808 }
3809
3810 // Functions with no result always return void.
3811 if (!ReturnValue.isValid()) {
3812 Builder.CreateRetVoid();
3813 return;
3814 }
3815
3816 llvm::DebugLoc RetDbgLoc;
3817 llvm::Value *RV = nullptr;
3818 QualType RetTy = FI.getReturnType();
3819 const ABIArgInfo &RetAI = FI.getReturnInfo();
3820
3821 switch (RetAI.getKind()) {
3823 // Aggregates get evaluated directly into the destination. Sometimes we
3824 // need to return the sret value in a register, though.
3825 assert(hasAggregateEvaluationKind(RetTy));
3826 if (RetAI.getInAllocaSRet()) {
3827 llvm::Function::arg_iterator EI = CurFn->arg_end();
3828 --EI;
3829 llvm::Value *ArgStruct = &*EI;
3830 llvm::Value *SRet = Builder.CreateStructGEP(
3831 FI.getArgStruct(), ArgStruct, RetAI.getInAllocaFieldIndex());
3832 llvm::Type *Ty =
3833 cast<llvm::GetElementPtrInst>(SRet)->getResultElementType();
3834 RV = Builder.CreateAlignedLoad(Ty, SRet, getPointerAlign(), "sret");
3835 }
3836 break;
3837
3838 case ABIArgInfo::Indirect: {
3839 auto AI = CurFn->arg_begin();
3840 if (RetAI.isSRetAfterThis())
3841 ++AI;
3842 switch (getEvaluationKind(RetTy)) {
3843 case TEK_Complex: {
3844 ComplexPairTy RT =
3847 /*isInit*/ true);
3848 break;
3849 }
3850 case TEK_Aggregate:
3851 // Do nothing; aggregates get evaluated directly into the destination.
3852 break;
3853 case TEK_Scalar: {
3854 LValueBaseInfo BaseInfo;
3855 TBAAAccessInfo TBAAInfo;
3856 CharUnits Alignment =
3857 CGM.getNaturalTypeAlignment(RetTy, &BaseInfo, &TBAAInfo);
3858 Address ArgAddr(&*AI, ConvertType(RetTy), Alignment);
3859 LValue ArgVal =
3860 LValue::MakeAddr(ArgAddr, RetTy, getContext(), BaseInfo, TBAAInfo);
3862 Builder.CreateLoad(ReturnValue), ArgVal, /*isInit*/ true);
3863 break;
3864 }
3865 }
3866 break;
3867 }
3868
3869 case ABIArgInfo::Extend:
3870 case ABIArgInfo::Direct:
3871 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
3872 RetAI.getDirectOffset() == 0) {
3873 // The internal return value temp always will have pointer-to-return-type
3874 // type, just do a load.
3875
3876 // If there is a dominating store to ReturnValue, we can elide
3877 // the load, zap the store, and usually zap the alloca.
3878 if (llvm::StoreInst *SI =
3880 // Reuse the debug location from the store unless there is
3881 // cleanup code to be emitted between the store and return
3882 // instruction.
3883 if (EmitRetDbgLoc && !AutoreleaseResult)
3884 RetDbgLoc = SI->getDebugLoc();
3885 // Get the stored value and nuke the now-dead store.
3886 RV = SI->getValueOperand();
3887 SI->eraseFromParent();
3888
3889 // Otherwise, we have to do a simple load.
3890 } else {
3892 }
3893 } else {
3894 // If the value is offset in memory, apply the offset now.
3895 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
3896
3897 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
3898 }
3899
3900 // In ARC, end functions that return a retainable type with a call
3901 // to objc_autoreleaseReturnValue.
3902 if (AutoreleaseResult) {
3903#ifndef NDEBUG
3904 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
3905 // been stripped of the typedefs, so we cannot use RetTy here. Get the
3906 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
3907 // CurCodeDecl or BlockInfo.
3908 QualType RT;
3909
3910 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
3911 RT = FD->getReturnType();
3912 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
3913 RT = MD->getReturnType();
3914 else if (isa<BlockDecl>(CurCodeDecl))
3916 else
3917 llvm_unreachable("Unexpected function/method type");
3918
3919 assert(getLangOpts().ObjCAutoRefCount &&
3920 !FI.isReturnsRetained() &&
3921 RT->isObjCRetainableType());
3922#endif
3923 RV = emitAutoreleaseOfResult(*this, RV);
3924 }
3925
3926 break;
3927
3928 case ABIArgInfo::Ignore:
3929 break;
3930
3932 auto coercionType = RetAI.getCoerceAndExpandType();
3933
3934 // Load all of the coerced elements out into results.
3936 Address addr = ReturnValue.withElementType(coercionType);
3937 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3938 auto coercedEltType = coercionType->getElementType(i);
3939 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
3940 continue;
3941
3942 auto eltAddr = Builder.CreateStructGEP(addr, i);
3943 auto elt = Builder.CreateLoad(eltAddr);
3944 results.push_back(elt);
3945 }
3946
3947 // If we have one result, it's the single direct result type.
3948 if (results.size() == 1) {
3949 RV = results[0];
3950
3951 // Otherwise, we need to make a first-class aggregate.
3952 } else {
3953 // Construct a return type that lacks padding elements.
3954 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
3955
3956 RV = llvm::PoisonValue::get(returnType);
3957 for (unsigned i = 0, e = results.size(); i != e; ++i) {
3958 RV = Builder.CreateInsertValue(RV, results[i], i);
3959 }
3960 }
3961 break;
3962 }
3963 case ABIArgInfo::Expand:
3965 llvm_unreachable("Invalid ABI kind for return argument");
3966 }
3967
3968 llvm::Instruction *Ret;
3969 if (RV) {
3970 if (CurFuncDecl && CurFuncDecl->hasAttr<CmseNSEntryAttr>()) {
3971 // For certain return types, clear padding bits, as they may reveal
3972 // sensitive information.
3973 // Small struct/union types are passed as integers.
3974 auto *ITy = dyn_cast<llvm::IntegerType>(RV->getType());
3975 if (ITy != nullptr && isa<RecordType>(RetTy.getCanonicalType()))
3976 RV = EmitCMSEClearRecord(RV, ITy, RetTy);
3977 }
3979 Ret = Builder.CreateRet(RV);
3980 } else {
3981 Ret = Builder.CreateRetVoid();
3982 }
3983
3984 if (RetDbgLoc)
3985 Ret->setDebugLoc(std::move(RetDbgLoc));
3986}
3987
3988void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) {
3989 // A current decl may not be available when emitting vtable thunks.
3990 if (!CurCodeDecl)
3991 return;
3992
3993 // If the return block isn't reachable, neither is this check, so don't emit
3994 // it.
3995 if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty())
3996 return;
3997
3998 ReturnsNonNullAttr *RetNNAttr = nullptr;
3999 if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
4000 RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
4001
4002 if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
4003 return;
4004
4005 // Prefer the returns_nonnull attribute if it's present.
4006 SourceLocation AttrLoc;
4007 SanitizerMask CheckKind;
4008 SanitizerHandler Handler;
4009 if (RetNNAttr) {
4010 assert(!requiresReturnValueNullabilityCheck() &&
4011 "Cannot check nullability and the nonnull attribute");
4012 AttrLoc = RetNNAttr->getLocation();
4013 CheckKind = SanitizerKind::ReturnsNonnullAttribute;
4014 Handler = SanitizerHandler::NonnullReturn;
4015 } else {
4016 if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl))
4017 if (auto *TSI = DD->getTypeSourceInfo())
4018 if (auto FTL = TSI->getTypeLoc().getAsAdjusted<FunctionTypeLoc>())
4019 AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
4020 CheckKind = SanitizerKind::NullabilityReturn;
4021 Handler = SanitizerHandler::NullabilityReturn;
4022 }
4023
4024 SanitizerScope SanScope(this);
4025
4026 // Make sure the "return" source location is valid. If we're checking a
4027 // nullability annotation, make sure the preconditions for the check are met.
4028 llvm::BasicBlock *Check = createBasicBlock("nullcheck");
4029 llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck");
4030 llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load");
4031 llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr);
4032 if (requiresReturnValueNullabilityCheck())
4033 CanNullCheck =
4034 Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition);
4035 Builder.CreateCondBr(CanNullCheck, Check, NoCheck);
4036 EmitBlock(Check);
4037
4038 // Now do the null check.
4039 llvm::Value *Cond = Builder.CreateIsNotNull(RV);
4040 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)};
4041 llvm::Value *DynamicData[] = {SLocPtr};
4042 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData);
4043
4044 EmitBlock(NoCheck);
4045
4046#ifndef NDEBUG
4047 // The return location should not be used after the check has been emitted.
4048 ReturnLocation = Address::invalid();
4049#endif
4050}
4051
4053 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
4054 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
4055}
4056
4058 QualType Ty) {
4059 // FIXME: Generate IR in one pass, rather than going back and fixing up these
4060 // placeholders.
4061 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
4062 llvm::Type *IRPtrTy = llvm::PointerType::getUnqual(CGF.getLLVMContext());
4063 llvm::Value *Placeholder = llvm::PoisonValue::get(IRPtrTy);
4064
4065 // FIXME: When we generate this IR in one pass, we shouldn't need
4066 // this win32-specific alignment hack.
4068 Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
4069
4070 return AggValueSlot::forAddr(Address(Placeholder, IRTy, Align),
4071 Ty.getQualifiers(),
4076}
4077
4079 const VarDecl *param,
4080 SourceLocation loc) {
4081 // StartFunction converted the ABI-lowered parameter(s) into a
4082 // local alloca. We need to turn that into an r-value suitable
4083 // for EmitCall.
4084 Address local = GetAddrOfLocalVar(param);
4085
4086 QualType type = param->getType();
4087
4088 // GetAddrOfLocalVar returns a pointer-to-pointer for references,
4089 // but the argument needs to be the original pointer.
4090 if (type->isReferenceType()) {
4091 args.add(RValue::get(Builder.CreateLoad(local)), type);
4092
4093 // In ARC, move out of consumed arguments so that the release cleanup
4094 // entered by StartFunction doesn't cause an over-release. This isn't
4095 // optimal -O0 code generation, but it should get cleaned up when
4096 // optimization is enabled. This also assumes that delegate calls are
4097 // performed exactly once for a set of arguments, but that should be safe.
4098 } else if (getLangOpts().ObjCAutoRefCount &&
4099 param->hasAttr<NSConsumedAttr>() &&
4100 type->isObjCRetainableType()) {
4101 llvm::Value *ptr = Builder.CreateLoad(local);
4102 auto null =
4103 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
4104 Builder.CreateStore(null, local);
4105 args.add(RValue::get(ptr), type);
4106
4107 // For the most part, we just need to load the alloca, except that
4108 // aggregate r-values are actually pointers to temporaries.
4109 } else {
4110 args.add(convertTempToRValue(local, type, loc), type);
4111 }
4112
4113 // Deactivate the cleanup for the callee-destructed param that was pushed.
4114 if (type->isRecordType() && !CurFuncIsThunk &&
4116 param->needsDestruction(getContext())) {
4118 CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param));
4119 assert(cleanup.isValid() &&
4120 "cleanup for callee-destructed param not recorded");
4121 // This unreachable is a temporary marker which will be removed later.
4122 llvm::Instruction *isActive = Builder.CreateUnreachable();
4123 args.addArgCleanupDeactivation(cleanup, isActive);
4124 }
4125}
4126
4127static bool isProvablyNull(llvm::Value *addr) {
4128 return llvm::isa_and_nonnull<llvm::ConstantPointerNull>(addr);
4129}
4130
4132 return llvm::isKnownNonZero(Addr.getBasePointer(), CGF.CGM.getDataLayout());
4133}
4134
4135/// Emit the actual writing-back of a writeback.
4137 const CallArgList::Writeback &writeback) {
4138 const LValue &srcLV = writeback.Source;
4139 Address srcAddr = srcLV.getAddress();
4140 assert(!isProvablyNull(srcAddr.getBasePointer()) &&
4141 "shouldn't have writeback for provably null argument");
4142
4143 llvm::BasicBlock *contBB = nullptr;
4144
4145 // If the argument wasn't provably non-null, we need to null check
4146 // before doing the store.
4147 bool provablyNonNull = isProvablyNonNull(srcAddr, CGF);
4148
4149 if (!provablyNonNull) {
4150 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
4151 contBB = CGF.createBasicBlock("icr.done");
4152
4153 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
4154 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
4155 CGF.EmitBlock(writebackBB);
4156 }
4157
4158 // Load the value to writeback.
4159 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
4160
4161 // Cast it back, in case we're writing an id to a Foo* or something.
4162 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
4163 "icr.writeback-cast");
4164
4165 // Perform the writeback.
4166
4167 // If we have a "to use" value, it's something we need to emit a use
4168 // of. This has to be carefully threaded in: if it's done after the
4169 // release it's potentially undefined behavior (and the optimizer
4170 // will ignore it), and if it happens before the retain then the
4171 // optimizer could move the release there.
4172 if (writeback.ToUse) {
4173 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
4174
4175 // Retain the new value. No need to block-copy here: the block's
4176 // being passed up the stack.
4177 value = CGF.EmitARCRetainNonBlock(value);
4178
4179 // Emit the intrinsic use here.
4180 CGF.EmitARCIntrinsicUse(writeback.ToUse);
4181
4182 // Load the old value (primitively).
4183 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
4184
4185 // Put the new value in place (primitively).
4186 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
4187
4188 // Release the old value.
4189 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
4190
4191 // Otherwise, we can just do a normal lvalue store.
4192 } else {
4193 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
4194 }
4195
4196 // Jump to the continuation block.
4197 if (!provablyNonNull)
4198 CGF.EmitBlock(contBB);
4199}
4200
4202 const CallArgList &args) {
4203 for (const auto &I : args.writebacks())
4204 emitWriteback(CGF, I);
4205}
4206
4208 const CallArgList &CallArgs) {
4210 CallArgs.getCleanupsToDeactivate();
4211 // Iterate in reverse to increase the likelihood of popping the cleanup.
4212 for (const auto &I : llvm::reverse(Cleanups)) {
4213 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
4214 I.IsActiveIP->eraseFromParent();
4215 }
4216}
4217
4218static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
4219 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
4220 if (uop->getOpcode() == UO_AddrOf)
4221 return uop->getSubExpr();
4222 return nullptr;
4223}
4224
4225/// Emit an argument that's being passed call-by-writeback. That is,
4226/// we are passing the address of an __autoreleased temporary; it
4227/// might be copy-initialized with the current value of the given
4228/// address, but it will definitely be copied out of after the call.
4230 const ObjCIndirectCopyRestoreExpr *CRE) {
4231 LValue srcLV;
4232
4233 // Make an optimistic effort to emit the address as an l-value.
4234 // This can fail if the argument expression is more complicated.
4235 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
4236 srcLV = CGF.EmitLValue(lvExpr);
4237
4238 // Otherwise, just emit it as a scalar.
4239 } else {
4240 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
4241
4242 QualType srcAddrType =
4243 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
4244 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
4245 }
4246 Address srcAddr = srcLV.getAddress();
4247
4248 // The dest and src types don't necessarily match in LLVM terms
4249 // because of the crazy ObjC compatibility rules.
4250
4251 llvm::PointerType *destType =
4252 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
4253 llvm::Type *destElemType =
4255
4256 // If the address is a constant null, just pass the appropriate null.
4257 if (isProvablyNull(srcAddr.getBasePointer())) {
4258 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
4259 CRE->getType());
4260 return;
4261 }
4262
4263 // Create the temporary.
4264 Address temp =
4265 CGF.CreateTempAlloca(destElemType, CGF.getPointerAlign(), "icr.temp");
4266 // Loading an l-value can introduce a cleanup if the l-value is __weak,
4267 // and that cleanup will be conditional if we can't prove that the l-value
4268 // isn't null, so we need to register a dominating point so that the cleanups
4269 // system will make valid IR.
4270 CodeGenFunction::ConditionalEvaluation condEval(CGF);
4271
4272 // Zero-initialize it if we're not doing a copy-initialization.
4273 bool shouldCopy = CRE->shouldCopy();
4274 if (!shouldCopy) {
4275 llvm::Value *null =
4276 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(destElemType));
4277 CGF.Builder.CreateStore(null, temp);
4278 }
4279
4280 llvm::BasicBlock *contBB = nullptr;
4281 llvm::BasicBlock *originBB = nullptr;
4282
4283 // If the address is *not* known to be non-null, we need to switch.
4284 llvm::Value *finalArgument;
4285
4286 bool provablyNonNull = isProvablyNonNull(srcAddr, CGF);
4287
4288 if (provablyNonNull) {
4289 finalArgument = temp.emitRawPointer(CGF);
4290 } else {
4291 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
4292
4293 finalArgument = CGF.Builder.CreateSelect(
4294 isNull, llvm::ConstantPointerNull::get(destType),
4295 temp.emitRawPointer(CGF), "icr.argument");
4296
4297 // If we need to copy, then the load has to be conditional, which
4298 // means we need control flow.
4299 if (shouldCopy) {
4300 originBB = CGF.Builder.GetInsertBlock();
4301 contBB = CGF.createBasicBlock("icr.cont");
4302 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
4303 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
4304 CGF.EmitBlock(copyBB);
4305 condEval.begin(CGF);
4306 }
4307 }
4308
4309 llvm::Value *valueToUse = nullptr;
4310
4311 // Perform a copy if necessary.
4312 if (shouldCopy) {
4313 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
4314 assert(srcRV.isScalar());
4315
4316 llvm::Value *src = srcRV.getScalarVal();
4317 src = CGF.Builder.CreateBitCast(src, destElemType, "icr.cast");
4318
4319 // Use an ordinary store, not a store-to-lvalue.
4320 CGF.Builder.CreateStore(src, temp);
4321
4322 // If optimization is enabled, and the value was held in a
4323 // __strong variable, we need to tell the optimizer that this
4324 // value has to stay alive until we're doing the store back.
4325 // This is because the temporary is effectively unretained,
4326 // and so otherwise we can violate the high-level semantics.
4327 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
4329 valueToUse = src;
4330 }
4331 }
4332
4333 // Finish the control flow if we needed it.
4334 if (shouldCopy && !provablyNonNull) {
4335 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
4336 CGF.EmitBlock(contBB);
4337
4338 // Make a phi for the value to intrinsically use.
4339 if (valueToUse) {
4340 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
4341 "icr.to-use");
4342 phiToUse->addIncoming(valueToUse, copyBB);
4343 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
4344 originBB);
4345 valueToUse = phiToUse;
4346 }
4347
4348 condEval.end(CGF);
4349 }
4350
4351 args.addWriteback(srcLV, temp, valueToUse);
4352 args.add(RValue::get(finalArgument), CRE->getType());
4353}
4354
4356 assert(!StackBase);
4357
4358 // Save the stack.
4359 StackBase = CGF.Builder.CreateStackSave("inalloca.save");
4360}
4361
4363 if (StackBase) {
4364 // Restore the stack after the call.
4365 CGF.Builder.CreateStackRestore(StackBase);
4366 }
4367}
4368
4370 SourceLocation ArgLoc,
4371 AbstractCallee AC,
4372 unsigned ParmNum) {
4373 if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
4374 SanOpts.has(SanitizerKind::NullabilityArg)))
4375 return;
4376
4377 // The param decl may be missing in a variadic function.
4378 auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr;
4379 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
4380
4381 // Prefer the nonnull attribute if it's present.
4382 const NonNullAttr *NNAttr = nullptr;
4383 if (SanOpts.has(SanitizerKind::NonnullAttribute))
4384 NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
4385
4386 bool CanCheckNullability = false;
4387 if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD &&
4388 !PVD->getType()->isRecordType()) {
4389 auto Nullability = PVD->getType()->getNullability();
4390 CanCheckNullability = Nullability &&
4391 *Nullability == NullabilityKind::NonNull &&
4392 PVD->getTypeSourceInfo();
4393 }
4394
4395 if (!NNAttr && !CanCheckNullability)
4396 return;
4397
4398 SourceLocation AttrLoc;
4399 SanitizerMask CheckKind;
4400 SanitizerHandler Handler;
4401 if (NNAttr) {
4402 AttrLoc = NNAttr->getLocation();
4403 CheckKind = SanitizerKind::NonnullAttribute;
4404 Handler = SanitizerHandler::NonnullArg;
4405 } else {
4406 AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
4407 CheckKind = SanitizerKind::NullabilityArg;
4408 Handler = SanitizerHandler::NullabilityArg;
4409 }
4410
4411 SanitizerScope SanScope(this);
4412 llvm::Value *Cond = EmitNonNullRValueCheck(RV, ArgType);
4413 llvm::Constant *StaticData[] = {
4415 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
4416 };
4417 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, std::nullopt);
4418}
4419
4421 SourceLocation ArgLoc,
4422 AbstractCallee AC, unsigned ParmNum) {
4423 if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
4424 SanOpts.has(SanitizerKind::NullabilityArg)))
4425 return;
4426
4427 EmitNonNullArgCheck(RValue::get(Addr, *this), ArgType, ArgLoc, AC, ParmNum);
4428}
4429
4430// Check if the call is going to use the inalloca convention. This needs to
4431// agree with CGFunctionInfo::usesInAlloca. The CGFunctionInfo is arranged
4432// later, so we can't check it directly.
4433static bool hasInAllocaArgs(CodeGenModule &CGM, CallingConv ExplicitCC,
4434 ArrayRef<QualType> ArgTypes) {
4435 // The Swift calling conventions don't go through the target-specific
4436 // argument classification, they never use inalloca.
4437 // TODO: Consider limiting inalloca use to only calling conventions supported
4438 // by MSVC.
4439 if (ExplicitCC == CC_Swift || ExplicitCC == CC_SwiftAsync)
4440 return false;
4441 if (!CGM.getTarget().getCXXABI().isMicrosoft())
4442 return false;
4443 return llvm::any_of(ArgTypes, [&](QualType Ty) {
4444 return isInAllocaArgument(CGM.getCXXABI(), Ty);
4445 });
4446}
4447
4448#ifndef NDEBUG
4449// Determine whether the given argument is an Objective-C method
4450// that may have type parameters in its signature.
4451static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
4452 const DeclContext *dc = method->getDeclContext();
4453 if (const ObjCInterfaceDecl *classDecl = dyn_cast<ObjCInterfaceDecl>(dc)) {
4454 return classDecl->getTypeParamListAsWritten();
4455 }
4456
4457 if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
4458 return catDecl->getTypeParamList();
4459 }
4460
4461 return false;
4462}
4463#endif
4464
4465/// EmitCallArgs - Emit call arguments for a function.
4467 CallArgList &Args, PrototypeWrapper Prototype,
4468 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
4469 AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
4471
4472 assert((ParamsToSkip == 0 || Prototype.P) &&
4473 "Can't skip parameters if type info is not provided");
4474
4475 // This variable only captures *explicitly* written conventions, not those
4476 // applied by default via command line flags or target defaults, such as
4477 // thiscall, aapcs, stdcall via -mrtd, etc. Computing that correctly would
4478 // require knowing if this is a C++ instance method or being able to see
4479 // unprototyped FunctionTypes.
4480 CallingConv ExplicitCC = CC_C;
4481
4482 // First, if a prototype was provided, use those argument types.
4483 bool IsVariadic = false;
4484 if (Prototype.P) {
4485 const auto *MD = Prototype.P.dyn_cast<const ObjCMethodDecl *>();
4486 if (MD) {
4487 IsVariadic = MD->isVariadic();
4488 ExplicitCC = getCallingConventionForDecl(
4489 MD, CGM.getTarget().getTriple().isOSWindows());
4490 ArgTypes.assign(MD->param_type_begin() + ParamsToSkip,
4491 MD->param_type_end());
4492 } else {
4493 const auto *FPT = Prototype.P.get<const FunctionProtoType *>();
4494 IsVariadic = FPT->isVariadic();
4495 ExplicitCC = FPT->getExtInfo().getCC();
4496 ArgTypes.assign(FPT->param_type_begin() + ParamsToSkip,
4497 FPT->param_type_end());
4498 }
4499
4500#ifndef NDEBUG
4501 // Check that the prototyped types match the argument expression types.
4502 bool isGenericMethod = MD && isObjCMethodWithTypeParams(MD);
4503 CallExpr::const_arg_iterator Arg = ArgRange.begin();
4504 for (QualType Ty : ArgTypes) {
4505 assert(Arg != ArgRange.end() && "Running over edge of argument list!");
4506 assert(
4507 (isGenericMethod || Ty->isVariablyModifiedType() ||
4508 Ty.getNonReferenceType()->isObjCRetainableType() ||
4509 getContext()
4510 .getCanonicalType(Ty.getNonReferenceType())
4511 .getTypePtr() ==
4512 getContext().getCanonicalType((*Arg)->getType()).getTypePtr()) &&
4513 "type mismatch in call argument!");
4514 ++Arg;
4515 }
4516
4517 // Either we've emitted all the call args, or we have a call to variadic
4518 // function.
4519 assert((Arg == ArgRange.end() || IsVariadic) &&
4520 "Extra arguments in non-variadic function!");
4521#endif
4522 }
4523
4524 // If we still have any arguments, emit them using the type of the argument.
4525 for (auto *A : llvm::drop_begin(ArgRange, ArgTypes.size()))
4526 ArgTypes.push_back(IsVariadic ? getVarArgType(A) : A->getType());
4527 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
4528
4529 // We must evaluate arguments from right to left in the MS C++ ABI,
4530 // because arguments are destroyed left to right in the callee. As a special
4531 // case, there are certain language constructs that require left-to-right
4532 // evaluation, and in those cases we consider the evaluation order requirement
4533 // to trump the "destruction order is reverse construction order" guarantee.
4534 bool LeftToRight =
4538
4539 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
4540 RValue EmittedArg) {
4541 if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
4542 return;
4543 auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
4544 if (PS == nullptr)
4545 return;
4546
4547 const auto &Context = getContext();
4548 auto SizeTy = Context.getSizeType();
4549 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
4550 assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?");
4551 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
4552 EmittedArg.getScalarVal(),
4553 PS->isDynamic());
4554 Args.add(RValue::get(V), SizeTy);
4555 // If we're emitting args in reverse, be sure to do so with
4556 // pass_object_size, as well.
4557 if (!LeftToRight)
4558 std::swap(Args.back(), *(&Args.back() - 1));
4559 };
4560
4561 // Insert a stack save if we're going to need any inalloca args.
4562 if (hasInAllocaArgs(CGM, ExplicitCC, ArgTypes)) {
4563 assert(getTarget().getTriple().getArch() == llvm::Triple::x86 &&
4564 "inalloca only supported on x86");
4565 Args.allocateArgumentMemory(*this);
4566 }
4567
4568 // Evaluate each argument in the appropriate order.
4569 size_t CallArgsStart = Args.size();
4570 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
4571 unsigned Idx = LeftToRight ? I : E - I - 1;
4572 CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
4573 unsigned InitialArgSize = Args.size();
4574 // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of
4575 // the argument and parameter match or the objc method is parameterized.
4576 assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) ||
4577 getContext().hasSameUnqualifiedType((*Arg)->getType(),
4578 ArgTypes[Idx]) ||
4579 (isa<ObjCMethodDecl>(AC.getDecl()) &&
4580 isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) &&
4581 "Argument and parameter types don't match");
4582 EmitCallArg(Args, *Arg, ArgTypes[Idx]);
4583 // In particular, we depend on it being the last arg in Args, and the
4584 // objectsize bits depend on there only being one arg if !LeftToRight.
4585 assert(InitialArgSize + 1 == Args.size() &&
4586 "The code below depends on only adding one arg per EmitCallArg");
4587 (void)InitialArgSize;
4588 // Since pointer argument are never emitted as LValue, it is safe to emit
4589 // non-null argument check for r-value only.
4590 if (!Args.back().hasLValue()) {
4591 RValue RVArg = Args.back().getKnownRValue();
4592 EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
4593 ParamsToSkip + Idx);
4594 // @llvm.objectsize should never have side-effects and shouldn't need
4595 // destruction/cleanups, so we can safely "emit" it after its arg,
4596 // regardless of right-to-leftness
4597 MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
4598 }
4599 }
4600
4601 if (!LeftToRight) {
4602 // Un-reverse the arguments we just evaluated so they match up with the LLVM
4603 // IR function.
4604 std::reverse(Args.begin() + CallArgsStart, Args.end());
4605 }
4606}
4607
4608namespace {
4609
4610struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
4611 DestroyUnpassedArg(Address Addr, QualType Ty)
4612 : Addr(Addr), Ty(Ty) {}
4613
4614 Address Addr;
4615 QualType Ty;
4616
4617 void Emit(CodeGenFunction &CGF, Flags flags) override {
4619 if (DtorKind == QualType::DK_cxx_destructor) {
4620 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
4621 assert(!Dtor->isTrivial());
4622 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
4623 /*Delegating=*/false, Addr, Ty);
4624 } else {
4625 CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty));
4626 }
4627 }
4628};
4629
4630struct DisableDebugLocationUpdates {
4631 CodeGenFunction &CGF;
4632 bool disabledDebugInfo;
4633 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
4634 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
4635 CGF.disableDebugInfo();
4636 }
4637 ~DisableDebugLocationUpdates() {
4638 if (disabledDebugInfo)
4639 CGF.enableDebugInfo();
4640 }
4641};
4642
4643} // end anonymous namespace
4644
4646 if (!HasLV)
4647 return RV;
4650 LV.isVolatile());
4651 IsUsed = true;
4652 return RValue::getAggregate(Copy.getAddress());
4653}
4654
4656 LValue Dst = CGF.MakeAddrLValue(Addr, Ty);
4657 if (!HasLV && RV.isScalar())
4658 CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*isInit=*/true);
4659 else if (!HasLV && RV.isComplex())
4660 CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true);
4661 else {
4662 auto Addr = HasLV ? LV.getAddress() : RV.getAggregateAddress();
4663 LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty);
4664 // We assume that call args are never copied into subobjects.
4666 HasLV ? LV.isVolatileQualified()
4668 }
4669 IsUsed = true;
4670}
4671
4672void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
4673 QualType type) {
4674 DisableDebugLocationUpdates Dis(*this, E);
4675 if (const ObjCIndirectCopyRestoreExpr *CRE
4676 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
4677 assert(getLangOpts().ObjCAutoRefCount);
4678 return emitWritebackArg(*this, args, CRE);
4679 }
4680
4681 assert(type->isReferenceType() == E->isGLValue() &&
4682 "reference binding to unmaterialized r-value!");
4683
4684 if (E->isGLValue()) {
4685 assert(E->getObjectKind() == OK_Ordinary);
4686 return args.add(EmitReferenceBindingToExpr(E), type);
4687 }
4688
4689 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
4690
4691 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
4692 // However, we still have to push an EH-only cleanup in case we unwind before
4693 // we make it to the call.
4694 if (type->isRecordType() &&
4696 // If we're using inalloca, use the argument memory. Otherwise, use a
4697 // temporary.
4698 AggValueSlot Slot = args.isUsingInAlloca()
4699 ? createPlaceholderSlot(*this, type) : CreateAggTemp(type, "agg.tmp");
4700
4701 bool DestroyedInCallee = true, NeedsCleanup = true;
4702 if (const auto *RD = type->getAsCXXRecordDecl())
4703 DestroyedInCallee = RD->hasNonTrivialDestructor();
4704 else
4705 NeedsCleanup = type.isDestructedType();
4706
4707 if (DestroyedInCallee)
4709
4710 EmitAggExpr(E, Slot);
4711 RValue RV = Slot.asRValue();
4712 args.add(RV, type);
4713
4714 if (DestroyedInCallee && NeedsCleanup) {
4715 // Create a no-op GEP between the placeholder and the cleanup so we can
4716 // RAUW it successfully. It also serves as a marker of the first
4717 // instruction where the cleanup is active.
4718 pushFullExprCleanup<DestroyUnpassedArg>(NormalAndEHCleanup,
4719 Slot.getAddress(), type);
4720 // This unreachable is a temporary marker which will be removed later.
4721 llvm::Instruction *IsActive =
4722 Builder.CreateFlagLoad(llvm::Constant::getNullValue(Int8PtrTy));
4724 }
4725 return;
4726 }
4727
4728 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
4729 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue &&
4730 !type->isArrayParameterType()) {
4731 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
4732 assert(L.isSimple());
4733 args.addUncopiedAggregate(L, type);
4734 return;
4735 }
4736
4737 args.add(EmitAnyExprToTemp(E), type);
4738}
4739
4740QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
4741 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
4742 // implicitly widens null pointer constants that are arguments to varargs
4743 // functions to pointer-sized ints.
4744 if (!getTarget().getTriple().isOSWindows())
4745 return Arg->getType();
4746
4747 if (Arg->getType()->isIntegerType() &&
4748 getContext().getTypeSize(Arg->getType()) <
4749 getContext().getTargetInfo().getPointerWidth(LangAS::Default) &&
4752 return getContext().getIntPtrType();
4753 }
4754
4755 return Arg->getType();
4756}
4757
4758// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4759// optimizer it can aggressively ignore unwind edges.
4760void
4761CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
4762 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
4763 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
4764 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
4766}
4767
4768/// Emits a call to the given no-arguments nounwind runtime function.
4769llvm::CallInst *
4770CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4771 const llvm::Twine &name) {
4772 return EmitNounwindRuntimeCall(callee, ArrayRef<llvm::Value *>(), name);
4773}
4774
4775/// Emits a call to the given nounwind runtime function.
4776llvm::CallInst *
4777CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4778 ArrayRef<Address> args,
4779 const llvm::Twine &name) {
4781 for (auto arg : args)
4782 values.push_back(arg.emitRawPointer(*this));
4783 return EmitNounwindRuntimeCall(callee, values, name);
4784}
4785
4786llvm::CallInst *
4787CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4789 const llvm::Twine &name) {
4790 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
4791 call->setDoesNotThrow();
4792 return call;
4793}
4794
4795/// Emits a simple call (never an invoke) to the given no-arguments
4796/// runtime function.
4797llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
4798 const llvm::Twine &name) {
4799 return EmitRuntimeCall(callee, std::nullopt, name);
4800}
4801
4802// Calls which may throw must have operand bundles indicating which funclet
4803// they are nested within.
4805CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) {
4806 // There is no need for a funclet operand bundle if we aren't inside a
4807 // funclet.
4808 if (!CurrentFuncletPad)
4810
4811 // Skip intrinsics which cannot throw (as long as they don't lower into
4812 // regular function calls in the course of IR transformations).
4813 if (auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts())) {
4814 if (CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow()) {
4815 auto IID = CalleeFn->getIntrinsicID();
4816 if (!llvm::IntrinsicInst::mayLowerToFunctionCall(IID))
4818 }
4819 }
4820
4822 BundleList.emplace_back("funclet", CurrentFuncletPad);
4823 return BundleList;
4824}
4825
4826/// Emits a simple call (never an invoke) to the given runtime function.
4827llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
4829 const llvm::Twine &name) {
4830 llvm::CallInst *call = Builder.CreateCall(
4831 callee, args, getBundlesForFunclet(callee.getCallee()), name);
4832 call->setCallingConv(getRuntimeCC());
4833
4834 if (CGM.shouldEmitConvergenceTokens() && call->isConvergent())
4835 return addControlledConvergenceToken(call);
4836 return call;
4837}
4838
4839/// Emits a call or invoke to the given noreturn runtime function.
4841 llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) {
4843 getBundlesForFunclet(callee.getCallee());
4844
4845 if (getInvokeDest()) {
4846 llvm::InvokeInst *invoke =
4847 Builder.CreateInvoke(callee,
4849 getInvokeDest(),
4850 args,
4851 BundleList);
4852 invoke->setDoesNotReturn();
4853 invoke->setCallingConv(getRuntimeCC());
4854 } else {
4855 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
4856 call->setDoesNotReturn();
4857 call->setCallingConv(getRuntimeCC());
4858 Builder.CreateUnreachable();
4859 }
4860}
4861
4862/// Emits a call or invoke instruction to the given nullary runtime function.
4863llvm::CallBase *
4864CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4865 const Twine &name) {
4866 return EmitRuntimeCallOrInvoke(callee, std::nullopt, name);
4867}
4868
4869/// Emits a call or invoke instruction to the given runtime function.
4870llvm::CallBase *
4871CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4873 const Twine &name) {
4874 llvm::CallBase *call = EmitCallOrInvoke(callee, args, name);
4875 call->setCallingConv(getRuntimeCC());
4876 return call;
4877}
4878
4879/// Emits a call or invoke instruction to the given function, depending
4880/// on the current state of the EH stack.
4881llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee,
4883 const Twine &Name) {
4884 llvm::BasicBlock *InvokeDest = getInvokeDest();
4886 getBundlesForFunclet(Callee.getCallee());
4887
4888 llvm::CallBase *Inst;
4889 if (!InvokeDest)
4890 Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
4891 else {
4892 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
4893 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
4894 Name);
4895 EmitBlock(ContBB);
4896 }
4897
4898 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4899 // optimizer it can aggressively ignore unwind edges.
4900 if (CGM.getLangOpts().ObjCAutoRefCount)
4901 AddObjCARCExceptionMetadata(Inst);
4902
4903 return Inst;
4904}
4905
4906void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
4907 llvm::Value *New) {
4908 DeferredReplacements.push_back(
4909 std::make_pair(llvm::WeakTrackingVH(Old), New));
4910}
4911
4912namespace {
4913
4914/// Specify given \p NewAlign as the alignment of return value attribute. If
4915/// such attribute already exists, re-set it to the maximal one of two options.
4916[[nodiscard]] llvm::AttributeList
4917maybeRaiseRetAlignmentAttribute(llvm::LLVMContext &Ctx,
4918 const llvm::AttributeList &Attrs,
4919 llvm::Align NewAlign) {
4920 llvm::Align CurAlign = Attrs.getRetAlignment().valueOrOne();
4921 if (CurAlign >= NewAlign)
4922 return Attrs;
4923 llvm::Attribute AlignAttr = llvm::Attribute::getWithAlignment(Ctx, NewAlign);
4924 return Attrs.removeRetAttribute(Ctx, llvm::Attribute::AttrKind::Alignment)
4925 .addRetAttribute(Ctx, AlignAttr);
4926}
4927
4928template <typename AlignedAttrTy> class AbstractAssumeAlignedAttrEmitter {
4929protected:
4930 CodeGenFunction &CGF;
4931
4932 /// We do nothing if this is, or becomes, nullptr.
4933 const AlignedAttrTy *AA = nullptr;
4934
4935 llvm::Value *Alignment = nullptr; // May or may not be a constant.
4936 llvm::ConstantInt *OffsetCI = nullptr; // Constant, hopefully zero.
4937
4938 AbstractAssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
4939 : CGF(CGF_) {
4940 if (!FuncDecl)
4941 return;
4942 AA = FuncDecl->getAttr<AlignedAttrTy>();
4943 }
4944
4945public:
4946 /// If we can, materialize the alignment as an attribute on return value.
4947 [[nodiscard]] llvm::AttributeList
4948 TryEmitAsCallSiteAttribute(const llvm::AttributeList &Attrs) {
4949 if (!AA || OffsetCI || CGF.SanOpts.has(SanitizerKind::Alignment))
4950 return Attrs;
4951 const auto *AlignmentCI = dyn_cast<llvm::ConstantInt>(Alignment);
4952 if (!AlignmentCI)
4953 return Attrs;
4954 // We may legitimately have non-power-of-2 alignment here.
4955 // If so, this is UB land, emit it via `@llvm.assume` instead.
4956 if (!AlignmentCI->getValue().isPowerOf2())
4957 return Attrs;
4958 llvm::AttributeList NewAttrs = maybeRaiseRetAlignmentAttribute(
4959 CGF.getLLVMContext(), Attrs,
4960 llvm::Align(
4961 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment)));
4962 AA = nullptr; // We're done. Disallow doing anything else.
4963 return NewAttrs;
4964 }
4965
4966 /// Emit alignment assumption.
4967 /// This is a general fallback that we take if either there is an offset,
4968 /// or the alignment is variable or we are sanitizing for alignment.
4969 void EmitAsAnAssumption(SourceLocation Loc, QualType RetTy, RValue &Ret) {
4970 if (!AA)
4971 return;
4972 CGF.emitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc,
4973 AA->getLocation(), Alignment, OffsetCI);
4974 AA = nullptr; // We're done. Disallow doing anything else.
4975 }
4976};
4977
4978/// Helper data structure to emit `AssumeAlignedAttr`.
4979class AssumeAlignedAttrEmitter final
4980 : public AbstractAssumeAlignedAttrEmitter<AssumeAlignedAttr> {
4981public:
4982 AssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
4983 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
4984 if (!AA)
4985 return;
4986 // It is guaranteed that the alignment/offset are constants.
4987 Alignment = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AA->getAlignment()));
4988 if (Expr *Offset = AA->getOffset()) {
4989 OffsetCI = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(Offset));
4990 if (OffsetCI->isNullValue()) // Canonicalize zero offset to no offset.
4991 OffsetCI = nullptr;
4992 }
4993 }
4994};
4995
4996/// Helper data structure to emit `AllocAlignAttr`.
4997class AllocAlignAttrEmitter final
4998 : public AbstractAssumeAlignedAttrEmitter<AllocAlignAttr> {
4999public:
5000 AllocAlignAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl,
5001 const CallArgList &CallArgs)
5002 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
5003 if (!AA)
5004 return;
5005 // Alignment may or may not be a constant, and that is okay.
5006 Alignment = CallArgs[AA->getParamIndex().getLLVMIndex()]
5007 .getRValue(CGF)
5008 .getScalarVal();
5009 }
5010};
5011
5012} // namespace
5013
5014static unsigned getMaxVectorWidth(const llvm::Type *Ty) {
5015 if (auto *VT = dyn_cast<llvm::VectorType>(Ty))
5016 return VT->getPrimitiveSizeInBits().getKnownMinValue();
5017 if (auto *AT = dyn_cast<llvm::ArrayType>(Ty))
5018 return getMaxVectorWidth(AT->getElementType());
5019
5020 unsigned MaxVectorWidth = 0;
5021 if (auto *ST = dyn_cast<llvm::StructType>(Ty))
5022 for (auto *I : ST->elements())
5023 MaxVectorWidth = std::max(MaxVectorWidth, getMaxVectorWidth(I));
5024 return MaxVectorWidth;
5025}
5026
5028 const CGCallee &Callee,
5029 ReturnValueSlot ReturnValue,
5030 const CallArgList &CallArgs,
5031 llvm::CallBase **callOrInvoke, bool IsMustTail,
5033 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
5034
5035 assert(Callee.isOrdinary() || Callee.isVirtual());
5036
5037 // Handle struct-return functions by passing a pointer to the
5038 // location that we would like to return into.
5039 QualType RetTy = CallInfo.getReturnType();
5040 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
5041
5042 llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
5043
5044 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
5045 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
5046 // We can only guarantee that a function is called from the correct
5047 // context/function based on the appropriate target attributes,
5048 // so only check in the case where we have both always_inline and target
5049 // since otherwise we could be making a conditional call after a check for
5050 // the proper cpu features (and it won't cause code generation issues due to
5051 // function based code generation).
5052 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
5053 (TargetDecl->hasAttr<TargetAttr>() ||
5054 (CurFuncDecl && CurFuncDecl->hasAttr<TargetAttr>())))
5056 }
5057
5058 // Some architectures (such as x86-64) have the ABI changed based on
5059 // attribute-target/features. Give them a chance to diagnose.
5061 CGM, Loc, dyn_cast_or_null<FunctionDecl>(CurCodeDecl),
5062 dyn_cast_or_null<FunctionDecl>(TargetDecl), CallArgs, RetTy);
5063
5064 // 1. Set up the arguments.
5065
5066 // If we're using inalloca, insert the allocation after the stack save.
5067 // FIXME: Do this earlier rather than hacking it in here!
5068 RawAddress ArgMemory = RawAddress::invalid();
5069 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
5070 const llvm::DataLayout &DL = CGM.getDataLayout();
5071 llvm::Instruction *IP = CallArgs.getStackBase();
5072 llvm::AllocaInst *AI;
5073 if (IP) {
5074 IP = IP->getNextNode();
5075 AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(),
5076 "argmem", IP);
5077 } else {
5078 AI = CreateTempAlloca(ArgStruct, "argmem");
5079 }
5080 auto Align = CallInfo.getArgStructAlignment();
5081 AI->setAlignment(Align.getAsAlign());
5082 AI->setUsedWithInAlloca(true);
5083 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
5084 ArgMemory = RawAddress(AI, ArgStruct, Align);
5085 }
5086
5087 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
5088 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
5089
5090 // If the call returns a temporary with struct return, create a temporary
5091 // alloca to hold the result, unless one is given to us.
5092 Address SRetPtr = Address::invalid();
5093 RawAddress SRetAlloca = RawAddress::invalid();
5094 llvm::Value *UnusedReturnSizePtr = nullptr;
5095 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
5096 if (!ReturnValue.isNull()) {
5097 SRetPtr = ReturnValue.getAddress();
5098 } else {
5099 SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca);
5100 if (HaveInsertPoint() && ReturnValue.isUnused()) {
5101 llvm::TypeSize size =
5102 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
5103 UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer());
5104 }
5105 }
5106 if (IRFunctionArgs.hasSRetArg()) {
5107 IRCallArgs[IRFunctionArgs.getSRetArgNo()] =<