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