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, std::nullopt,
122 FTNP->getExtInfo(), {}, RequiredArgs(0));
123}
124
127 const FunctionProtoType *proto,
128 unsigned prefixArgs,
129 unsigned totalArgs) {
130 assert(proto->hasExtParameterInfos());
131 assert(paramInfos.size() <= prefixArgs);
132 assert(proto->getNumParams() + prefixArgs <= totalArgs);
133
134 paramInfos.reserve(totalArgs);
135
136 // Add default infos for any prefix args that don't already have infos.
137 paramInfos.resize(prefixArgs);
138
139 // Add infos for the prototype.
140 for (const auto &ParamInfo : proto->getExtParameterInfos()) {
141 paramInfos.push_back(ParamInfo);
142 // pass_object_size params have no parameter info.
143 if (ParamInfo.hasPassObjectSize())
144 paramInfos.emplace_back();
145 }
146
147 assert(paramInfos.size() <= totalArgs &&
148 "Did we forget to insert pass_object_size args?");
149 // Add default infos for the variadic and/or suffix arguments.
150 paramInfos.resize(totalArgs);
151}
152
153/// Adds the formal parameters in FPT to the given prefix. If any parameter in
154/// FPT has pass_object_size attrs, then we'll add parameters for those, too.
155static void appendParameterTypes(const CodeGenTypes &CGT,
159 // Fast path: don't touch param info if we don't need to.
160 if (!FPT->hasExtParameterInfos()) {
161 assert(paramInfos.empty() &&
162 "We have paramInfos, but the prototype doesn't?");
163 prefix.append(FPT->param_type_begin(), FPT->param_type_end());
164 return;
165 }
166
167 unsigned PrefixSize = prefix.size();
168 // In the vast majority of cases, we'll have precisely FPT->getNumParams()
169 // parameters; the only thing that can change this is the presence of
170 // pass_object_size. So, we preallocate for the common case.
171 prefix.reserve(prefix.size() + FPT->getNumParams());
172
173 auto ExtInfos = FPT->getExtParameterInfos();
174 assert(ExtInfos.size() == FPT->getNumParams());
175 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
176 prefix.push_back(FPT->getParamType(I));
177 if (ExtInfos[I].hasPassObjectSize())
178 prefix.push_back(CGT.getContext().getSizeType());
179 }
180
181 addExtParameterInfosForCall(paramInfos, FPT.getTypePtr(), PrefixSize,
182 prefix.size());
183}
184
185/// Arrange the LLVM function layout for a value of the given function
186/// type, on top of any implicit parameters already stored.
187static const CGFunctionInfo &
188arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
193 // FIXME: Kill copy.
194 appendParameterTypes(CGT, prefix, paramInfos, FTP);
195 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
196
197 FnInfoOpts opts =
199 return CGT.arrangeLLVMFunctionInfo(resultType, opts, prefix,
200 FTP->getExtInfo(), paramInfos, Required);
201}
202
203/// Arrange the argument and result information for a value of the
204/// given freestanding function type.
205const CGFunctionInfo &
208 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
209 FTP);
210}
211
213 bool IsWindows) {
214 // Set the appropriate calling convention for the Function.
215 if (D->hasAttr<StdCallAttr>())
216 return CC_X86StdCall;
217
218 if (D->hasAttr<FastCallAttr>())
219 return CC_X86FastCall;
220
221 if (D->hasAttr<RegCallAttr>())
222 return CC_X86RegCall;
223
224 if (D->hasAttr<ThisCallAttr>())
225 return CC_X86ThisCall;
226
227 if (D->hasAttr<VectorCallAttr>())
228 return CC_X86VectorCall;
229
230 if (D->hasAttr<PascalAttr>())
231 return CC_X86Pascal;
232
233 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
234 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
235
236 if (D->hasAttr<AArch64VectorPcsAttr>())
238
239 if (D->hasAttr<AArch64SVEPcsAttr>())
240 return CC_AArch64SVEPCS;
241
242 if (D->hasAttr<AMDGPUKernelCallAttr>())
243 return CC_AMDGPUKernelCall;
244
245 if (D->hasAttr<IntelOclBiccAttr>())
246 return CC_IntelOclBicc;
247
248 if (D->hasAttr<MSABIAttr>())
249 return IsWindows ? CC_C : CC_Win64;
250
251 if (D->hasAttr<SysVABIAttr>())
252 return IsWindows ? CC_X86_64SysV : CC_C;
253
254 if (D->hasAttr<PreserveMostAttr>())
255 return CC_PreserveMost;
256
257 if (D->hasAttr<PreserveAllAttr>())
258 return CC_PreserveAll;
259
260 if (D->hasAttr<M68kRTDAttr>())
261 return CC_M68kRTD;
262
263 if (D->hasAttr<PreserveNoneAttr>())
264 return CC_PreserveNone;
265
266 if (D->hasAttr<RISCVVectorCCAttr>())
267 return CC_RISCVVectorCall;
268
269 return CC_C;
270}
271
272/// Arrange the argument and result information for a call to an
273/// unknown C++ non-static member function of the given abstract type.
274/// (A null RD means we don't have any meaningful "this" argument type,
275/// so fall back to a generic pointer type).
276/// The member function must be an ordinary function, i.e. not a
277/// constructor or destructor.
278const CGFunctionInfo &
280 const FunctionProtoType *FTP,
281 const CXXMethodDecl *MD) {
283
284 // Add the 'this' pointer.
285 argTypes.push_back(DeriveThisType(RD, MD));
286
287 return ::arrangeLLVMFunctionInfo(
288 *this, /*instanceMethod=*/true, argTypes,
290}
291
292/// Set calling convention for CUDA/HIP kernel.
294 const FunctionDecl *FD) {
295 if (FD->hasAttr<CUDAGlobalAttr>()) {
296 const FunctionType *FT = FTy->getAs<FunctionType>();
298 FTy = FT->getCanonicalTypeUnqualified();
299 }
300}
301
302/// Arrange the argument and result information for a declaration or
303/// definition of the given C++ non-static member function. The
304/// member function must be an ordinary function, i.e. not a
305/// constructor or destructor.
306const CGFunctionInfo &
308 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
309 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
310
313 auto prototype = FT.getAs<FunctionProtoType>();
314
316 // The abstract case is perfectly fine.
317 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
318 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
319 }
320
321 return arrangeFreeFunctionType(prototype);
322}
323
325 const InheritedConstructor &Inherited, CXXCtorType Type) {
326 // Parameters are unnecessary if we're constructing a base class subobject
327 // and the inherited constructor lives in a virtual base.
328 return Type == Ctor_Complete ||
329 !Inherited.getShadowDecl()->constructsVirtualBase() ||
330 !Target.getCXXABI().hasConstructorVariants();
331}
332
333const CGFunctionInfo &
335 auto *MD = cast<CXXMethodDecl>(GD.getDecl());
336
339
340 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(GD);
341 argTypes.push_back(DeriveThisType(ThisType, MD));
342
343 bool PassParams = true;
344
345 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
346 // A base class inheriting constructor doesn't get forwarded arguments
347 // needed to construct a virtual base (or base class thereof).
348 if (auto Inherited = CD->getInheritedConstructor())
349 PassParams = inheritingCtorHasParams(Inherited, GD.getCtorType());
350 }
351
353
354 // Add the formal parameters.
355 if (PassParams)
356 appendParameterTypes(*this, argTypes, paramInfos, FTP);
357
359 TheCXXABI.buildStructorSignature(GD, argTypes);
360 if (!paramInfos.empty()) {
361 // Note: prefix implies after the first param.
362 if (AddedArgs.Prefix)
363 paramInfos.insert(paramInfos.begin() + 1, AddedArgs.Prefix,
365 if (AddedArgs.Suffix)
366 paramInfos.append(AddedArgs.Suffix,
368 }
369
370 RequiredArgs required =
371 (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
373
374 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
375 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
376 ? argTypes.front()
377 : TheCXXABI.hasMostDerivedReturn(GD)
378 ? CGM.getContext().VoidPtrTy
379 : Context.VoidTy;
381 argTypes, extInfo, paramInfos, required);
382}
383
387 for (auto &arg : args)
388 argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
389 return argTypes;
390}
391
395 for (auto &arg : args)
396 argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
397 return argTypes;
398}
399
402 unsigned prefixArgs, unsigned totalArgs) {
404 if (proto->hasExtParameterInfos()) {
405 addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
406 }
407 return result;
408}
409
410/// Arrange a call to a C++ method, passing the given arguments.
411///
412/// ExtraPrefixArgs is the number of ABI-specific args passed after the `this`
413/// parameter.
414/// ExtraSuffixArgs is the number of ABI-specific args passed at the end of
415/// args.
416/// PassProtoArgs indicates whether `args` has args for the parameters in the
417/// given CXXConstructorDecl.
418const CGFunctionInfo &
420 const CXXConstructorDecl *D,
421 CXXCtorType CtorKind,
422 unsigned ExtraPrefixArgs,
423 unsigned ExtraSuffixArgs,
424 bool PassProtoArgs) {
425 // FIXME: Kill copy.
427 for (const auto &Arg : args)
428 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
429
430 // +1 for implicit this, which should always be args[0].
431 unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs;
432
434 RequiredArgs Required = PassProtoArgs
436 FPT, TotalPrefixArgs + ExtraSuffixArgs)
438
439 GlobalDecl GD(D, CtorKind);
440 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
441 ? ArgTypes.front()
442 : TheCXXABI.hasMostDerivedReturn(GD)
443 ? CGM.getContext().VoidPtrTy
444 : Context.VoidTy;
445
446 FunctionType::ExtInfo Info = FPT->getExtInfo();
448 // If the prototype args are elided, we should only have ABI-specific args,
449 // which never have param info.
450 if (PassProtoArgs && FPT->hasExtParameterInfos()) {
451 // ABI-specific suffix arguments are treated the same as variadic arguments.
452 addExtParameterInfosForCall(ParamInfos, FPT.getTypePtr(), TotalPrefixArgs,
453 ArgTypes.size());
454 }
455
457 ArgTypes, Info, ParamInfos, Required);
458}
459
460/// Arrange the argument and result information for the declaration or
461/// definition of the given function.
462const CGFunctionInfo &
464 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
465 if (MD->isImplicitObjectMemberFunction())
467
469
470 assert(isa<FunctionType>(FTy));
471 setCUDAKernelCallingConvention(FTy, CGM, FD);
472
473 // When declaring a function without a prototype, always use a
474 // non-variadic type.
476 return arrangeLLVMFunctionInfo(noProto->getReturnType(), FnInfoOpts::None,
477 std::nullopt, noProto->getExtInfo(), {},
479 }
480
482}
483
484/// Arrange the argument and result information for the declaration or
485/// definition of an Objective-C method.
486const CGFunctionInfo &
488 // It happens that this is the same as a call with no optional
489 // arguments, except also using the formal 'self' type.
491}
492
493/// Arrange the argument and result information for the function type
494/// through which to perform a send to the given Objective-C method,
495/// using the given receiver type. The receiver type is not always
496/// the 'self' type of the method or even an Objective-C pointer type.
497/// This is *not* the right method for actually performing such a
498/// message send, due to the possibility of optional arguments.
499const CGFunctionInfo &
501 QualType receiverType) {
504 MD->isDirectMethod() ? 1 : 2);
505 argTys.push_back(Context.getCanonicalParamType(receiverType));
506 if (!MD->isDirectMethod())
507 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
508 // FIXME: Kill copy?
509 for (const auto *I : MD->parameters()) {
510 argTys.push_back(Context.getCanonicalParamType(I->getType()));
512 I->hasAttr<NoEscapeAttr>());
513 extParamInfos.push_back(extParamInfo);
514 }
515
517 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
518 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
519
520 if (getContext().getLangOpts().ObjCAutoRefCount &&
521 MD->hasAttr<NSReturnsRetainedAttr>())
522 einfo = einfo.withProducesResult(true);
523
524 RequiredArgs required =
525 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
526
528 FnInfoOpts::None, argTys, einfo, extParamInfos,
529 required);
530}
531
532const CGFunctionInfo &
534 const CallArgList &args) {
535 auto argTypes = getArgTypesForCall(Context, args);
537
539 argTypes, einfo, {}, RequiredArgs::All);
540}
541
542const CGFunctionInfo &
544 // FIXME: Do we need to handle ObjCMethodDecl?
545 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
546
547 if (isa<CXXConstructorDecl>(GD.getDecl()) ||
548 isa<CXXDestructorDecl>(GD.getDecl()))
550
552}
553
554/// Arrange a thunk that takes 'this' as the first parameter followed by
555/// varargs. Return a void pointer, regardless of the actual return type.
556/// The body of the thunk will end in a musttail call to a function of the
557/// correct type, and the caller will bitcast the function to the correct
558/// prototype.
559const CGFunctionInfo &
561 assert(MD->isVirtual() && "only methods have thunks");
563 CanQualType ArgTys[] = {DeriveThisType(MD->getParent(), MD)};
564 return arrangeLLVMFunctionInfo(Context.VoidTy, FnInfoOpts::None, ArgTys,
565 FTP->getExtInfo(), {}, RequiredArgs(1));
566}
567
568const CGFunctionInfo &
570 CXXCtorType CT) {
571 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
572
575 const CXXRecordDecl *RD = CD->getParent();
576 ArgTys.push_back(DeriveThisType(RD, CD));
577 if (CT == Ctor_CopyingClosure)
578 ArgTys.push_back(*FTP->param_type_begin());
579 if (RD->getNumVBases() > 0)
580 ArgTys.push_back(Context.IntTy);
582 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
584 ArgTys, FunctionType::ExtInfo(CC), {},
586}
587
588/// Arrange a call as unto a free function, except possibly with an
589/// additional number of formal parameters considered required.
590static const CGFunctionInfo &
592 CodeGenModule &CGM,
593 const CallArgList &args,
594 const FunctionType *fnType,
595 unsigned numExtraRequiredArgs,
596 bool chainCall) {
597 assert(args.size() >= numExtraRequiredArgs);
598
600
601 // In most cases, there are no optional arguments.
603
604 // If we have a variadic prototype, the required arguments are the
605 // extra prefix plus the arguments in the prototype.
606 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
607 if (proto->isVariadic())
608 required = RequiredArgs::forPrototypePlus(proto, numExtraRequiredArgs);
609
610 if (proto->hasExtParameterInfos())
611 addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
612 args.size());
613
614 // If we don't have a prototype at all, but we're supposed to
615 // explicitly use the variadic convention for unprototyped calls,
616 // treat all of the arguments as required but preserve the nominal
617 // possibility of variadics.
618 } else if (CGM.getTargetCodeGenInfo()
620 cast<FunctionNoProtoType>(fnType))) {
621 required = RequiredArgs(args.size());
622 }
623
624 // FIXME: Kill copy.
626 for (const auto &arg : args)
627 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
630 opts, argTypes, fnType->getExtInfo(),
631 paramInfos, required);
632}
633
634/// Figure out the rules for calling a function with the given formal
635/// type using the given arguments. The arguments are necessary
636/// because the function might be unprototyped, in which case it's
637/// target-dependent in crazy ways.
638const CGFunctionInfo &
640 const FunctionType *fnType,
641 bool chainCall) {
642 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
643 chainCall ? 1 : 0, chainCall);
644}
645
646/// A block function is essentially a free function with an
647/// extra implicit argument.
648const CGFunctionInfo &
650 const FunctionType *fnType) {
651 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
652 /*chainCall=*/false);
653}
654
655const CGFunctionInfo &
657 const FunctionArgList &params) {
658 auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
659 auto argTypes = getArgTypesForDeclaration(Context, params);
660
662 FnInfoOpts::None, argTypes,
663 proto->getExtInfo(), paramInfos,
665}
666
667const CGFunctionInfo &
669 const CallArgList &args) {
670 // FIXME: Kill copy.
672 for (const auto &Arg : args)
673 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
675 argTypes, FunctionType::ExtInfo(),
676 /*paramInfos=*/{}, RequiredArgs::All);
677}
678
679const CGFunctionInfo &
681 const FunctionArgList &args) {
682 auto argTypes = getArgTypesForDeclaration(Context, args);
683
685 argTypes, FunctionType::ExtInfo(), {},
687}
688
689const CGFunctionInfo &
691 ArrayRef<CanQualType> argTypes) {
692 return arrangeLLVMFunctionInfo(resultType, FnInfoOpts::None, argTypes,
695}
696
697/// Arrange a call to a C++ method, passing the given arguments.
698///
699/// numPrefixArgs is the number of ABI-specific prefix arguments we have. It
700/// does not count `this`.
701const CGFunctionInfo &
703 const FunctionProtoType *proto,
704 RequiredArgs required,
705 unsigned numPrefixArgs) {
706 assert(numPrefixArgs + 1 <= args.size() &&
707 "Emitting a call with less args than the required prefix?");
708 // Add one to account for `this`. It's a bit awkward here, but we don't count
709 // `this` in similar places elsewhere.
710 auto paramInfos =
711 getExtParameterInfosForCall(proto, numPrefixArgs + 1, args.size());
712
713 // FIXME: Kill copy.
714 auto argTypes = getArgTypesForCall(Context, args);
715
716 FunctionType::ExtInfo info = proto->getExtInfo();
718 FnInfoOpts::IsInstanceMethod, argTypes, info,
719 paramInfos, required);
720}
721
724 std::nullopt, FunctionType::ExtInfo(), {},
726}
727
728const CGFunctionInfo &
730 const CallArgList &args) {
731 assert(signature.arg_size() <= args.size());
732 if (signature.arg_size() == args.size())
733 return signature;
734
736 auto sigParamInfos = signature.getExtParameterInfos();
737 if (!sigParamInfos.empty()) {
738 paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
739 paramInfos.resize(args.size());
740 }
741
742 auto argTypes = getArgTypesForCall(Context, args);
743
744 assert(signature.getRequiredArgs().allowsOptionalArgs());
746 if (signature.isInstanceMethod())
748 if (signature.isChainCall())
750 if (signature.isDelegateCall())
752 return arrangeLLVMFunctionInfo(signature.getReturnType(), opts, argTypes,
753 signature.getExtInfo(), paramInfos,
754 signature.getRequiredArgs());
755}
756
757namespace clang {
758namespace CodeGen {
760}
761}
762
763/// Arrange the argument and result information for an abstract value
764/// of a given function type. This is the method which all of the
765/// above functions ultimately defer to.
767 CanQualType resultType, FnInfoOpts opts, ArrayRef<CanQualType> argTypes,
770 RequiredArgs required) {
771 assert(llvm::all_of(argTypes,
772 [](CanQualType T) { return T.isCanonicalAsParam(); }));
773
774 // Lookup or create unique function info.
775 llvm::FoldingSetNodeID ID;
776 bool isInstanceMethod =
778 bool isChainCall =
780 bool isDelegateCall =
782 CGFunctionInfo::Profile(ID, isInstanceMethod, isChainCall, isDelegateCall,
783 info, paramInfos, required, resultType, argTypes);
784
785 void *insertPos = nullptr;
786 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
787 if (FI)
788 return *FI;
789
790 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
791
792 // Construct the function info. We co-allocate the ArgInfos.
793 FI = CGFunctionInfo::create(CC, isInstanceMethod, isChainCall, isDelegateCall,
794 info, paramInfos, resultType, argTypes, required);
795 FunctionInfos.InsertNode(FI, insertPos);
796
797 bool inserted = FunctionsBeingProcessed.insert(FI).second;
798 (void)inserted;
799 assert(inserted && "Recursively being processed?");
800
801 // Compute ABI information.
802 if (CC == llvm::CallingConv::SPIR_KERNEL) {
803 // Force target independent argument handling for the host visible
804 // kernel functions.
805 computeSPIRKernelABIInfo(CGM, *FI);
806 } else if (info.getCC() == CC_Swift || info.getCC() == CC_SwiftAsync) {
808 } else {
809 getABIInfo().computeInfo(*FI);
810 }
811
812 // Loop over all of the computed argument and return value info. If any of
813 // them are direct or extend without a specified coerce type, specify the
814 // default now.
815 ABIArgInfo &retInfo = FI->getReturnInfo();
816 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
818
819 for (auto &I : FI->arguments())
820 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
821 I.info.setCoerceToType(ConvertType(I.type));
822
823 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
824 assert(erased && "Not in set?");
825
826 return *FI;
827}
828
829CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC, bool instanceMethod,
830 bool chainCall, bool delegateCall,
831 const FunctionType::ExtInfo &info,
833 CanQualType resultType,
834 ArrayRef<CanQualType> argTypes,
835 RequiredArgs required) {
836 assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
837 assert(!required.allowsOptionalArgs() ||
838 required.getNumRequiredArgs() <= argTypes.size());
839
840 void *buffer =
841 operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
842 argTypes.size() + 1, paramInfos.size()));
843
844 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
845 FI->CallingConvention = llvmCC;
846 FI->EffectiveCallingConvention = llvmCC;
847 FI->ASTCallingConvention = info.getCC();
848 FI->InstanceMethod = instanceMethod;
849 FI->ChainCall = chainCall;
850 FI->DelegateCall = delegateCall;
851 FI->CmseNSCall = info.getCmseNSCall();
852 FI->NoReturn = info.getNoReturn();
853 FI->ReturnsRetained = info.getProducesResult();
854 FI->NoCallerSavedRegs = info.getNoCallerSavedRegs();
855 FI->NoCfCheck = info.getNoCfCheck();
856 FI->Required = required;
857 FI->HasRegParm = info.getHasRegParm();
858 FI->RegParm = info.getRegParm();
859 FI->ArgStruct = nullptr;
860 FI->ArgStructAlign = 0;
861 FI->NumArgs = argTypes.size();
862 FI->HasExtParameterInfos = !paramInfos.empty();
863 FI->getArgsBuffer()[0].type = resultType;
864 FI->MaxVectorWidth = 0;
865 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
866 FI->getArgsBuffer()[i + 1].type = argTypes[i];
867 for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
868 FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
869 return FI;
870}
871
872/***/
873
874namespace {
875// ABIArgInfo::Expand implementation.
876
877// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
878struct TypeExpansion {
879 enum TypeExpansionKind {
880 // Elements of constant arrays are expanded recursively.
881 TEK_ConstantArray,
882 // Record fields are expanded recursively (but if record is a union, only
883 // the field with the largest size is expanded).
884 TEK_Record,
885 // For complex types, real and imaginary parts are expanded recursively.
887 // All other types are not expandable.
888 TEK_None
889 };
890
891 const TypeExpansionKind Kind;
892
893 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
894 virtual ~TypeExpansion() {}
895};
896
897struct ConstantArrayExpansion : TypeExpansion {
898 QualType EltTy;
899 uint64_t NumElts;
900
901 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
902 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
903 static bool classof(const TypeExpansion *TE) {
904 return TE->Kind == TEK_ConstantArray;
905 }
906};
907
908struct RecordExpansion : TypeExpansion {
910
912
913 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
915 : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
916 Fields(std::move(Fields)) {}
917 static bool classof(const TypeExpansion *TE) {
918 return TE->Kind == TEK_Record;
919 }
920};
921
922struct ComplexExpansion : TypeExpansion {
923 QualType EltTy;
924
925 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
926 static bool classof(const TypeExpansion *TE) {
927 return TE->Kind == TEK_Complex;
928 }
929};
930
931struct NoExpansion : TypeExpansion {
932 NoExpansion() : TypeExpansion(TEK_None) {}
933 static bool classof(const TypeExpansion *TE) {
934 return TE->Kind == TEK_None;
935 }
936};
937} // namespace
938
939static std::unique_ptr<TypeExpansion>
941 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
942 return std::make_unique<ConstantArrayExpansion>(AT->getElementType(),
943 AT->getZExtSize());
944 }
945 if (const RecordType *RT = Ty->getAs<RecordType>()) {
948 const RecordDecl *RD = RT->getDecl();
949 assert(!RD->hasFlexibleArrayMember() &&
950 "Cannot expand structure with flexible array.");
951 if (RD->isUnion()) {
952 // Unions can be here only in degenerative cases - all the fields are same
953 // after flattening. Thus we have to use the "largest" field.
954 const FieldDecl *LargestFD = nullptr;
955 CharUnits UnionSize = CharUnits::Zero();
956
957 for (const auto *FD : RD->fields()) {
958 if (FD->isZeroLengthBitField(Context))
959 continue;
960 assert(!FD->isBitField() &&
961 "Cannot expand structure with bit-field members.");
962 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
963 if (UnionSize < FieldSize) {
964 UnionSize = FieldSize;
965 LargestFD = FD;
966 }
967 }
968 if (LargestFD)
969 Fields.push_back(LargestFD);
970 } else {
971 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
972 assert(!CXXRD->isDynamicClass() &&
973 "cannot expand vtable pointers in dynamic classes");
974 llvm::append_range(Bases, llvm::make_pointer_range(CXXRD->bases()));
975 }
976
977 for (const auto *FD : RD->fields()) {
978 if (FD->isZeroLengthBitField(Context))
979 continue;
980 assert(!FD->isBitField() &&
981 "Cannot expand structure with bit-field members.");
982 Fields.push_back(FD);
983 }
984 }
985 return std::make_unique<RecordExpansion>(std::move(Bases),
986 std::move(Fields));
987 }
988 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
989 return std::make_unique<ComplexExpansion>(CT->getElementType());
990 }
991 return std::make_unique<NoExpansion>();
992}
993
994static int getExpansionSize(QualType Ty, const ASTContext &Context) {
995 auto Exp = getTypeExpansion(Ty, Context);
996 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
997 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
998 }
999 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1000 int Res = 0;
1001 for (auto BS : RExp->Bases)
1002 Res += getExpansionSize(BS->getType(), Context);
1003 for (auto FD : RExp->Fields)
1004 Res += getExpansionSize(FD->getType(), Context);
1005 return Res;
1006 }
1007 if (isa<ComplexExpansion>(Exp.get()))
1008 return 2;
1009 assert(isa<NoExpansion>(Exp.get()));
1010 return 1;
1011}
1012
1013void
1016 auto Exp = getTypeExpansion(Ty, Context);
1017 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1018 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
1019 getExpandedTypes(CAExp->EltTy, TI);
1020 }
1021 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1022 for (auto BS : RExp->Bases)
1023 getExpandedTypes(BS->getType(), TI);
1024 for (auto FD : RExp->Fields)
1025 getExpandedTypes(FD->getType(), TI);
1026 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
1027 llvm::Type *EltTy = ConvertType(CExp->EltTy);
1028 *TI++ = EltTy;
1029 *TI++ = EltTy;
1030 } else {
1031 assert(isa<NoExpansion>(Exp.get()));
1032 *TI++ = ConvertType(Ty);
1033 }
1034}
1035
1037 ConstantArrayExpansion *CAE,
1038 Address BaseAddr,
1039 llvm::function_ref<void(Address)> Fn) {
1040 for (int i = 0, n = CAE->NumElts; i < n; i++) {
1041 Address EltAddr = CGF.Builder.CreateConstGEP2_32(BaseAddr, 0, i);
1042 Fn(EltAddr);
1043 }
1044}
1045
1046void CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
1047 llvm::Function::arg_iterator &AI) {
1048 assert(LV.isSimple() &&
1049 "Unexpected non-simple lvalue during struct expansion.");
1050
1051 auto Exp = getTypeExpansion(Ty, getContext());
1052 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1054 *this, CAExp, LV.getAddress(), [&](Address EltAddr) {
1055 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
1056 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
1057 });
1058 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1059 Address This = LV.getAddress();
1060 for (const CXXBaseSpecifier *BS : RExp->Bases) {
1061 // Perform a single step derived-to-base conversion.
1062 Address Base =
1063 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1064 /*NullCheckValue=*/false, SourceLocation());
1065 LValue SubLV = MakeAddrLValue(Base, BS->getType());
1066
1067 // Recurse onto bases.
1068 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
1069 }
1070 for (auto FD : RExp->Fields) {
1071 // FIXME: What are the right qualifiers here?
1073 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
1074 }
1075 } else if (isa<ComplexExpansion>(Exp.get())) {
1076 auto realValue = &*AI++;
1077 auto imagValue = &*AI++;
1078 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
1079 } else {
1080 // Call EmitStoreOfScalar except when the lvalue is a bitfield to emit a
1081 // primitive store.
1082 assert(isa<NoExpansion>(Exp.get()));
1083 llvm::Value *Arg = &*AI++;
1084 if (LV.isBitField()) {
1086 } else {
1087 // TODO: currently there are some places are inconsistent in what LLVM
1088 // pointer type they use (see D118744). Once clang uses opaque pointers
1089 // all LLVM pointer types will be the same and we can remove this check.
1090 if (Arg->getType()->isPointerTy()) {
1091 Address Addr = LV.getAddress();
1092 Arg = Builder.CreateBitCast(Arg, Addr.getElementType());
1093 }
1094 EmitStoreOfScalar(Arg, LV);
1095 }
1096 }
1097}
1098
1099void CodeGenFunction::ExpandTypeToArgs(
1100 QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
1101 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
1102 auto Exp = getTypeExpansion(Ty, getContext());
1103 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1104 Address Addr = Arg.hasLValue() ? Arg.getKnownLValue().getAddress()
1107 *this, CAExp, Addr, [&](Address EltAddr) {
1108 CallArg EltArg = CallArg(
1109 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation()),
1110 CAExp->EltTy);
1111 ExpandTypeToArgs(CAExp->EltTy, EltArg, IRFuncTy, IRCallArgs,
1112 IRCallArgPos);
1113 });
1114 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1117 for (const CXXBaseSpecifier *BS : RExp->Bases) {
1118 // Perform a single step derived-to-base conversion.
1119 Address Base =
1120 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1121 /*NullCheckValue=*/false, SourceLocation());
1122 CallArg BaseArg = CallArg(RValue::getAggregate(Base), BS->getType());
1123
1124 // Recurse onto bases.
1125 ExpandTypeToArgs(BS->getType(), BaseArg, IRFuncTy, IRCallArgs,
1126 IRCallArgPos);
1127 }
1128
1129 LValue LV = MakeAddrLValue(This, Ty);
1130 for (auto FD : RExp->Fields) {
1131 CallArg FldArg =
1132 CallArg(EmitRValueForField(LV, FD, SourceLocation()), FD->getType());
1133 ExpandTypeToArgs(FD->getType(), FldArg, IRFuncTy, IRCallArgs,
1134 IRCallArgPos);
1135 }
1136 } else if (isa<ComplexExpansion>(Exp.get())) {
1138 IRCallArgs[IRCallArgPos++] = CV.first;
1139 IRCallArgs[IRCallArgPos++] = CV.second;
1140 } else {
1141 assert(isa<NoExpansion>(Exp.get()));
1142 auto RV = Arg.getKnownRValue();
1143 assert(RV.isScalar() &&
1144 "Unexpected non-scalar rvalue during struct expansion.");
1145
1146 // Insert a bitcast as needed.
1147 llvm::Value *V = RV.getScalarVal();
1148 if (IRCallArgPos < IRFuncTy->getNumParams() &&
1149 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
1150 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
1151
1152 IRCallArgs[IRCallArgPos++] = V;
1153 }
1154}
1155
1156/// Create a temporary allocation for the purposes of coercion.
1158 llvm::Type *Ty,
1159 CharUnits MinAlign,
1160 const Twine &Name = "tmp") {
1161 // Don't use an alignment that's worse than what LLVM would prefer.
1162 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(Ty);
1163 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
1164
1165 return CGF.CreateTempAlloca(Ty, Align, Name + ".coerce");
1166}
1167
1168/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
1169/// accessing some number of bytes out of it, try to gep into the struct to get
1170/// at its inner goodness. Dive as deep as possible without entering an element
1171/// with an in-memory size smaller than DstSize.
1172static Address
1174 llvm::StructType *SrcSTy,
1175 uint64_t DstSize, CodeGenFunction &CGF) {
1176 // We can't dive into a zero-element struct.
1177 if (SrcSTy->getNumElements() == 0) return SrcPtr;
1178
1179 llvm::Type *FirstElt = SrcSTy->getElementType(0);
1180
1181 // If the first elt is at least as large as what we're looking for, or if the
1182 // first element is the same size as the whole struct, we can enter it. The
1183 // comparison must be made on the store size and not the alloca size. Using
1184 // the alloca size may overstate the size of the load.
1185 uint64_t FirstEltSize =
1186 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
1187 if (FirstEltSize < DstSize &&
1188 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
1189 return SrcPtr;
1190
1191 // GEP into the first element.
1192 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, "coerce.dive");
1193
1194 // If the first element is a struct, recurse.
1195 llvm::Type *SrcTy = SrcPtr.getElementType();
1196 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
1197 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
1198
1199 return SrcPtr;
1200}
1201
1202/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1203/// are either integers or pointers. This does a truncation of the value if it
1204/// is too large or a zero extension if it is too small.
1205///
1206/// This behaves as if the value were coerced through memory, so on big-endian
1207/// targets the high bits are preserved in a truncation, while little-endian
1208/// targets preserve the low bits.
1209static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
1210 llvm::Type *Ty,
1211 CodeGenFunction &CGF) {
1212 if (Val->getType() == Ty)
1213 return Val;
1214
1215 if (isa<llvm::PointerType>(Val->getType())) {
1216 // If this is Pointer->Pointer avoid conversion to and from int.
1217 if (isa<llvm::PointerType>(Ty))
1218 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
1219
1220 // Convert the pointer to an integer so we can play with its width.
1221 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
1222 }
1223
1224 llvm::Type *DestIntTy = Ty;
1225 if (isa<llvm::PointerType>(DestIntTy))
1226 DestIntTy = CGF.IntPtrTy;
1227
1228 if (Val->getType() != DestIntTy) {
1229 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
1230 if (DL.isBigEndian()) {
1231 // Preserve the high bits on big-endian targets.
1232 // That is what memory coercion does.
1233 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1234 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1235
1236 if (SrcSize > DstSize) {
1237 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
1238 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
1239 } else {
1240 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
1241 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
1242 }
1243 } else {
1244 // Little-endian targets preserve the low bits. No shifts required.
1245 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
1246 }
1247 }
1248
1249 if (isa<llvm::PointerType>(Ty))
1250 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
1251 return Val;
1252}
1253
1254
1255
1256/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
1257/// a pointer to an object of type \arg Ty, known to be aligned to
1258/// \arg SrcAlign bytes.
1259///
1260/// This safely handles the case when the src type is smaller than the
1261/// destination type; in this situation the values of bits which not
1262/// present in the src are undefined.
1263static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
1264 CodeGenFunction &CGF) {
1265 llvm::Type *SrcTy = Src.getElementType();
1266
1267 // If SrcTy and Ty are the same, just do a load.
1268 if (SrcTy == Ty)
1269 return CGF.Builder.CreateLoad(Src);
1270
1271 llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
1272
1273 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
1274 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy,
1275 DstSize.getFixedValue(), CGF);
1276 SrcTy = Src.getElementType();
1277 }
1278
1279 llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
1280
1281 // If the source and destination are integer or pointer types, just do an
1282 // extension or truncation to the desired type.
1283 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
1284 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
1285 llvm::Value *Load = CGF.Builder.CreateLoad(Src);
1286 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
1287 }
1288
1289 // If load is legal, just bitcast the src pointer.
1290 if (!SrcSize.isScalable() && !DstSize.isScalable() &&
1291 SrcSize.getFixedValue() >= DstSize.getFixedValue()) {
1292 // Generally SrcSize is never greater than DstSize, since this means we are
1293 // losing bits. However, this can happen in cases where the structure has
1294 // additional padding, for example due to a user specified alignment.
1295 //
1296 // FIXME: Assert that we aren't truncating non-padding bits when have access
1297 // to that information.
1298 Src = Src.withElementType(Ty);
1299 return CGF.Builder.CreateLoad(Src);
1300 }
1301
1302 // If coercing a fixed vector to a scalable vector for ABI compatibility, and
1303 // the types match, use the llvm.vector.insert intrinsic to perform the
1304 // conversion.
1305 if (auto *ScalableDstTy = dyn_cast<llvm::ScalableVectorType>(Ty)) {
1306 if (auto *FixedSrcTy = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
1307 // If we are casting a fixed i8 vector to a scalable i1 predicate
1308 // vector, use a vector insert and bitcast the result.
1309 if (ScalableDstTy->getElementType()->isIntegerTy(1) &&
1310 ScalableDstTy->getElementCount().isKnownMultipleOf(8) &&
1311 FixedSrcTy->getElementType()->isIntegerTy(8)) {
1312 ScalableDstTy = llvm::ScalableVectorType::get(
1313 FixedSrcTy->getElementType(),
1314 ScalableDstTy->getElementCount().getKnownMinValue() / 8);
1315 }
1316 if (ScalableDstTy->getElementType() == FixedSrcTy->getElementType()) {
1317 auto *Load = CGF.Builder.CreateLoad(Src);
1318 auto *UndefVec = llvm::UndefValue::get(ScalableDstTy);
1319 auto *Zero = llvm::Constant::getNullValue(CGF.CGM.Int64Ty);
1320 llvm::Value *Result = CGF.Builder.CreateInsertVector(
1321 ScalableDstTy, UndefVec, Load, Zero, "cast.scalable");
1322 if (ScalableDstTy != Ty)
1323 Result = CGF.Builder.CreateBitCast(Result, Ty);
1324 return Result;
1325 }
1326 }
1327 }
1328
1329 // Otherwise do coercion through memory. This is stupid, but simple.
1330 RawAddress Tmp =
1331 CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment(), Src.getName());
1333 Tmp.getPointer(), Tmp.getAlignment().getAsAlign(),
1334 Src.emitRawPointer(CGF), Src.getAlignment().getAsAlign(),
1335 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize.getKnownMinValue()));
1336 return CGF.Builder.CreateLoad(Tmp);
1337}
1338
1339// Function to store a first-class aggregate into memory. We prefer to
1340// store the elements rather than the aggregate to be more friendly to
1341// fast-isel.
1342// FIXME: Do we need to recurse here?
1343void CodeGenFunction::EmitAggregateStore(llvm::Value *Val, Address Dest,
1344 bool DestIsVolatile) {
1345 // Prefer scalar stores to first-class aggregate stores.
1346 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(Val->getType())) {
1347 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1348 Address EltPtr = Builder.CreateStructGEP(Dest, i);
1349 llvm::Value *Elt = Builder.CreateExtractValue(Val, i);
1350 Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
1351 }
1352 } else {
1353 Builder.CreateStore(Val, Dest, DestIsVolatile);
1354 }
1355}
1356
1357/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
1358/// where the source and destination may have different types. The
1359/// destination is known to be aligned to \arg DstAlign bytes.
1360///
1361/// This safely handles the case when the src type is larger than the
1362/// destination type; the upper bits of the src will be lost.
1363static void CreateCoercedStore(llvm::Value *Src,
1364 Address Dst,
1365 bool DstIsVolatile,
1366 CodeGenFunction &CGF) {
1367 llvm::Type *SrcTy = Src->getType();
1368 llvm::Type *DstTy = Dst.getElementType();
1369 if (SrcTy == DstTy) {
1370 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1371 return;
1372 }
1373
1374 llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
1375
1376 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
1377 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy,
1378 SrcSize.getFixedValue(), CGF);
1379 DstTy = Dst.getElementType();
1380 }
1381
1382 llvm::PointerType *SrcPtrTy = llvm::dyn_cast<llvm::PointerType>(SrcTy);
1383 llvm::PointerType *DstPtrTy = llvm::dyn_cast<llvm::PointerType>(DstTy);
1384 if (SrcPtrTy && DstPtrTy &&
1385 SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace()) {
1386 Src = CGF.Builder.CreateAddrSpaceCast(Src, DstTy);
1387 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1388 return;
1389 }
1390
1391 // If the source and destination are integer or pointer types, just do an
1392 // extension or truncation to the desired type.
1393 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1394 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1395 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
1396 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1397 return;
1398 }
1399
1400 llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
1401
1402 // If store is legal, just bitcast the src pointer.
1403 if (isa<llvm::ScalableVectorType>(SrcTy) ||
1404 isa<llvm::ScalableVectorType>(DstTy) ||
1405 SrcSize.getFixedValue() <= DstSize.getFixedValue()) {
1406 Dst = Dst.withElementType(SrcTy);
1407 CGF.EmitAggregateStore(Src, Dst, DstIsVolatile);
1408 } else {
1409 // Otherwise do coercion through memory. This is stupid, but
1410 // simple.
1411
1412 // Generally SrcSize is never greater than DstSize, since this means we are
1413 // losing bits. However, this can happen in cases where the structure has
1414 // additional padding, for example due to a user specified alignment.
1415 //
1416 // FIXME: Assert that we aren't truncating non-padding bits when have access
1417 // to that information.
1418 RawAddress Tmp =
1419 CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1420 CGF.Builder.CreateStore(Src, Tmp);
1422 Dst.emitRawPointer(CGF), Dst.getAlignment().getAsAlign(),
1423 Tmp.getPointer(), Tmp.getAlignment().getAsAlign(),
1424 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize.getFixedValue()));
1425 }
1426}
1427
1429 const ABIArgInfo &info) {
1430 if (unsigned offset = info.getDirectOffset()) {
1431 addr = addr.withElementType(CGF.Int8Ty);
1432 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1433 CharUnits::fromQuantity(offset));
1434 addr = addr.withElementType(info.getCoerceToType());
1435 }
1436 return addr;
1437}
1438
1439namespace {
1440
1441/// Encapsulates information about the way function arguments from
1442/// CGFunctionInfo should be passed to actual LLVM IR function.
1443class ClangToLLVMArgMapping {
1444 static const unsigned InvalidIndex = ~0U;
1445 unsigned InallocaArgNo;
1446 unsigned SRetArgNo;
1447 unsigned TotalIRArgs;
1448
1449 /// Arguments of LLVM IR function corresponding to single Clang argument.
1450 struct IRArgs {
1451 unsigned PaddingArgIndex;
1452 // Argument is expanded to IR arguments at positions
1453 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1454 unsigned FirstArgIndex;
1455 unsigned NumberOfArgs;
1456
1457 IRArgs()
1458 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1459 NumberOfArgs(0) {}
1460 };
1461
1462 SmallVector<IRArgs, 8> ArgInfo;
1463
1464public:
1465 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1466 bool OnlyRequiredArgs = false)
1467 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1468 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1469 construct(Context, FI, OnlyRequiredArgs);
1470 }
1471
1472 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1473 unsigned getInallocaArgNo() const {
1474 assert(hasInallocaArg());
1475 return InallocaArgNo;
1476 }
1477
1478 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1479 unsigned getSRetArgNo() const {
1480 assert(hasSRetArg());
1481 return SRetArgNo;
1482 }
1483
1484 unsigned totalIRArgs() const { return TotalIRArgs; }
1485
1486 bool hasPaddingArg(unsigned ArgNo) const {
1487 assert(ArgNo < ArgInfo.size());
1488 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1489 }
1490 unsigned getPaddingArgNo(unsigned ArgNo) const {
1491 assert(hasPaddingArg(ArgNo));
1492 return ArgInfo[ArgNo].PaddingArgIndex;
1493 }
1494
1495 /// Returns index of first IR argument corresponding to ArgNo, and their
1496 /// quantity.
1497 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1498 assert(ArgNo < ArgInfo.size());
1499 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1500 ArgInfo[ArgNo].NumberOfArgs);
1501 }
1502
1503private:
1504 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1505 bool OnlyRequiredArgs);
1506};
1507
1508void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1509 const CGFunctionInfo &FI,
1510 bool OnlyRequiredArgs) {
1511 unsigned IRArgNo = 0;
1512 bool SwapThisWithSRet = false;
1513 const ABIArgInfo &RetAI = FI.getReturnInfo();
1514
1515 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1516 SwapThisWithSRet = RetAI.isSRetAfterThis();
1517 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1518 }
1519
1520 unsigned ArgNo = 0;
1521 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1522 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1523 ++I, ++ArgNo) {
1524 assert(I != FI.arg_end());
1525 QualType ArgType = I->type;
1526 const ABIArgInfo &AI = I->info;
1527 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1528 auto &IRArgs = ArgInfo[ArgNo];
1529
1530 if (AI.getPaddingType())
1531 IRArgs.PaddingArgIndex = IRArgNo++;
1532
1533 switch (AI.getKind()) {
1534 case ABIArgInfo::Extend:
1535 case ABIArgInfo::Direct: {
1536 // FIXME: handle sseregparm someday...
1537 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1538 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1539 IRArgs.NumberOfArgs = STy->getNumElements();
1540 } else {
1541 IRArgs.NumberOfArgs = 1;
1542 }
1543 break;
1544 }
1547 IRArgs.NumberOfArgs = 1;
1548 break;
1549 case ABIArgInfo::Ignore:
1551 // ignore and inalloca doesn't have matching LLVM parameters.
1552 IRArgs.NumberOfArgs = 0;
1553 break;
1555 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1556 break;
1557 case ABIArgInfo::Expand:
1558 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1559 break;
1560 }
1561
1562 if (IRArgs.NumberOfArgs > 0) {
1563 IRArgs.FirstArgIndex = IRArgNo;
1564 IRArgNo += IRArgs.NumberOfArgs;
1565 }
1566
1567 // Skip over the sret parameter when it comes second. We already handled it
1568 // above.
1569 if (IRArgNo == 1 && SwapThisWithSRet)
1570 IRArgNo++;
1571 }
1572 assert(ArgNo == ArgInfo.size());
1573
1574 if (FI.usesInAlloca())
1575 InallocaArgNo = IRArgNo++;
1576
1577 TotalIRArgs = IRArgNo;
1578}
1579} // namespace
1580
1581/***/
1582
1584 const auto &RI = FI.getReturnInfo();
1585 return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet());
1586}
1587
1589 const auto &RI = FI.getReturnInfo();
1590 return RI.getInReg();
1591}
1592
1594 return ReturnTypeUsesSRet(FI) &&
1596}
1597
1599 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1600 switch (BT->getKind()) {
1601 default:
1602 return false;
1603 case BuiltinType::Float:
1605 case BuiltinType::Double:
1607 case BuiltinType::LongDouble:
1609 }
1610 }
1611
1612 return false;
1613}
1614
1616 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1617 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1618 if (BT->getKind() == BuiltinType::LongDouble)
1620 }
1621 }
1622
1623 return false;
1624}
1625
1628 return GetFunctionType(FI);
1629}
1630
1631llvm::FunctionType *
1633
1634 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1635 (void)Inserted;
1636 assert(Inserted && "Recursively being processed?");
1637
1638 llvm::Type *resultType = nullptr;
1639 const ABIArgInfo &retAI = FI.getReturnInfo();
1640 switch (retAI.getKind()) {
1641 case ABIArgInfo::Expand:
1643 llvm_unreachable("Invalid ABI kind for return argument");
1644
1645 case ABIArgInfo::Extend:
1646 case ABIArgInfo::Direct:
1647 resultType = retAI.getCoerceToType();
1648 break;
1649
1651 if (retAI.getInAllocaSRet()) {
1652 // sret things on win32 aren't void, they return the sret pointer.
1653 QualType ret = FI.getReturnType();
1654 unsigned addressSpace = CGM.getTypes().getTargetAddressSpace(ret);
1655 resultType = llvm::PointerType::get(getLLVMContext(), addressSpace);
1656 } else {
1657 resultType = llvm::Type::getVoidTy(getLLVMContext());
1658 }
1659 break;
1660
1662 case ABIArgInfo::Ignore:
1663 resultType = llvm::Type::getVoidTy(getLLVMContext());
1664 break;
1665
1667 resultType = retAI.getUnpaddedCoerceAndExpandType();
1668 break;
1669 }
1670
1671 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1672 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1673
1674 // Add type for sret argument.
1675 if (IRFunctionArgs.hasSRetArg()) {
1676 QualType Ret = FI.getReturnType();
1677 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(Ret);
1678 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1679 llvm::PointerType::get(getLLVMContext(), AddressSpace);
1680 }
1681
1682 // Add type for inalloca argument.
1683 if (IRFunctionArgs.hasInallocaArg())
1684 ArgTypes[IRFunctionArgs.getInallocaArgNo()] =
1685 llvm::PointerType::getUnqual(getLLVMContext());
1686
1687 // Add in all of the required arguments.
1688 unsigned ArgNo = 0;
1690 ie = it + FI.getNumRequiredArgs();
1691 for (; it != ie; ++it, ++ArgNo) {
1692 const ABIArgInfo &ArgInfo = it->info;
1693
1694 // Insert a padding type to ensure proper alignment.
1695 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1696 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1697 ArgInfo.getPaddingType();
1698
1699 unsigned FirstIRArg, NumIRArgs;
1700 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1701
1702 switch (ArgInfo.getKind()) {
1703 case ABIArgInfo::Ignore:
1705 assert(NumIRArgs == 0);
1706 break;
1707
1709 assert(NumIRArgs == 1);
1710 // indirect arguments are always on the stack, which is alloca addr space.
1711 ArgTypes[FirstIRArg] = llvm::PointerType::get(
1712 getLLVMContext(), CGM.getDataLayout().getAllocaAddrSpace());
1713 break;
1715 assert(NumIRArgs == 1);
1716 ArgTypes[FirstIRArg] = llvm::PointerType::get(
1718 break;
1719 case ABIArgInfo::Extend:
1720 case ABIArgInfo::Direct: {
1721 // Fast-isel and the optimizer generally like scalar values better than
1722 // FCAs, so we flatten them if this is safe to do for this argument.
1723 llvm::Type *argType = ArgInfo.getCoerceToType();
1724 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
1725 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1726 assert(NumIRArgs == st->getNumElements());
1727 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
1728 ArgTypes[FirstIRArg + i] = st->getElementType(i);
1729 } else {
1730 assert(NumIRArgs == 1);
1731 ArgTypes[FirstIRArg] = argType;
1732 }
1733 break;
1734 }
1735
1737 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1738 for (auto *EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1739 *ArgTypesIter++ = EltTy;
1740 }
1741 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1742 break;
1743 }
1744
1745 case ABIArgInfo::Expand:
1746 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1747 getExpandedTypes(it->type, ArgTypesIter);
1748 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1749 break;
1750 }
1751 }
1752
1753 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1754 assert(Erased && "Not in set?");
1755
1756 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
1757}
1758
1760 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1761 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1762
1763 if (!isFuncTypeConvertible(FPT))
1764 return llvm::StructType::get(getLLVMContext());
1765
1766 return GetFunctionType(GD);
1767}
1768
1770 llvm::AttrBuilder &FuncAttrs,
1771 const FunctionProtoType *FPT) {
1772 if (!FPT)
1773 return;
1774
1776 FPT->isNothrow())
1777 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1778
1779 unsigned SMEBits = FPT->getAArch64SMEAttributes();
1781 FuncAttrs.addAttribute("aarch64_pstate_sm_enabled");
1783 FuncAttrs.addAttribute("aarch64_pstate_sm_compatible");
1784
1785 // ZA
1787 FuncAttrs.addAttribute("aarch64_preserves_za");
1789 FuncAttrs.addAttribute("aarch64_in_za");
1791 FuncAttrs.addAttribute("aarch64_out_za");
1793 FuncAttrs.addAttribute("aarch64_inout_za");
1794
1795 // ZT0
1797 FuncAttrs.addAttribute("aarch64_preserves_zt0");
1799 FuncAttrs.addAttribute("aarch64_in_zt0");
1801 FuncAttrs.addAttribute("aarch64_out_zt0");
1803 FuncAttrs.addAttribute("aarch64_inout_zt0");
1804}
1805
1806static void AddAttributesFromOMPAssumes(llvm::AttrBuilder &FuncAttrs,
1807 const Decl *Callee) {
1808 if (!Callee)
1809 return;
1810
1812
1813 for (const OMPAssumeAttr *AA : Callee->specific_attrs<OMPAssumeAttr>())
1814 AA->getAssumption().split(Attrs, ",");
1815
1816 if (!Attrs.empty())
1817 FuncAttrs.addAttribute(llvm::AssumptionAttrKey,
1818 llvm::join(Attrs.begin(), Attrs.end(), ","));
1819}
1820
1822 QualType ReturnType) const {
1823 // We can't just discard the return value for a record type with a
1824 // complex destructor or a non-trivially copyable type.
1825 if (const RecordType *RT =
1826 ReturnType.getCanonicalType()->getAs<RecordType>()) {
1827 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1828 return ClassDecl->hasTrivialDestructor();
1829 }
1830 return ReturnType.isTriviallyCopyableType(Context);
1831}
1832
1834 const Decl *TargetDecl) {
1835 // As-is msan can not tolerate noundef mismatch between caller and
1836 // implementation. Mismatch is possible for e.g. indirect calls from C-caller
1837 // into C++. Such mismatches lead to confusing false reports. To avoid
1838 // expensive workaround on msan we enforce initialization event in uncommon
1839 // cases where it's allowed.
1840 if (Module.getLangOpts().Sanitize.has(SanitizerKind::Memory))
1841 return true;
1842 // C++ explicitly makes returning undefined values UB. C's rule only applies
1843 // to used values, so we never mark them noundef for now.
1844 if (!Module.getLangOpts().CPlusPlus)
1845 return false;
1846 if (TargetDecl) {
1847 if (const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(TargetDecl)) {
1848 if (FDecl->isExternC())
1849 return false;
1850 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(TargetDecl)) {
1851 // Function pointer.
1852 if (VDecl->isExternC())
1853 return false;
1854 }
1855 }
1856
1857 // We don't want to be too aggressive with the return checking, unless
1858 // it's explicit in the code opts or we're using an appropriate sanitizer.
1859 // Try to respect what the programmer intended.
1860 return Module.getCodeGenOpts().StrictReturn ||
1861 !Module.MayDropFunctionReturn(Module.getContext(), RetTy) ||
1862 Module.getLangOpts().Sanitize.has(SanitizerKind::Return);
1863}
1864
1865/// Add denormal-fp-math and denormal-fp-math-f32 as appropriate for the
1866/// requested denormal behavior, accounting for the overriding behavior of the
1867/// -f32 case.
1868static void addDenormalModeAttrs(llvm::DenormalMode FPDenormalMode,
1869 llvm::DenormalMode FP32DenormalMode,
1870 llvm::AttrBuilder &FuncAttrs) {
1871 if (FPDenormalMode != llvm::DenormalMode::getDefault())
1872 FuncAttrs.addAttribute("denormal-fp-math", FPDenormalMode.str());
1873
1874 if (FP32DenormalMode != FPDenormalMode && FP32DenormalMode.isValid())
1875 FuncAttrs.addAttribute("denormal-fp-math-f32", FP32DenormalMode.str());
1876}
1877
1878/// Add default attributes to a function, which have merge semantics under
1879/// -mlink-builtin-bitcode and should not simply overwrite any existing
1880/// attributes in the linked library.
1881static void
1883 llvm::AttrBuilder &FuncAttrs) {
1884 addDenormalModeAttrs(CodeGenOpts.FPDenormalMode, CodeGenOpts.FP32DenormalMode,
1885 FuncAttrs);
1886}
1887
1889 StringRef Name, bool HasOptnone, const CodeGenOptions &CodeGenOpts,
1890 const LangOptions &LangOpts, bool AttrOnCallSite,
1891 llvm::AttrBuilder &FuncAttrs) {
1892 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1893 if (!HasOptnone) {
1894 if (CodeGenOpts.OptimizeSize)
1895 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1896 if (CodeGenOpts.OptimizeSize == 2)
1897 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1898 }
1899
1900 if (CodeGenOpts.DisableRedZone)
1901 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
1902 if (CodeGenOpts.IndirectTlsSegRefs)
1903 FuncAttrs.addAttribute("indirect-tls-seg-refs");
1904 if (CodeGenOpts.NoImplicitFloat)
1905 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
1906
1907 if (AttrOnCallSite) {
1908 // Attributes that should go on the call site only.
1909 // FIXME: Look for 'BuiltinAttr' on the function rather than re-checking
1910 // the -fno-builtin-foo list.
1911 if (!CodeGenOpts.SimplifyLibCalls || LangOpts.isNoBuiltinFunc(Name))
1912 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
1913 if (!CodeGenOpts.TrapFuncName.empty())
1914 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
1915 } else {
1916 switch (CodeGenOpts.getFramePointer()) {
1918 // This is the default behavior.
1919 break;
1923 FuncAttrs.addAttribute("frame-pointer",
1925 CodeGenOpts.getFramePointer()));
1926 }
1927
1928 if (CodeGenOpts.LessPreciseFPMAD)
1929 FuncAttrs.addAttribute("less-precise-fpmad", "true");
1930
1931 if (CodeGenOpts.NullPointerIsValid)
1932 FuncAttrs.addAttribute(llvm::Attribute::NullPointerIsValid);
1933
1935 FuncAttrs.addAttribute("no-trapping-math", "true");
1936
1937 // TODO: Are these all needed?
1938 // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
1939 if (LangOpts.NoHonorInfs)
1940 FuncAttrs.addAttribute("no-infs-fp-math", "true");
1941 if (LangOpts.NoHonorNaNs)
1942 FuncAttrs.addAttribute("no-nans-fp-math", "true");
1943 if (LangOpts.ApproxFunc)
1944 FuncAttrs.addAttribute("approx-func-fp-math", "true");
1945 if (LangOpts.AllowFPReassoc && LangOpts.AllowRecip &&
1946 LangOpts.NoSignedZero && LangOpts.ApproxFunc &&
1947 (LangOpts.getDefaultFPContractMode() ==
1949 LangOpts.getDefaultFPContractMode() ==
1951 FuncAttrs.addAttribute("unsafe-fp-math", "true");
1952 if (CodeGenOpts.SoftFloat)
1953 FuncAttrs.addAttribute("use-soft-float", "true");
1954 FuncAttrs.addAttribute("stack-protector-buffer-size",
1955 llvm::utostr(CodeGenOpts.SSPBufferSize));
1956 if (LangOpts.NoSignedZero)
1957 FuncAttrs.addAttribute("no-signed-zeros-fp-math", "true");
1958
1959 // TODO: Reciprocal estimate codegen options should apply to instructions?
1960 const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals;
1961 if (!Recips.empty())
1962 FuncAttrs.addAttribute("reciprocal-estimates",
1963 llvm::join(Recips, ","));
1964
1965 if (!CodeGenOpts.PreferVectorWidth.empty() &&
1966 CodeGenOpts.PreferVectorWidth != "none")
1967 FuncAttrs.addAttribute("prefer-vector-width",
1968 CodeGenOpts.PreferVectorWidth);
1969
1970 if (CodeGenOpts.StackRealignment)
1971 FuncAttrs.addAttribute("stackrealign");
1972 if (CodeGenOpts.Backchain)
1973 FuncAttrs.addAttribute("backchain");
1974 if (CodeGenOpts.EnableSegmentedStacks)
1975 FuncAttrs.addAttribute("split-stack");
1976
1977 if (CodeGenOpts.SpeculativeLoadHardening)
1978 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
1979
1980 // Add zero-call-used-regs attribute.
1981 switch (CodeGenOpts.getZeroCallUsedRegs()) {
1982 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Skip:
1983 FuncAttrs.removeAttribute("zero-call-used-regs");
1984 break;
1985 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPRArg:
1986 FuncAttrs.addAttribute("zero-call-used-regs", "used-gpr-arg");
1987 break;
1988 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPR:
1989 FuncAttrs.addAttribute("zero-call-used-regs", "used-gpr");
1990 break;
1991 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedArg:
1992 FuncAttrs.addAttribute("zero-call-used-regs", "used-arg");
1993 break;
1994 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Used:
1995 FuncAttrs.addAttribute("zero-call-used-regs", "used");
1996 break;
1997 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPRArg:
1998 FuncAttrs.addAttribute("zero-call-used-regs", "all-gpr-arg");
1999 break;
2000 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPR:
2001 FuncAttrs.addAttribute("zero-call-used-regs", "all-gpr");
2002 break;
2003 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllArg:
2004 FuncAttrs.addAttribute("zero-call-used-regs", "all-arg");
2005 break;
2006 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::All:
2007 FuncAttrs.addAttribute("zero-call-used-regs", "all");
2008 break;
2009 }
2010 }
2011
2012 if (LangOpts.assumeFunctionsAreConvergent()) {
2013 // Conservatively, mark all functions and calls in CUDA and OpenCL as
2014 // convergent (meaning, they may call an intrinsically convergent op, such
2015 // as __syncthreads() / barrier(), and so can't have certain optimizations
2016 // applied around them). LLVM will remove this attribute where it safely
2017 // can.
2018 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
2019 }
2020
2021 // TODO: NoUnwind attribute should be added for other GPU modes HIP,
2022 // OpenMP offload. AFAIK, neither of them support exceptions in device code.
2023 if ((LangOpts.CUDA && LangOpts.CUDAIsDevice) || LangOpts.OpenCL ||
2024 LangOpts.SYCLIsDevice) {
2025 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2026 }
2027
2028 if (CodeGenOpts.SaveRegParams && !AttrOnCallSite)
2029 FuncAttrs.addAttribute("save-reg-params");
2030
2031 for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) {
2032 StringRef Var, Value;
2033 std::tie(Var, Value) = Attr.split('=');
2034 FuncAttrs.addAttribute(Var, Value);
2035 }
2036
2039}
2040
2041/// Merges `target-features` from \TargetOpts and \F, and sets the result in
2042/// \FuncAttr
2043/// * features from \F are always kept
2044/// * a feature from \TargetOpts is kept if itself and its opposite are absent
2045/// from \F
2046static void
2048 const llvm::Function &F,
2049 const TargetOptions &TargetOpts) {
2050 auto FFeatures = F.getFnAttribute("target-features");
2051
2052 llvm::StringSet<> MergedNames;
2053 SmallVector<StringRef> MergedFeatures;
2054 MergedFeatures.reserve(TargetOpts.Features.size());
2055
2056 auto AddUnmergedFeatures = [&](auto &&FeatureRange) {
2057 for (StringRef Feature : FeatureRange) {
2058 if (Feature.empty())
2059 continue;
2060 assert(Feature[0] == '+' || Feature[0] == '-');
2061 StringRef Name = Feature.drop_front(1);
2062 bool Merged = !MergedNames.insert(Name).second;
2063 if (!Merged)
2064 MergedFeatures.push_back(Feature);
2065 }
2066 };
2067
2068 if (FFeatures.isValid())
2069 AddUnmergedFeatures(llvm::split(FFeatures.getValueAsString(), ','));
2070 AddUnmergedFeatures(TargetOpts.Features);
2071
2072 if (!MergedFeatures.empty()) {
2073 llvm::sort(MergedFeatures);
2074 FuncAttr.addAttribute("target-features", llvm::join(MergedFeatures, ","));
2075 }
2076}
2077
2079 llvm::Function &F, const CodeGenOptions &CodeGenOpts,
2080 const LangOptions &LangOpts, const TargetOptions &TargetOpts,
2081 bool WillInternalize) {
2082
2083 llvm::AttrBuilder FuncAttrs(F.getContext());
2084 // Here we only extract the options that are relevant compared to the version
2085 // from GetCPUAndFeaturesAttributes.
2086 if (!TargetOpts.CPU.empty())
2087 FuncAttrs.addAttribute("target-cpu", TargetOpts.CPU);
2088 if (!TargetOpts.TuneCPU.empty())
2089 FuncAttrs.addAttribute("tune-cpu", TargetOpts.TuneCPU);
2090
2091 ::getTrivialDefaultFunctionAttributes(F.getName(), F.hasOptNone(),
2092 CodeGenOpts, LangOpts,
2093 /*AttrOnCallSite=*/false, FuncAttrs);
2094
2095 if (!WillInternalize && F.isInterposable()) {
2096 // Do not promote "dynamic" denormal-fp-math to this translation unit's
2097 // setting for weak functions that won't be internalized. The user has no
2098 // real control for how builtin bitcode is linked, so we shouldn't assume
2099 // later copies will use a consistent mode.
2100 F.addFnAttrs(FuncAttrs);
2101 return;
2102 }
2103
2104 llvm::AttributeMask AttrsToRemove;
2105
2106 llvm::DenormalMode DenormModeToMerge = F.getDenormalModeRaw();
2107 llvm::DenormalMode DenormModeToMergeF32 = F.getDenormalModeF32Raw();
2108 llvm::DenormalMode Merged =
2109 CodeGenOpts.FPDenormalMode.mergeCalleeMode(DenormModeToMerge);
2110 llvm::DenormalMode MergedF32 = CodeGenOpts.FP32DenormalMode;
2111
2112 if (DenormModeToMergeF32.isValid()) {
2113 MergedF32 =
2114 CodeGenOpts.FP32DenormalMode.mergeCalleeMode(DenormModeToMergeF32);
2115 }
2116
2117 if (Merged == llvm::DenormalMode::getDefault()) {
2118 AttrsToRemove.addAttribute("denormal-fp-math");
2119 } else if (Merged != DenormModeToMerge) {
2120 // Overwrite existing attribute
2121 FuncAttrs.addAttribute("denormal-fp-math",
2122 CodeGenOpts.FPDenormalMode.str());
2123 }
2124
2125 if (MergedF32 == llvm::DenormalMode::getDefault()) {
2126 AttrsToRemove.addAttribute("denormal-fp-math-f32");
2127 } else if (MergedF32 != DenormModeToMergeF32) {
2128 // Overwrite existing attribute
2129 FuncAttrs.addAttribute("denormal-fp-math-f32",
2130 CodeGenOpts.FP32DenormalMode.str());
2131 }
2132
2133 F.removeFnAttrs(AttrsToRemove);
2134 addDenormalModeAttrs(Merged, MergedF32, FuncAttrs);
2135
2136 overrideFunctionFeaturesWithTargetFeatures(FuncAttrs, F, TargetOpts);
2137
2138 F.addFnAttrs(FuncAttrs);
2139}
2140
2141void CodeGenModule::getTrivialDefaultFunctionAttributes(
2142 StringRef Name, bool HasOptnone, bool AttrOnCallSite,
2143 llvm::AttrBuilder &FuncAttrs) {
2144 ::getTrivialDefaultFunctionAttributes(Name, HasOptnone, getCodeGenOpts(),
2145 getLangOpts(), AttrOnCallSite,
2146 FuncAttrs);
2147}
2148
2149void CodeGenModule::getDefaultFunctionAttributes(StringRef Name,
2150 bool HasOptnone,
2151 bool AttrOnCallSite,
2152 llvm::AttrBuilder &FuncAttrs) {
2153 getTrivialDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite,
2154 FuncAttrs);
2155 // If we're just getting the default, get the default values for mergeable
2156 // attributes.
2157 if (!AttrOnCallSite)
2158 addMergableDefaultFunctionAttributes(CodeGenOpts, FuncAttrs);
2159}
2160
2162 llvm::AttrBuilder &attrs) {
2163 getDefaultFunctionAttributes(/*function name*/ "", /*optnone*/ false,
2164 /*for call*/ false, attrs);
2165 GetCPUAndFeaturesAttributes(GlobalDecl(), attrs);
2166}
2167
2168static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs,
2169 const LangOptions &LangOpts,
2170 const NoBuiltinAttr *NBA = nullptr) {
2171 auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) {
2172 SmallString<32> AttributeName;
2173 AttributeName += "no-builtin-";
2174 AttributeName += BuiltinName;
2175 FuncAttrs.addAttribute(AttributeName);
2176 };
2177
2178 // First, handle the language options passed through -fno-builtin.
2179 if (LangOpts.NoBuiltin) {
2180 // -fno-builtin disables them all.
2181 FuncAttrs.addAttribute("no-builtins");
2182 return;
2183 }
2184
2185 // Then, add attributes for builtins specified through -fno-builtin-<name>.
2186 llvm::for_each(LangOpts.NoBuiltinFuncs, AddNoBuiltinAttr);
2187
2188 // Now, let's check the __attribute__((no_builtin("...")) attribute added to
2189 // the source.
2190 if (!NBA)
2191 return;
2192
2193 // If there is a wildcard in the builtin names specified through the
2194 // attribute, disable them all.
2195 if (llvm::is_contained(NBA->builtinNames(), "*")) {
2196 FuncAttrs.addAttribute("no-builtins");
2197 return;
2198 }
2199
2200 // And last, add the rest of the builtin names.
2201 llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr);
2202}
2203
2205 const llvm::DataLayout &DL, const ABIArgInfo &AI,
2206 bool CheckCoerce = true) {
2207 llvm::Type *Ty = Types.ConvertTypeForMem(QTy);
2208 if (AI.getKind() == ABIArgInfo::Indirect ||
2210 return true;
2211 if (AI.getKind() == ABIArgInfo::Extend)
2212 return true;
2213 if (!DL.typeSizeEqualsStoreSize(Ty))
2214 // TODO: This will result in a modest amount of values not marked noundef
2215 // when they could be. We care about values that *invisibly* contain undef
2216 // bits from the perspective of LLVM IR.
2217 return false;
2218 if (CheckCoerce && AI.canHaveCoerceToType()) {
2219 llvm::Type *CoerceTy = AI.getCoerceToType();
2220 if (llvm::TypeSize::isKnownGT(DL.getTypeSizeInBits(CoerceTy),
2221 DL.getTypeSizeInBits(Ty)))
2222 // If we're coercing to a type with a greater size than the canonical one,
2223 // we're introducing new undef bits.
2224 // Coercing to a type of smaller or equal size is ok, as we know that
2225 // there's no internal padding (typeSizeEqualsStoreSize).
2226 return false;
2227 }
2228 if (QTy->isBitIntType())
2229 return true;
2230 if (QTy->isReferenceType())
2231 return true;
2232 if (QTy->isNullPtrType())
2233 return false;
2234 if (QTy->isMemberPointerType())
2235 // TODO: Some member pointers are `noundef`, but it depends on the ABI. For
2236 // now, never mark them.
2237 return false;
2238 if (QTy->isScalarType()) {
2239 if (const ComplexType *Complex = dyn_cast<ComplexType>(QTy))
2240 return DetermineNoUndef(Complex->getElementType(), Types, DL, AI, false);
2241 return true;
2242 }
2243 if (const VectorType *Vector = dyn_cast<VectorType>(QTy))
2244 return DetermineNoUndef(Vector->getElementType(), Types, DL, AI, false);
2245 if (const MatrixType *Matrix = dyn_cast<MatrixType>(QTy))
2246 return DetermineNoUndef(Matrix->getElementType(), Types, DL, AI, false);
2247 if (const ArrayType *Array = dyn_cast<ArrayType>(QTy))
2248 return DetermineNoUndef(Array->getElementType(), Types, DL, AI, false);
2249
2250 // TODO: Some structs may be `noundef`, in specific situations.
2251 return false;
2252}
2253
2254/// Check if the argument of a function has maybe_undef attribute.
2255static bool IsArgumentMaybeUndef(const Decl *TargetDecl,
2256 unsigned NumRequiredArgs, unsigned ArgNo) {
2257 const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
2258 if (!FD)
2259 return false;
2260
2261 // Assume variadic arguments do not have maybe_undef attribute.
2262 if (ArgNo >= NumRequiredArgs)
2263 return false;
2264
2265 // Check if argument has maybe_undef attribute.
2266 if (ArgNo < FD->getNumParams()) {
2267 const ParmVarDecl *Param = FD->getParamDecl(ArgNo);
2268 if (Param && Param->hasAttr<MaybeUndefAttr>())
2269 return true;
2270 }
2271
2272 return false;
2273}
2274
2275/// Test if it's legal to apply nofpclass for the given parameter type and it's
2276/// lowered IR type.
2277static bool canApplyNoFPClass(const ABIArgInfo &AI, QualType ParamType,
2278 bool IsReturn) {
2279 // Should only apply to FP types in the source, not ABI promoted.
2280 if (!ParamType->hasFloatingRepresentation())
2281 return false;
2282
2283 // The promoted-to IR type also needs to support nofpclass.
2284 llvm::Type *IRTy = AI.getCoerceToType();
2285 if (llvm::AttributeFuncs::isNoFPClassCompatibleType(IRTy))
2286 return true;
2287
2288 if (llvm::StructType *ST = dyn_cast<llvm::StructType>(IRTy)) {
2289 return !IsReturn && AI.getCanBeFlattened() &&
2290 llvm::all_of(ST->elements(), [](llvm::Type *Ty) {
2291 return llvm::AttributeFuncs::isNoFPClassCompatibleType(Ty);
2292 });
2293 }
2294
2295 return false;
2296}
2297
2298/// Return the nofpclass mask that can be applied to floating-point parameters.
2299static llvm::FPClassTest getNoFPClassTestMask(const LangOptions &LangOpts) {
2300 llvm::FPClassTest Mask = llvm::fcNone;
2301 if (LangOpts.NoHonorInfs)
2302 Mask |= llvm::fcInf;
2303 if (LangOpts.NoHonorNaNs)
2304 Mask |= llvm::fcNan;
2305 return Mask;
2306}
2307
2309 CGCalleeInfo CalleeInfo,
2310 llvm::AttributeList &Attrs) {
2311 if (Attrs.getMemoryEffects().getModRef() == llvm::ModRefInfo::NoModRef) {
2312 Attrs = Attrs.removeFnAttribute(getLLVMContext(), llvm::Attribute::Memory);
2313 llvm::Attribute MemoryAttr = llvm::Attribute::getWithMemoryEffects(
2314 getLLVMContext(), llvm::MemoryEffects::writeOnly());
2315 Attrs = Attrs.addFnAttribute(getLLVMContext(), MemoryAttr);
2316 }
2317}
2318
2319/// Construct the IR attribute list of a function or call.
2320///
2321/// When adding an attribute, please consider where it should be handled:
2322///
2323/// - getDefaultFunctionAttributes is for attributes that are essentially
2324/// part of the global target configuration (but perhaps can be
2325/// overridden on a per-function basis). Adding attributes there
2326/// will cause them to also be set in frontends that build on Clang's
2327/// target-configuration logic, as well as for code defined in library
2328/// modules such as CUDA's libdevice.
2329///
2330/// - ConstructAttributeList builds on top of getDefaultFunctionAttributes
2331/// and adds declaration-specific, convention-specific, and
2332/// frontend-specific logic. The last is of particular importance:
2333/// attributes that restrict how the frontend generates code must be
2334/// added here rather than getDefaultFunctionAttributes.
2335///
2337 const CGFunctionInfo &FI,
2338 CGCalleeInfo CalleeInfo,
2339 llvm::AttributeList &AttrList,
2340 unsigned &CallingConv,
2341 bool AttrOnCallSite, bool IsThunk) {
2342 llvm::AttrBuilder FuncAttrs(getLLVMContext());
2343 llvm::AttrBuilder RetAttrs(getLLVMContext());
2344
2345 // Collect function IR attributes from the CC lowering.
2346 // We'll collect the paramete and result attributes later.
2348 if (FI.isNoReturn())
2349 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2350 if (FI.isCmseNSCall())
2351 FuncAttrs.addAttribute("cmse_nonsecure_call");
2352
2353 // Collect function IR attributes from the callee prototype if we have one.
2355 CalleeInfo.getCalleeFunctionProtoType());
2356
2357 const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl();
2358
2359 // Attach assumption attributes to the declaration. If this is a call
2360 // site, attach assumptions from the caller to the call as well.
2361 AddAttributesFromOMPAssumes(FuncAttrs, TargetDecl);
2362
2363 bool HasOptnone = false;
2364 // The NoBuiltinAttr attached to the target FunctionDecl.
2365 const NoBuiltinAttr *NBA = nullptr;
2366
2367 // Some ABIs may result in additional accesses to arguments that may
2368 // otherwise not be present.
2369 auto AddPotentialArgAccess = [&]() {
2370 llvm::Attribute A = FuncAttrs.getAttribute(llvm::Attribute::Memory);
2371 if (A.isValid())
2372 FuncAttrs.addMemoryAttr(A.getMemoryEffects() |
2373 llvm::MemoryEffects::argMemOnly());
2374 };
2375
2376 // Collect function IR attributes based on declaration-specific
2377 // information.
2378 // FIXME: handle sseregparm someday...
2379 if (TargetDecl) {
2380 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
2381 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
2382 if (TargetDecl->hasAttr<NoThrowAttr>())
2383 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2384 if (TargetDecl->hasAttr<NoReturnAttr>())
2385 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2386 if (TargetDecl->hasAttr<ColdAttr>())
2387 FuncAttrs.addAttribute(llvm::Attribute::Cold);
2388 if (TargetDecl->hasAttr<HotAttr>())
2389 FuncAttrs.addAttribute(llvm::Attribute::Hot);
2390 if (TargetDecl->hasAttr<NoDuplicateAttr>())
2391 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
2392 if (TargetDecl->hasAttr<ConvergentAttr>())
2393 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
2394
2395 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2397 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
2398 if (AttrOnCallSite && Fn->isReplaceableGlobalAllocationFunction()) {
2399 // A sane operator new returns a non-aliasing pointer.
2400 auto Kind = Fn->getDeclName().getCXXOverloadedOperator();
2401 if (getCodeGenOpts().AssumeSaneOperatorNew &&
2402 (Kind == OO_New || Kind == OO_Array_New))
2403 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2404 }
2405 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
2406 const bool IsVirtualCall = MD && MD->isVirtual();
2407 // Don't use [[noreturn]], _Noreturn or [[no_builtin]] for a call to a
2408 // virtual function. These attributes are not inherited by overloads.
2409 if (!(AttrOnCallSite && IsVirtualCall)) {
2410 if (Fn->isNoReturn())
2411 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2412 NBA = Fn->getAttr<NoBuiltinAttr>();
2413 }
2414 }
2415
2416 if (isa<FunctionDecl>(TargetDecl) || isa<VarDecl>(TargetDecl)) {
2417 // Only place nomerge attribute on call sites, never functions. This
2418 // allows it to work on indirect virtual function calls.
2419 if (AttrOnCallSite && TargetDecl->hasAttr<NoMergeAttr>())
2420 FuncAttrs.addAttribute(llvm::Attribute::NoMerge);
2421 }
2422
2423 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
2424 if (TargetDecl->hasAttr<ConstAttr>()) {
2425 FuncAttrs.addMemoryAttr(llvm::MemoryEffects::none());
2426 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2427 // gcc specifies that 'const' functions have greater restrictions than
2428 // 'pure' functions, so they also cannot have infinite loops.
2429 FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
2430 } else if (TargetDecl->hasAttr<PureAttr>()) {
2431 FuncAttrs.addMemoryAttr(llvm::MemoryEffects::readOnly());
2432 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2433 // gcc specifies that 'pure' functions cannot have infinite loops.
2434 FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
2435 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
2436 FuncAttrs.addMemoryAttr(llvm::MemoryEffects::inaccessibleOrArgMemOnly());
2437 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2438 }
2439 if (TargetDecl->hasAttr<RestrictAttr>())
2440 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2441 if (TargetDecl->hasAttr<ReturnsNonNullAttr>() &&
2442 !CodeGenOpts.NullPointerIsValid)
2443 RetAttrs.addAttribute(llvm::Attribute::NonNull);
2444 if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
2445 FuncAttrs.addAttribute("no_caller_saved_registers");
2446 if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>())
2447 FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck);
2448 if (TargetDecl->hasAttr<LeafAttr>())
2449 FuncAttrs.addAttribute(llvm::Attribute::NoCallback);
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 }
2526
2527 // Add "sample-profile-suffix-elision-policy" attribute for internal linkage
2528 // functions with -funique-internal-linkage-names.
2529 if (TargetDecl && CodeGenOpts.UniqueInternalLinkageNames) {
2530 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
2531 if (!FD->isExternallyVisible())
2532 FuncAttrs.addAttribute("sample-profile-suffix-elision-policy",
2533 "selected");
2534 }
2535 }
2536
2537 // Collect non-call-site function IR attributes from declaration-specific
2538 // information.
2539 if (!AttrOnCallSite) {
2540 if (TargetDecl && TargetDecl->hasAttr<CmseNSEntryAttr>())
2541 FuncAttrs.addAttribute("cmse_nonsecure_entry");
2542
2543 // Whether tail calls are enabled.
2544 auto shouldDisableTailCalls = [&] {
2545 // Should this be honored in getDefaultFunctionAttributes?
2546 if (CodeGenOpts.DisableTailCalls)
2547 return true;
2548
2549 if (!TargetDecl)
2550 return false;
2551
2552 if (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
2553 TargetDecl->hasAttr<AnyX86InterruptAttr>())
2554 return true;
2555
2556 if (CodeGenOpts.NoEscapingBlockTailCalls) {
2557 if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl))
2558 if (!BD->doesNotEscape())
2559 return true;
2560 }
2561
2562 return false;
2563 };
2564 if (shouldDisableTailCalls())
2565 FuncAttrs.addAttribute("disable-tail-calls", "true");
2566
2567 // CPU/feature overrides. addDefaultFunctionDefinitionAttributes
2568 // handles these separately to set them based on the global defaults.
2569 GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs);
2570 }
2571
2572 // Collect attributes from arguments and return values.
2573 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
2574
2575 QualType RetTy = FI.getReturnType();
2576 const ABIArgInfo &RetAI = FI.getReturnInfo();
2577 const llvm::DataLayout &DL = getDataLayout();
2578
2579 // Determine if the return type could be partially undef
2580 if (CodeGenOpts.EnableNoundefAttrs &&
2581 HasStrictReturn(*this, RetTy, TargetDecl)) {
2582 if (!RetTy->isVoidType() && RetAI.getKind() != ABIArgInfo::Indirect &&
2583 DetermineNoUndef(RetTy, getTypes(), DL, RetAI))
2584 RetAttrs.addAttribute(llvm::Attribute::NoUndef);
2585 }
2586
2587 switch (RetAI.getKind()) {
2588 case ABIArgInfo::Extend:
2589 if (RetAI.isSignExt())
2590 RetAttrs.addAttribute(llvm::Attribute::SExt);
2591 else
2592 RetAttrs.addAttribute(llvm::Attribute::ZExt);
2593 [[fallthrough]];
2594 case ABIArgInfo::Direct:
2595 if (RetAI.getInReg())
2596 RetAttrs.addAttribute(llvm::Attribute::InReg);
2597
2598 if (canApplyNoFPClass(RetAI, RetTy, true))
2599 RetAttrs.addNoFPClassAttr(getNoFPClassTestMask(getLangOpts()));
2600
2601 break;
2602 case ABIArgInfo::Ignore:
2603 break;
2604
2606 case ABIArgInfo::Indirect: {
2607 // inalloca and sret disable readnone and readonly
2608 AddPotentialArgAccess();
2609 break;
2610 }
2611
2613 break;
2614
2615 case ABIArgInfo::Expand:
2617 llvm_unreachable("Invalid ABI kind for return argument");
2618 }
2619
2620 if (!IsThunk) {
2621 // FIXME: fix this properly, https://reviews.llvm.org/D100388
2622 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
2623 QualType PTy = RefTy->getPointeeType();
2624 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2625 RetAttrs.addDereferenceableAttr(
2626 getMinimumObjectSize(PTy).getQuantity());
2627 if (getTypes().getTargetAddressSpace(PTy) == 0 &&
2628 !CodeGenOpts.NullPointerIsValid)
2629 RetAttrs.addAttribute(llvm::Attribute::NonNull);
2630 if (PTy->isObjectType()) {
2631 llvm::Align Alignment =
2633 RetAttrs.addAlignmentAttr(Alignment);
2634 }
2635 }
2636 }
2637
2638 bool hasUsedSRet = false;
2639 SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs());
2640
2641 // Attach attributes to sret.
2642 if (IRFunctionArgs.hasSRetArg()) {
2643 llvm::AttrBuilder SRETAttrs(getLLVMContext());
2644 SRETAttrs.addStructRetAttr(getTypes().ConvertTypeForMem(RetTy));
2645 SRETAttrs.addAttribute(llvm::Attribute::Writable);
2646 SRETAttrs.addAttribute(llvm::Attribute::DeadOnUnwind);
2647 hasUsedSRet = true;
2648 if (RetAI.getInReg())
2649 SRETAttrs.addAttribute(llvm::Attribute::InReg);
2650 SRETAttrs.addAlignmentAttr(RetAI.getIndirectAlign().getQuantity());
2651 ArgAttrs[IRFunctionArgs.getSRetArgNo()] =
2652 llvm::AttributeSet::get(getLLVMContext(), SRETAttrs);
2653 }
2654
2655 // Attach attributes to inalloca argument.
2656 if (IRFunctionArgs.hasInallocaArg()) {
2657 llvm::AttrBuilder Attrs(getLLVMContext());
2658 Attrs.addInAllocaAttr(FI.getArgStruct());
2659 ArgAttrs[IRFunctionArgs.getInallocaArgNo()] =
2660 llvm::AttributeSet::get(getLLVMContext(), Attrs);
2661 }
2662
2663 // Apply `nonnull`, `dereferencable(N)` and `align N` to the `this` argument,
2664 // unless this is a thunk function.
2665 // FIXME: fix this properly, https://reviews.llvm.org/D100388
2666 if (FI.isInstanceMethod() && !IRFunctionArgs.hasInallocaArg() &&
2667 !FI.arg_begin()->type->isVoidPointerType() && !IsThunk) {
2668 auto IRArgs = IRFunctionArgs.getIRArgs(0);
2669
2670 assert(IRArgs.second == 1 && "Expected only a single `this` pointer.");
2671
2672 llvm::AttrBuilder Attrs(getLLVMContext());
2673
2674 QualType ThisTy =
2676
2677 if (!CodeGenOpts.NullPointerIsValid &&
2678 getTypes().getTargetAddressSpace(FI.arg_begin()->type) == 0) {
2679 Attrs.addAttribute(llvm::Attribute::NonNull);
2680 Attrs.addDereferenceableAttr(getMinimumObjectSize(ThisTy).getQuantity());
2681 } else {
2682 // FIXME dereferenceable should be correct here, regardless of
2683 // NullPointerIsValid. However, dereferenceable currently does not always
2684 // respect NullPointerIsValid and may imply nonnull and break the program.
2685 // See https://reviews.llvm.org/D66618 for discussions.
2686 Attrs.addDereferenceableOrNullAttr(
2689 .getQuantity());
2690 }
2691
2692 llvm::Align Alignment =
2693 getNaturalTypeAlignment(ThisTy, /*BaseInfo=*/nullptr,
2694 /*TBAAInfo=*/nullptr, /*forPointeeType=*/true)
2695 .getAsAlign();
2696 Attrs.addAlignmentAttr(Alignment);
2697
2698 ArgAttrs[IRArgs.first] = llvm::AttributeSet::get(getLLVMContext(), Attrs);
2699 }
2700
2701 unsigned ArgNo = 0;
2703 E = FI.arg_end();
2704 I != E; ++I, ++ArgNo) {
2705 QualType ParamType = I->type;
2706 const ABIArgInfo &AI = I->info;
2707 llvm::AttrBuilder Attrs(getLLVMContext());
2708
2709 // Add attribute for padding argument, if necessary.
2710 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
2711 if (AI.getPaddingInReg()) {
2712 ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2713 llvm::AttributeSet::get(
2715 llvm::AttrBuilder(getLLVMContext()).addAttribute(llvm::Attribute::InReg));
2716 }
2717 }
2718
2719 // Decide whether the argument we're handling could be partially undef
2720 if (CodeGenOpts.EnableNoundefAttrs &&
2721 DetermineNoUndef(ParamType, getTypes(), DL, AI)) {
2722 Attrs.addAttribute(llvm::Attribute::NoUndef);
2723 }
2724
2725 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
2726 // have the corresponding parameter variable. It doesn't make
2727 // sense to do it here because parameters are so messed up.
2728 switch (AI.getKind()) {
2729 case ABIArgInfo::Extend:
2730 if (AI.isSignExt())
2731 Attrs.addAttribute(llvm::Attribute::SExt);
2732 else
2733 Attrs.addAttribute(llvm::Attribute::ZExt);
2734 [[fallthrough]];
2735 case ABIArgInfo::Direct:
2736 if (ArgNo == 0 && FI.isChainCall())
2737 Attrs.addAttribute(llvm::Attribute::Nest);
2738 else if (AI.getInReg())
2739 Attrs.addAttribute(llvm::Attribute::InReg);
2740 Attrs.addStackAlignmentAttr(llvm::MaybeAlign(AI.getDirectAlign()));
2741
2742 if (canApplyNoFPClass(AI, ParamType, false))
2743 Attrs.addNoFPClassAttr(getNoFPClassTestMask(getLangOpts()));
2744 break;
2745 case ABIArgInfo::Indirect: {
2746 if (AI.getInReg())
2747 Attrs.addAttribute(llvm::Attribute::InReg);
2748
2749 if (AI.getIndirectByVal())
2750 Attrs.addByValAttr(getTypes().ConvertTypeForMem(ParamType));
2751
2752 auto *Decl = ParamType->getAsRecordDecl();
2753 if (CodeGenOpts.PassByValueIsNoAlias && Decl &&
2754 Decl->getArgPassingRestrictions() ==
2756 // When calling the function, the pointer passed in will be the only
2757 // reference to the underlying object. Mark it accordingly.
2758 Attrs.addAttribute(llvm::Attribute::NoAlias);
2759
2760 // TODO: We could add the byref attribute if not byval, but it would
2761 // require updating many testcases.
2762
2763 CharUnits Align = AI.getIndirectAlign();
2764
2765 // In a byval argument, it is important that the required
2766 // alignment of the type is honored, as LLVM might be creating a
2767 // *new* stack object, and needs to know what alignment to give
2768 // it. (Sometimes it can deduce a sensible alignment on its own,
2769 // but not if clang decides it must emit a packed struct, or the
2770 // user specifies increased alignment requirements.)
2771 //
2772 // This is different from indirect *not* byval, where the object
2773 // exists already, and the align attribute is purely
2774 // informative.
2775 assert(!Align.isZero());
2776
2777 // For now, only add this when we have a byval argument.
2778 // TODO: be less lazy about updating test cases.
2779 if (AI.getIndirectByVal())
2780 Attrs.addAlignmentAttr(Align.getQuantity());
2781
2782 // byval disables readnone and readonly.
2783 AddPotentialArgAccess();
2784 break;
2785 }
2787 CharUnits Align = AI.getIndirectAlign();
2788 Attrs.addByRefAttr(getTypes().ConvertTypeForMem(ParamType));
2789 Attrs.addAlignmentAttr(Align.getQuantity());
2790 break;
2791 }
2792 case ABIArgInfo::Ignore:
2793 case ABIArgInfo::Expand:
2795 break;
2796
2798 // inalloca disables readnone and readonly.
2799 AddPotentialArgAccess();
2800 continue;
2801 }
2802
2803 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
2804 QualType PTy = RefTy->getPointeeType();
2805 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2806 Attrs.addDereferenceableAttr(
2807 getMinimumObjectSize(PTy).getQuantity());
2808 if (getTypes().getTargetAddressSpace(PTy) == 0 &&
2809 !CodeGenOpts.NullPointerIsValid)
2810 Attrs.addAttribute(llvm::Attribute::NonNull);
2811 if (PTy->isObjectType()) {
2812 llvm::Align Alignment =
2814 Attrs.addAlignmentAttr(Alignment);
2815 }
2816 }
2817
2818 // From OpenCL spec v3.0.10 section 6.3.5 Alignment of Types:
2819 // > For arguments to a __kernel function declared to be a pointer to a
2820 // > data type, the OpenCL compiler can assume that the pointee is always
2821 // > appropriately aligned as required by the data type.
2822 if (TargetDecl && TargetDecl->hasAttr<OpenCLKernelAttr>() &&
2823 ParamType->isPointerType()) {
2824 QualType PTy = ParamType->getPointeeType();
2825 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2826 llvm::Align Alignment =
2828 Attrs.addAlignmentAttr(Alignment);
2829 }
2830 }
2831
2832 switch (FI.getExtParameterInfo(ArgNo).getABI()) {
2834 break;
2835
2837 // Add 'sret' if we haven't already used it for something, but
2838 // only if the result is void.
2839 if (!hasUsedSRet && RetTy->isVoidType()) {
2840 Attrs.addStructRetAttr(getTypes().ConvertTypeForMem(ParamType));
2841 hasUsedSRet = true;
2842 }
2843
2844 // Add 'noalias' in either case.
2845 Attrs.addAttribute(llvm::Attribute::NoAlias);
2846
2847 // Add 'dereferenceable' and 'alignment'.
2848 auto PTy = ParamType->getPointeeType();
2849 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2850 auto info = getContext().getTypeInfoInChars(PTy);
2851 Attrs.addDereferenceableAttr(info.Width.getQuantity());
2852 Attrs.addAlignmentAttr(info.Align.getAsAlign());
2853 }
2854 break;
2855 }
2856
2858 Attrs.addAttribute(llvm::Attribute::SwiftError);
2859 break;
2860
2862 Attrs.addAttribute(llvm::Attribute::SwiftSelf);
2863 break;
2864
2866 Attrs.addAttribute(llvm::Attribute::SwiftAsync);
2867 break;
2868 }
2869
2870 if (FI.getExtParameterInfo(ArgNo).isNoEscape())
2871 Attrs.addAttribute(llvm::Attribute::NoCapture);
2872
2873 if (Attrs.hasAttributes()) {
2874 unsigned FirstIRArg, NumIRArgs;
2875 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2876 for (unsigned i = 0; i < NumIRArgs; i++)
2877 ArgAttrs[FirstIRArg + i] = ArgAttrs[FirstIRArg + i].addAttributes(
2878 getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), Attrs));
2879 }
2880 }
2881 assert(ArgNo == FI.arg_size());
2882
2883 AttrList = llvm::AttributeList::get(
2884 getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs),
2885 llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs);
2886}
2887
2888/// An argument came in as a promoted argument; demote it back to its
2889/// declared type.
2890static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
2891 const VarDecl *var,
2892 llvm::Value *value) {
2893 llvm::Type *varType = CGF.ConvertType(var->getType());
2894
2895 // This can happen with promotions that actually don't change the
2896 // underlying type, like the enum promotions.
2897 if (value->getType() == varType) return value;
2898
2899 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
2900 && "unexpected promotion type");
2901
2902 if (isa<llvm::IntegerType>(varType))
2903 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2904
2905 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2906}
2907
2908/// Returns the attribute (either parameter attribute, or function
2909/// attribute), which declares argument ArgNo to be non-null.
2910static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2911 QualType ArgType, unsigned ArgNo) {
2912 // FIXME: __attribute__((nonnull)) can also be applied to:
2913 // - references to pointers, where the pointee is known to be
2914 // nonnull (apparently a Clang extension)
2915 // - transparent unions containing pointers
2916 // In the former case, LLVM IR cannot represent the constraint. In
2917 // the latter case, we have no guarantee that the transparent union
2918 // is in fact passed as a pointer.
2919 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2920 return nullptr;
2921 // First, check attribute on parameter itself.
2922 if (PVD) {
2923 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2924 return ParmNNAttr;
2925 }
2926 // Check function attributes.
2927 if (!FD)
2928 return nullptr;
2929 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
2930 if (NNAttr->isNonNull(ArgNo))
2931 return NNAttr;
2932 }
2933 return nullptr;
2934}
2935
2936namespace {
2937 struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2938 Address Temp;
2939 Address Arg;
2940 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
2941 void Emit(CodeGenFunction &CGF, Flags flags) override {
2942 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2943 CGF.Builder.CreateStore(errorValue, Arg);
2944 }
2945 };
2946}
2947
2949 llvm::Function *Fn,
2950 const FunctionArgList &Args) {
2951 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
2952 // Naked functions don't have prologues.
2953 return;
2954
2955 // If this is an implicit-return-zero function, go ahead and
2956 // initialize the return value. TODO: it might be nice to have
2957 // a more general mechanism for this that didn't require synthesized
2958 // return statements.
2959 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
2960 if (FD->hasImplicitReturnZero()) {
2961 QualType RetTy = FD->getReturnType().getUnqualifiedType();
2962 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
2963 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
2965 }
2966 }
2967
2968 // FIXME: We no longer need the types from FunctionArgList; lift up and
2969 // simplify.
2970
2971 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
2972 assert(Fn->arg_size() == IRFunctionArgs.totalIRArgs());
2973
2974 // If we're using inalloca, all the memory arguments are GEPs off of the last
2975 // parameter, which is a pointer to the complete memory area.
2976 Address ArgStruct = Address::invalid();
2977 if (IRFunctionArgs.hasInallocaArg())
2978 ArgStruct = Address(Fn->getArg(IRFunctionArgs.getInallocaArgNo()),
2980
2981 // Name the struct return parameter.
2982 if (IRFunctionArgs.hasSRetArg()) {
2983 auto AI = Fn->getArg(IRFunctionArgs.getSRetArgNo());
2984 AI->setName("agg.result");
2985 AI->addAttr(llvm::Attribute::NoAlias);
2986 }
2987
2988 // Track if we received the parameter as a pointer (indirect, byval, or
2989 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
2990 // into a local alloca for us.
2992 ArgVals.reserve(Args.size());
2993
2994 // Create a pointer value for every parameter declaration. This usually
2995 // entails copying one or more LLVM IR arguments into an alloca. Don't push
2996 // any cleanups or do anything that might unwind. We do that separately, so
2997 // we can push the cleanups in the correct order for the ABI.
2998 assert(FI.arg_size() == Args.size() &&
2999 "Mismatch between function signature & arguments.");
3000 unsigned ArgNo = 0;
3002 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
3003 i != e; ++i, ++info_it, ++ArgNo) {
3004 const VarDecl *Arg = *i;
3005 const ABIArgInfo &ArgI = info_it->info;
3006
3007 bool isPromoted =
3008 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
3009 // We are converting from ABIArgInfo type to VarDecl type directly, unless
3010 // the parameter is promoted. In this case we convert to
3011 // CGFunctionInfo::ArgInfo type with subsequent argument demotion.
3012 QualType Ty = isPromoted ? info_it->type : Arg->getType();
3013 assert(hasScalarEvaluationKind(Ty) ==
3015
3016 unsigned FirstIRArg, NumIRArgs;
3017 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
3018
3019 switch (ArgI.getKind()) {
3020 case ABIArgInfo::InAlloca: {
3021 assert(NumIRArgs == 0);
3022 auto FieldIndex = ArgI.getInAllocaFieldIndex();
3023 Address V =
3024 Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName());
3025 if (ArgI.getInAllocaIndirect())
3027 getContext().getTypeAlignInChars(Ty));
3028 ArgVals.push_back(ParamValue::forIndirect(V));
3029 break;
3030 }
3031
3034 assert(NumIRArgs == 1);
3036 Fn->getArg(FirstIRArg), Ty, ArgI.getIndirectAlign(), false, nullptr,
3037 nullptr, KnownNonNull);
3038
3039 if (!hasScalarEvaluationKind(Ty)) {
3040 // Aggregates and complex variables are accessed by reference. All we
3041 // need to do is realign the value, if requested. Also, if the address
3042 // may be aliased, copy it to ensure that the parameter variable is
3043 // mutable and has a unique adress, as C requires.
3044 if (ArgI.getIndirectRealign() || ArgI.isIndirectAliased()) {
3045 RawAddress AlignedTemp = CreateMemTemp(Ty, "coerce");
3046
3047 // Copy from the incoming argument pointer to the temporary with the
3048 // appropriate alignment.
3049 //
3050 // FIXME: We should have a common utility for generating an aggregate
3051 // copy.
3054 AlignedTemp.getPointer(), AlignedTemp.getAlignment().getAsAlign(),
3055 ParamAddr.emitRawPointer(*this),
3056 ParamAddr.getAlignment().getAsAlign(),
3057 llvm::ConstantInt::get(IntPtrTy, Size.getQuantity()));
3058 ParamAddr = AlignedTemp;
3059 }
3060 ArgVals.push_back(ParamValue::forIndirect(ParamAddr));
3061 } else {
3062 // Load scalar value from indirect argument.
3063 llvm::Value *V =
3064 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc());
3065
3066 if (isPromoted)
3067 V = emitArgumentDemotion(*this, Arg, V);
3068 ArgVals.push_back(ParamValue::forDirect(V));
3069 }
3070 break;
3071 }
3072
3073 case ABIArgInfo::Extend:
3074 case ABIArgInfo::Direct: {
3075 auto AI = Fn->getArg(FirstIRArg);
3076 llvm::Type *LTy = ConvertType(Arg->getType());
3077
3078 // Prepare parameter attributes. So far, only attributes for pointer
3079 // parameters are prepared. See
3080 // http://llvm.org/docs/LangRef.html#paramattrs.
3081 if (ArgI.getDirectOffset() == 0 && LTy->isPointerTy() &&
3082 ArgI.getCoerceToType()->isPointerTy()) {
3083 assert(NumIRArgs == 1);
3084
3085 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
3086 // Set `nonnull` attribute if any.
3087 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
3088 PVD->getFunctionScopeIndex()) &&
3089 !CGM.getCodeGenOpts().NullPointerIsValid)
3090 AI->addAttr(llvm::Attribute::NonNull);
3091
3092 QualType OTy = PVD->getOriginalType();
3093 if (const auto *ArrTy =
3094 getContext().getAsConstantArrayType(OTy)) {
3095 // A C99 array parameter declaration with the static keyword also
3096 // indicates dereferenceability, and if the size is constant we can
3097 // use the dereferenceable attribute (which requires the size in
3098 // bytes).
3099 if (ArrTy->getSizeModifier() == ArraySizeModifier::Static) {
3100 QualType ETy = ArrTy->getElementType();
3101 llvm::Align Alignment =
3103 AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(Alignment));
3104 uint64_t ArrSize = ArrTy->getZExtSize();
3105 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
3106 ArrSize) {
3107 llvm::AttrBuilder Attrs(getLLVMContext());
3108 Attrs.addDereferenceableAttr(
3109 getContext().getTypeSizeInChars(ETy).getQuantity() *
3110 ArrSize);
3111 AI->addAttrs(Attrs);
3112 } else if (getContext().getTargetInfo().getNullPointerValue(
3113 ETy.getAddressSpace()) == 0 &&
3114 !CGM.getCodeGenOpts().NullPointerIsValid) {
3115 AI->addAttr(llvm::Attribute::NonNull);
3116 }
3117 }
3118 } else if (const auto *ArrTy =
3119 getContext().getAsVariableArrayType(OTy)) {
3120 // For C99 VLAs with the static keyword, we don't know the size so
3121 // we can't use the dereferenceable attribute, but in addrspace(0)
3122 // we know that it must be nonnull.
3123 if (ArrTy->getSizeModifier() == ArraySizeModifier::Static) {
3124 QualType ETy = ArrTy->getElementType();
3125 llvm::Align Alignment =
3127 AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(Alignment));
3128 if (!getTypes().getTargetAddressSpace(ETy) &&
3129 !CGM.getCodeGenOpts().NullPointerIsValid)
3130 AI->addAttr(llvm::Attribute::NonNull);
3131 }
3132 }
3133
3134 // Set `align` attribute if any.
3135 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
3136 if (!AVAttr)
3137 if (const auto *TOTy = OTy->getAs<TypedefType>())
3138 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
3139 if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) {
3140 // If alignment-assumption sanitizer is enabled, we do *not* add
3141 // alignment attribute here, but emit normal alignment assumption,
3142 // so the UBSAN check could function.
3143 llvm::ConstantInt *AlignmentCI =
3144 cast<llvm::ConstantInt>(EmitScalarExpr(AVAttr->getAlignment()));
3145 uint64_t AlignmentInt =
3146 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment);
3147 if (AI->getParamAlign().valueOrOne() < AlignmentInt) {
3148 AI->removeAttr(llvm::Attribute::AttrKind::Alignment);
3149 AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(
3150 llvm::Align(AlignmentInt)));
3151 }
3152 }
3153 }
3154
3155 // Set 'noalias' if an argument type has the `restrict` qualifier.
3156 if (Arg->getType().isRestrictQualified())
3157 AI->addAttr(llvm::Attribute::NoAlias);
3158 }
3159
3160 // Prepare the argument value. If we have the trivial case, handle it
3161 // with no muss and fuss.
3162 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
3163 ArgI.getCoerceToType() == ConvertType(Ty) &&
3164 ArgI.getDirectOffset() == 0) {
3165 assert(NumIRArgs == 1);
3166
3167 // LLVM expects swifterror parameters to be used in very restricted
3168 // ways. Copy the value into a less-restricted temporary.
3169 llvm::Value *V = AI;
3170 if (FI.getExtParameterInfo(ArgNo).getABI()
3172 QualType pointeeTy = Ty->getPointeeType();
3173 assert(pointeeTy->isPointerType());
3174 RawAddress temp =
3175 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
3177 V, pointeeTy, getContext().getTypeAlignInChars(pointeeTy));
3178 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
3179 Builder.CreateStore(incomingErrorValue, temp);
3180 V = temp.getPointer();
3181
3182 // Push a cleanup to copy the value back at the end of the function.
3183 // The convention does not guarantee that the value will be written
3184 // back if the function exits with an unwind exception.
3185 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
3186 }
3187
3188 // Ensure the argument is the correct type.
3189 if (V->getType() != ArgI.getCoerceToType())
3190 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
3191
3192 if (isPromoted)
3193 V = emitArgumentDemotion(*this, Arg, V);
3194
3195 // Because of merging of function types from multiple decls it is
3196 // possible for the type of an argument to not match the corresponding
3197 // type in the function type. Since we are codegening the callee
3198 // in here, add a cast to the argument type.
3199 llvm::Type *LTy = ConvertType(Arg->getType());
3200 if (V->getType() != LTy)
3201 V = Builder.CreateBitCast(V, LTy);
3202
3203 ArgVals.push_back(ParamValue::forDirect(V));
3204 break;
3205 }
3206
3207 // VLST arguments are coerced to VLATs at the function boundary for
3208 // ABI consistency. If this is a VLST that was coerced to
3209 // a VLAT at the function boundary and the types match up, use
3210 // llvm.vector.extract to convert back to the original VLST.
3211 if (auto *VecTyTo = dyn_cast<llvm::FixedVectorType>(ConvertType(Ty))) {
3212 llvm::Value *Coerced = Fn->getArg(FirstIRArg);
3213 if (auto *VecTyFrom =
3214 dyn_cast<llvm::ScalableVectorType>(Coerced->getType())) {
3215 // If we are casting a scalable i1 predicate vector to a fixed i8
3216 // vector, bitcast the source and use a vector extract.
3217 if (VecTyFrom->getElementType()->isIntegerTy(1) &&
3218 VecTyFrom->getElementCount().isKnownMultipleOf(8) &&
3219 VecTyTo->getElementType() == Builder.getInt8Ty()) {
3220 VecTyFrom = llvm::ScalableVectorType::get(
3221 VecTyTo->getElementType(),
3222 VecTyFrom->getElementCount().getKnownMinValue() / 8);
3223 Coerced = Builder.CreateBitCast(Coerced, VecTyFrom);
3224 }
3225 if (VecTyFrom->getElementType() == VecTyTo->getElementType()) {
3226 llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty);
3227
3228 assert(NumIRArgs == 1);
3229 Coerced->setName(Arg->getName() + ".coerce");
3230 ArgVals.push_back(ParamValue::forDirect(Builder.CreateExtractVector(
3231 VecTyTo, Coerced, Zero, "cast.fixed")));
3232 break;
3233 }
3234 }
3235 }
3236
3237 llvm::StructType *STy =
3238 dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
3239 if (ArgI.isDirect() && !ArgI.getCanBeFlattened() && STy &&
3240 STy->getNumElements() > 1) {
3241 [[maybe_unused]] llvm::TypeSize StructSize =
3242 CGM.getDataLayout().getTypeAllocSize(STy);
3243 [[maybe_unused]] llvm::TypeSize PtrElementSize =
3244 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(Ty));
3245 if (STy->containsHomogeneousScalableVectorTypes()) {
3246 assert(StructSize == PtrElementSize &&
3247 "Only allow non-fractional movement of structure with"
3248 "homogeneous scalable vector type");
3249
3250 ArgVals.push_back(ParamValue::forDirect(AI));
3251 break;
3252 }
3253 }
3254
3255 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
3256 Arg->getName());
3257
3258 // Pointer to store into.
3259 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
3260
3261 // Fast-isel and the optimizer generally like scalar values better than
3262 // FCAs, so we flatten them if this is safe to do for this argument.
3263 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
3264 STy->getNumElements() > 1) {
3265 llvm::TypeSize StructSize = CGM.getDataLayout().getTypeAllocSize(STy);
3266 llvm::TypeSize PtrElementSize =
3267 CGM.getDataLayout().getTypeAllocSize(Ptr.getElementType());
3268 if (StructSize.isScalable()) {
3269 assert(STy->containsHomogeneousScalableVectorTypes() &&
3270 "ABI only supports structure with homogeneous scalable vector "
3271 "type");
3272 assert(StructSize == PtrElementSize &&
3273 "Only allow non-fractional movement of structure with"
3274 "homogeneous scalable vector type");
3275 assert(STy->getNumElements() == NumIRArgs);
3276
3277 llvm::Value *LoadedStructValue = llvm::PoisonValue::get(STy);
3278 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3279 auto *AI = Fn->getArg(FirstIRArg + i);
3280 AI->setName(Arg->getName() + ".coerce" + Twine(i));
3281 LoadedStructValue =
3282 Builder.CreateInsertValue(LoadedStructValue, AI, i);
3283 }
3284
3285 Builder.CreateStore(LoadedStructValue, Ptr);
3286 } else {
3287 uint64_t SrcSize = StructSize.getFixedValue();
3288 uint64_t DstSize = PtrElementSize.getFixedValue();
3289
3290 Address AddrToStoreInto = Address::invalid();
3291 if (SrcSize <= DstSize) {
3292 AddrToStoreInto = Ptr.withElementType(STy);
3293 } else {
3294 AddrToStoreInto =
3295 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
3296 }
3297
3298 assert(STy->getNumElements() == NumIRArgs);
3299 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3300 auto AI = Fn->getArg(FirstIRArg + i);
3301 AI->setName(Arg->getName() + ".coerce" + Twine(i));
3302 Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i);
3303 Builder.CreateStore(AI, EltPtr);
3304 }
3305
3306 if (SrcSize > DstSize) {
3307 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
3308 }
3309 }
3310 } else {
3311 // Simple case, just do a coerced store of the argument into the alloca.
3312 assert(NumIRArgs == 1);
3313 auto AI = Fn->getArg(FirstIRArg);
3314 AI->setName(Arg->getName() + ".coerce");
3315 CreateCoercedStore(AI, Ptr, /*DstIsVolatile=*/false, *this);
3316 }
3317
3318 // Match to what EmitParmDecl is expecting for this type.
3320 llvm::Value *V =
3321 EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc());
3322 if (isPromoted)
3323 V = emitArgumentDemotion(*this, Arg, V);
3324 ArgVals.push_back(ParamValue::forDirect(V));
3325 } else {
3326 ArgVals.push_back(ParamValue::forIndirect(Alloca));
3327 }
3328 break;
3329 }
3330
3332 // Reconstruct into a temporary.
3333 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
3334 ArgVals.push_back(ParamValue::forIndirect(alloca));
3335
3336 auto coercionType = ArgI.getCoerceAndExpandType();
3337 alloca = alloca.withElementType(coercionType);
3338
3339 unsigned argIndex = FirstIRArg;
3340 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3341 llvm::Type *eltType = coercionType->getElementType(i);
3343 continue;
3344
3345 auto eltAddr = Builder.CreateStructGEP(alloca, i);
3346 auto elt = Fn->getArg(argIndex++);
3347 Builder.CreateStore(elt, eltAddr);
3348 }
3349 assert(argIndex == FirstIRArg + NumIRArgs);
3350 break;
3351 }
3352
3353 case ABIArgInfo::Expand: {
3354 // If this structure was expanded into multiple arguments then
3355 // we need to create a temporary and reconstruct it from the
3356 // arguments.
3357 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
3358 LValue LV = MakeAddrLValue(Alloca, Ty);
3359 ArgVals.push_back(ParamValue::forIndirect(Alloca));
3360
3361 auto FnArgIter = Fn->arg_begin() + FirstIRArg;
3362 ExpandTypeFromArgs(Ty, LV, FnArgIter);
3363 assert(FnArgIter == Fn->arg_begin() + FirstIRArg + NumIRArgs);
3364 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
3365 auto AI = Fn->getArg(FirstIRArg + i);
3366 AI->setName(Arg->getName() + "." + Twine(i));
3367 }
3368 break;
3369 }
3370
3371 case ABIArgInfo::Ignore:
3372 assert(NumIRArgs == 0);
3373 // Initialize the local variable appropriately.
3374 if (!hasScalarEvaluationKind(Ty)) {
3375 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
3376 } else {
3377 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
3378 ArgVals.push_back(ParamValue::forDirect(U));
3379 }
3380 break;
3381 }
3382 }
3383
3384 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3385 for (int I = Args.size() - 1; I >= 0; --I)
3386 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
3387 } else {
3388 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3389 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
3390 }
3391}
3392
3393static void eraseUnusedBitCasts(llvm::Instruction *insn) {
3394 while (insn->use_empty()) {
3395 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
3396 if (!bitcast) return;
3397
3398 // This is "safe" because we would have used a ConstantExpr otherwise.
3399 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
3400 bitcast->eraseFromParent();
3401 }
3402}
3403
3404/// Try to emit a fused autorelease of a return result.
3406 llvm::Value *result) {
3407 // We must be immediately followed the cast.
3408 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
3409 if (BB->empty()) return nullptr;
3410 if (&BB->back() != result) return nullptr;
3411
3412 llvm::Type *resultType = result->getType();
3413
3414 // result is in a BasicBlock and is therefore an Instruction.
3415 llvm::Instruction *generator = cast<llvm::Instruction>(result);
3416
3418
3419 // Look for:
3420 // %generator = bitcast %type1* %generator2 to %type2*
3421 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
3422 // We would have emitted this as a constant if the operand weren't
3423 // an Instruction.
3424 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
3425
3426 // Require the generator to be immediately followed by the cast.
3427 if (generator->getNextNode() != bitcast)
3428 return nullptr;
3429
3430 InstsToKill.push_back(bitcast);
3431 }
3432
3433 // Look for:
3434 // %generator = call i8* @objc_retain(i8* %originalResult)
3435 // or
3436 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
3437 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
3438 if (!call) return nullptr;
3439
3440 bool doRetainAutorelease;
3441
3442 if (call->getCalledOperand() == CGF.CGM.getObjCEntrypoints().objc_retain) {
3443 doRetainAutorelease = true;
3444 } else if (call->getCalledOperand() ==
3446 doRetainAutorelease = false;
3447
3448 // If we emitted an assembly marker for this call (and the
3449 // ARCEntrypoints field should have been set if so), go looking
3450 // for that call. If we can't find it, we can't do this
3451 // optimization. But it should always be the immediately previous
3452 // instruction, unless we needed bitcasts around the call.
3454 llvm::Instruction *prev = call->getPrevNode();
3455 assert(prev);
3456 if (isa<llvm::BitCastInst>(prev)) {
3457 prev = prev->getPrevNode();
3458 assert(prev);
3459 }
3460 assert(isa<llvm::CallInst>(prev));
3461 assert(cast<llvm::CallInst>(prev)->getCalledOperand() ==
3463 InstsToKill.push_back(prev);
3464 }
3465 } else {
3466 return nullptr;
3467 }
3468
3469 result = call->getArgOperand(0);
3470 InstsToKill.push_back(call);
3471
3472 // Keep killing bitcasts, for sanity. Note that we no longer care
3473 // about precise ordering as long as there's exactly one use.
3474 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
3475 if (!bitcast->hasOneUse()) break;
3476 InstsToKill.push_back(bitcast);
3477 result = bitcast->getOperand(0);
3478 }
3479
3480 // Delete all the unnecessary instructions, from latest to earliest.
3481 for (auto *I : InstsToKill)
3482 I->eraseFromParent();
3483
3484 // Do the fused retain/autorelease if we were asked to.
3485 if (doRetainAutorelease)
3486 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
3487
3488 // Cast back to the result type.
3489 return CGF.Builder.CreateBitCast(result, resultType);
3490}
3491
3492/// If this is a +1 of the value of an immutable 'self', remove it.
3494 llvm::Value *result) {
3495 // This is only applicable to a method with an immutable 'self'.
3496 const ObjCMethodDecl *method =
3497 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
3498 if (!method) return nullptr;
3499 const VarDecl *self = method->getSelfDecl();
3500 if (!self->getType().isConstQualified()) return nullptr;
3501
3502 // Look for a retain call. Note: stripPointerCasts looks through returned arg
3503 // functions, which would cause us to miss the retain.
3504 llvm::CallInst *retainCall = dyn_cast<llvm::CallInst>(result);
3505 if (!retainCall || retainCall->getCalledOperand() !=
3507 return nullptr;
3508
3509 // Look for an ordinary load of 'self'.
3510 llvm::Value *retainedValue = retainCall->getArgOperand(0);
3511 llvm::LoadInst *load =
3512 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
3513 if (!load || load->isAtomic() || load->isVolatile() ||
3514 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getBasePointer())
3515 return nullptr;
3516
3517 // Okay! Burn it all down. This relies for correctness on the
3518 // assumption that the retain is emitted as part of the return and
3519 // that thereafter everything is used "linearly".
3520 llvm::Type *resultType = result->getType();
3521 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
3522 assert(retainCall->use_empty());
3523 retainCall->eraseFromParent();
3524 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
3525
3526 return CGF.Builder.CreateBitCast(load, resultType);
3527}
3528
3529/// Emit an ARC autorelease of the result of a function.
3530///
3531/// \return the value to actually return from the function
3533 llvm::Value *result) {
3534 // If we're returning 'self', kill the initial retain. This is a
3535 // heuristic attempt to "encourage correctness" in the really unfortunate
3536 // case where we have a return of self during a dealloc and we desperately
3537 // need to avoid the possible autorelease.
3538 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
3539 return self;
3540
3541 // At -O0, try to emit a fused retain/autorelease.
3542 if (CGF.shouldUseFusedARCCalls())
3543 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
3544 return fused;
3545
3546 return CGF.EmitARCAutoreleaseReturnValue(result);
3547}
3548
3549/// Heuristically search for a dominating store to the return-value slot.
3551 llvm::Value *ReturnValuePtr = CGF.ReturnValue.getBasePointer();
3552
3553 // Check if a User is a store which pointerOperand is the ReturnValue.
3554 // We are looking for stores to the ReturnValue, not for stores of the
3555 // ReturnValue to some other location.
3556 auto GetStoreIfValid = [&CGF,
3557 ReturnValuePtr](llvm::User *U) -> llvm::StoreInst * {
3558 auto *SI = dyn_cast<llvm::StoreInst>(U);
3559 if (!SI || SI->getPointerOperand() != ReturnValuePtr ||
3560 SI->getValueOperand()->getType() != CGF.ReturnValue.getElementType())
3561 return nullptr;
3562 // These aren't actually possible for non-coerced returns, and we
3563 // only care about non-coerced returns on this code path.
3564 // All memory instructions inside __try block are volatile.
3565 assert(!SI->isAtomic() &&
3566 (!SI->isVolatile() || CGF.currentFunctionUsesSEHTry()));
3567 return SI;
3568 };
3569 // If there are multiple uses of the return-value slot, just check
3570 // for something immediately preceding the IP. Sometimes this can
3571 // happen with how we generate implicit-returns; it can also happen
3572 // with noreturn cleanups.
3573 if (!ReturnValuePtr->hasOneUse()) {
3574 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
3575 if (IP->empty()) return nullptr;
3576
3577 // Look at directly preceding instruction, skipping bitcasts and lifetime
3578 // markers.
3579 for (llvm::Instruction &I : make_range(IP->rbegin(), IP->rend())) {
3580 if (isa<llvm::BitCastInst>(&I))
3581 continue;
3582 if (auto *II = dyn_cast<llvm::IntrinsicInst>(&I))
3583 if (II->getIntrinsicID() == llvm::Intrinsic::lifetime_end)
3584 continue;
3585
3586 return GetStoreIfValid(&I);
3587 }
3588 return nullptr;
3589 }
3590
3591 llvm::StoreInst *store = GetStoreIfValid(ReturnValuePtr->user_back());
3592 if (!store) return nullptr;
3593
3594 // Now do a first-and-dirty dominance check: just walk up the
3595 // single-predecessors chain from the current insertion point.
3596 llvm::BasicBlock *StoreBB = store->getParent();
3597 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
3599 while (IP != StoreBB) {
3600 if (!SeenBBs.insert(IP).second || !(IP = IP->getSinglePredecessor()))
3601 return nullptr;
3602 }
3603
3604 // Okay, the store's basic block dominates the insertion point; we
3605 // can do our thing.
3606 return store;
3607}
3608
3609// Helper functions for EmitCMSEClearRecord
3610
3611// Set the bits corresponding to a field having width `BitWidth` and located at
3612// offset `BitOffset` (from the least significant bit) within a storage unit of
3613// `Bits.size()` bytes. Each element of `Bits` corresponds to one target byte.
3614// Use little-endian layout, i.e.`Bits[0]` is the LSB.
3615static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int BitOffset,
3616 int BitWidth, int CharWidth) {
3617 assert(CharWidth <= 64);
3618 assert(static_cast<unsigned>(BitWidth) <= Bits.size() * CharWidth);
3619
3620 int Pos = 0;
3621 if (BitOffset >= CharWidth) {
3622 Pos += BitOffset / CharWidth;
3623 BitOffset = BitOffset % CharWidth;
3624 }
3625
3626 const uint64_t Used = (uint64_t(1) << CharWidth) - 1;
3627 if (BitOffset + BitWidth >= CharWidth) {
3628 Bits[Pos++] |= (Used << BitOffset) & Used;
3629 BitWidth -= CharWidth - BitOffset;
3630 BitOffset = 0;
3631 }
3632
3633 while (BitWidth >= CharWidth) {
3634 Bits[Pos++] = Used;
3635 BitWidth -= CharWidth;
3636 }
3637
3638 if (BitWidth > 0)
3639 Bits[Pos++] |= (Used >> (CharWidth - BitWidth)) << BitOffset;
3640}
3641
3642// Set the bits corresponding to a field having width `BitWidth` and located at
3643// offset `BitOffset` (from the least significant bit) within a storage unit of
3644// `StorageSize` bytes, located at `StorageOffset` in `Bits`. Each element of
3645// `Bits` corresponds to one target byte. Use target endian layout.
3646static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int StorageOffset,
3647 int StorageSize, int BitOffset, int BitWidth,
3648 int CharWidth, bool BigEndian) {
3649
3650 SmallVector<uint64_t, 8> TmpBits(StorageSize);
3651 setBitRange(TmpBits, BitOffset, BitWidth, CharWidth);
3652
3653 if (BigEndian)
3654 std::reverse(TmpBits.begin(), TmpBits.end());
3655
3656 for (uint64_t V : TmpBits)
3657 Bits[StorageOffset++] |= V;
3658}
3659
3660static void setUsedBits(CodeGenModule &, QualType, int,
3662
3663// Set the bits in `Bits`, which correspond to the value representations of
3664// the actual members of the record type `RTy`. Note that this function does
3665// not handle base classes, virtual tables, etc, since they cannot happen in
3666// CMSE function arguments or return. The bit mask corresponds to the target
3667// memory layout, i.e. it's endian dependent.
3668static void setUsedBits(CodeGenModule &CGM, const RecordType *RTy, int Offset,
3670 ASTContext &Context = CGM.getContext();
3671 int CharWidth = Context.getCharWidth();
3672 const RecordDecl *RD = RTy->getDecl()->getDefinition();
3673 const ASTRecordLayout &ASTLayout = Context.getASTRecordLayout(RD);
3674 const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(RD);
3675
3676 int Idx = 0;
3677 for (auto I = RD->field_begin(), E = RD->field_end(); I != E; ++I, ++Idx) {
3678 const FieldDecl *F = *I;
3679
3680 if (F->isUnnamedBitField() || F->isZeroLengthBitField(Context) ||
3682 continue;
3683
3684 if (F->isBitField()) {
3685 const CGBitFieldInfo &BFI = Layout.getBitFieldInfo(F);
3686 setBitRange(Bits, Offset + BFI.StorageOffset.getQuantity(),
3687 BFI.StorageSize / CharWidth, BFI.Offset,
3688 BFI.Size, CharWidth,
3689 CGM.getDataLayout().isBigEndian());
3690 continue;
3691 }
3692
3693 setUsedBits(CGM, F->getType(),
3694 Offset + ASTLayout.getFieldOffset(Idx) / CharWidth, Bits);
3695 }
3696}
3697
3698// Set the bits in `Bits`, which correspond to the value representations of
3699// the elements of an array type `ATy`.
3700static void setUsedBits(CodeGenModule &CGM, const ConstantArrayType *ATy,
3701 int Offset, SmallVectorImpl<uint64_t> &Bits) {
3702 const ASTContext &Context = CGM.getContext();
3703
3704 QualType ETy = Context.getBaseElementType(ATy);
3705 int Size = Context.getTypeSizeInChars(ETy).getQuantity();
3706 SmallVector<uint64_t, 4> TmpBits(Size);
3707 setUsedBits(CGM, ETy, 0, TmpBits);
3708
3709 for (int I = 0, N = Context.getConstantArrayElementCount(ATy); I < N; ++I) {
3710 auto Src = TmpBits.begin();
3711 auto Dst = Bits.begin() + Offset + I * Size;
3712 for (int J = 0; J < Size; ++J)
3713 *Dst++ |= *Src++;
3714 }
3715}
3716
3717// Set the bits in `Bits`, which correspond to the value representations of
3718// the type `QTy`.
3719static void setUsedBits(CodeGenModule &CGM, QualType QTy, int Offset,
3721 if (const auto *RTy = QTy->getAs<RecordType>())
3722 return setUsedBits(CGM, RTy, Offset, Bits);
3723
3724 ASTContext &Context = CGM.getContext();
3725 if (const auto *ATy = Context.getAsConstantArrayType(QTy))
3726 return setUsedBits(CGM, ATy, Offset, Bits);
3727
3728 int Size = Context.getTypeSizeInChars(QTy).getQuantity();
3729 if (Size <= 0)
3730 return;
3731
3732 std::fill_n(Bits.begin() + Offset, Size,
3733 (uint64_t(1) << Context.getCharWidth()) - 1);
3734}
3735
3737 int Pos, int Size, int CharWidth,
3738 bool BigEndian) {
3739 assert(Size > 0);
3740 uint64_t Mask = 0;
3741 if (BigEndian) {
3742 for (auto P = Bits.begin() + Pos, E = Bits.begin() + Pos + Size; P != E;
3743 ++P)
3744 Mask = (Mask << CharWidth) | *P;
3745 } else {
3746 auto P = Bits.begin() + Pos + Size, End = Bits.begin() + Pos;
3747 do
3748 Mask = (Mask << CharWidth) | *--P;
3749 while (P != End);
3750 }
3751 return Mask;
3752}
3753
3754// Emit code to clear the bits in a record, which aren't a part of any user
3755// declared member, when the record is a function return.
3756llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3757 llvm::IntegerType *ITy,
3758 QualType QTy) {
3759 assert(Src->getType() == ITy);
3760 assert(ITy->getScalarSizeInBits() <= 64);
3761
3762 const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3763 int Size = DataLayout.getTypeStoreSize(ITy);
3764 SmallVector<uint64_t, 4> Bits(Size);
3765 setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
3766
3767 int CharWidth = CGM.getContext().getCharWidth();
3768 uint64_t Mask =
3769 buildMultiCharMask(Bits, 0, Size, CharWidth, DataLayout.isBigEndian());
3770
3771 return Builder.CreateAnd(Src, Mask, "cmse.clear");
3772}
3773
3774// Emit code to clear the bits in a record, which aren't a part of any user
3775// declared member, when the record is a function argument.
3776llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3777 llvm::ArrayType *ATy,
3778 QualType QTy) {
3779 const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3780 int Size = DataLayout.getTypeStoreSize(ATy);
3781 SmallVector<uint64_t, 16> Bits(Size);
3782 setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
3783
3784 // Clear each element of the LLVM array.
3785 int CharWidth = CGM.getContext().getCharWidth();
3786 int CharsPerElt =
3787 ATy->getArrayElementType()->getScalarSizeInBits() / CharWidth;
3788 int MaskIndex = 0;
3789 llvm::Value *R = llvm::PoisonValue::get(ATy);
3790 for (int I = 0, N = ATy->getArrayNumElements(); I != N; ++I) {
3791 uint64_t Mask = buildMultiCharMask(Bits, MaskIndex, CharsPerElt, CharWidth,
3792 DataLayout.isBigEndian());
3793 MaskIndex += CharsPerElt;
3794 llvm::Value *T0 = Builder.CreateExtractValue(Src, I);
3795 llvm::Value *T1 = Builder.CreateAnd(T0, Mask, "cmse.clear");
3796 R = Builder.CreateInsertValue(R, T1, I);
3797 }
3798
3799 return R;
3800}
3801
3803 bool EmitRetDbgLoc,
3804 SourceLocation EndLoc) {
3805 if (FI.isNoReturn()) {
3806 // Noreturn functions don't return.
3807 EmitUnreachable(EndLoc);
3808 return;
3809 }
3810
3811 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
3812 // Naked functions don't have epilogues.
3813 Builder.CreateUnreachable();
3814 return;
3815 }
3816
3817 // Functions with no result always return void.
3818 if (!ReturnValue.isValid()) {
3819 Builder.CreateRetVoid();
3820 return;
3821 }
3822
3823 llvm::DebugLoc RetDbgLoc;
3824 llvm::Value *RV = nullptr;
3825 QualType RetTy = FI.getReturnType();
3826 const ABIArgInfo &RetAI = FI.getReturnInfo();
3827
3828 switch (RetAI.getKind()) {
3830 // Aggregates get evaluated directly into the destination. Sometimes we
3831 // need to return the sret value in a register, though.
3832 assert(hasAggregateEvaluationKind(RetTy));
3833 if (RetAI.getInAllocaSRet()) {
3834 llvm::Function::arg_iterator EI = CurFn->arg_end();
3835 --EI;
3836 llvm::Value *ArgStruct = &*EI;
3837 llvm::Value *SRet = Builder.CreateStructGEP(
3838 FI.getArgStruct(), ArgStruct, RetAI.getInAllocaFieldIndex());
3839 llvm::Type *Ty =
3840 cast<llvm::GetElementPtrInst>(SRet)->getResultElementType();
3841 RV = Builder.CreateAlignedLoad(Ty, SRet, getPointerAlign(), "sret");
3842 }
3843 break;
3844
3845 case ABIArgInfo::Indirect: {
3846 auto AI = CurFn->arg_begin();
3847 if (RetAI.isSRetAfterThis())
3848 ++AI;
3849 switch (getEvaluationKind(RetTy)) {
3850 case TEK_Complex: {
3851 ComplexPairTy RT =
3854 /*isInit*/ true);
3855 break;
3856 }
3857 case TEK_Aggregate:
3858 // Do nothing; aggregates get evaluated directly into the destination.
3859 break;
3860 case TEK_Scalar: {
3861 LValueBaseInfo BaseInfo;
3862 TBAAAccessInfo TBAAInfo;
3863 CharUnits Alignment =
3864 CGM.getNaturalTypeAlignment(RetTy, &BaseInfo, &TBAAInfo);
3865 Address ArgAddr(&*AI, ConvertType(RetTy), Alignment);
3866 LValue ArgVal =
3867 LValue::MakeAddr(ArgAddr, RetTy, getContext(), BaseInfo, TBAAInfo);
3869 EmitLoadOfScalar(MakeAddrLValue(ReturnValue, RetTy), EndLoc), ArgVal,
3870 /*isInit*/ true);
3871 break;
3872 }
3873 }
3874 break;
3875 }
3876
3877 case ABIArgInfo::Extend:
3878 case ABIArgInfo::Direct:
3879 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
3880 RetAI.getDirectOffset() == 0) {
3881 // The internal return value temp always will have pointer-to-return-type
3882 // type, just do a load.
3883
3884 // If there is a dominating store to ReturnValue, we can elide
3885 // the load, zap the store, and usually zap the alloca.
3886 if (llvm::StoreInst *SI =
3888 // Reuse the debug location from the store unless there is
3889 // cleanup code to be emitted between the store and return
3890 // instruction.
3891 if (EmitRetDbgLoc && !AutoreleaseResult)
3892 RetDbgLoc = SI->getDebugLoc();
3893 // Get the stored value and nuke the now-dead store.
3894 RV = SI->getValueOperand();
3895 SI->eraseFromParent();
3896
3897 // Otherwise, we have to do a simple load.
3898 } else {
3900 }
3901 } else {
3902 // If the value is offset in memory, apply the offset now.
3903 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
3904
3905 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
3906 }
3907
3908 // In ARC, end functions that return a retainable type with a call
3909 // to objc_autoreleaseReturnValue.
3910 if (AutoreleaseResult) {
3911#ifndef NDEBUG
3912 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
3913 // been stripped of the typedefs, so we cannot use RetTy here. Get the
3914 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
3915 // CurCodeDecl or BlockInfo.
3916 QualType RT;
3917
3918 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
3919 RT = FD->getReturnType();
3920 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
3921 RT = MD->getReturnType();
3922 else if (isa<BlockDecl>(CurCodeDecl))
3924 else
3925 llvm_unreachable("Unexpected function/method type");
3926
3927 assert(getLangOpts().ObjCAutoRefCount &&
3928 !FI.isReturnsRetained() &&
3929 RT->isObjCRetainableType());
3930#endif
3931 RV = emitAutoreleaseOfResult(*this, RV);
3932 }
3933
3934 break;
3935
3936 case ABIArgInfo::Ignore:
3937 break;
3938
3940 auto coercionType = RetAI.getCoerceAndExpandType();
3941
3942 // Load all of the coerced elements out into results.
3944 Address addr = ReturnValue.withElementType(coercionType);
3945 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3946 auto coercedEltType = coercionType->getElementType(i);
3947 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
3948 continue;
3949
3950 auto eltAddr = Builder.CreateStructGEP(addr, i);
3951 auto elt = Builder.CreateLoad(eltAddr);
3952 results.push_back(elt);
3953 }
3954
3955 // If we have one result, it's the single direct result type.
3956 if (results.size() == 1) {
3957 RV = results[0];
3958
3959 // Otherwise, we need to make a first-class aggregate.
3960 } else {
3961 // Construct a return type that lacks padding elements.
3962 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
3963
3964 RV = llvm::PoisonValue::get(returnType);
3965 for (unsigned i = 0, e = results.size(); i != e; ++i) {
3966 RV = Builder.CreateInsertValue(RV, results[i], i);
3967 }
3968 }
3969 break;
3970 }
3971 case ABIArgInfo::Expand:
3973 llvm_unreachable("Invalid ABI kind for return argument");
3974 }
3975
3976 llvm::Instruction *Ret;
3977 if (RV) {
3978 if (CurFuncDecl && CurFuncDecl->hasAttr<CmseNSEntryAttr>()) {
3979 // For certain return types, clear padding bits, as they may reveal
3980 // sensitive information.
3981 // Small struct/union types are passed as integers.
3982 auto *ITy = dyn_cast<llvm::IntegerType>(RV->getType());
3983 if (ITy != nullptr && isa<RecordType>(RetTy.getCanonicalType()))
3984 RV = EmitCMSEClearRecord(RV, ITy, RetTy);
3985 }
3987 Ret = Builder.CreateRet(RV);
3988 } else {
3989 Ret = Builder.CreateRetVoid();
3990 }
3991
3992 if (RetDbgLoc)
3993 Ret->setDebugLoc(std::move(RetDbgLoc));
3994}
3995
3996void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) {
3997 // A current decl may not be available when emitting vtable thunks.
3998 if (!CurCodeDecl)
3999 return;
4000
4001 // If the return block isn't reachable, neither is this check, so don't emit
4002 // it.
4003 if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty())
4004 return;
4005
4006 ReturnsNonNullAttr *RetNNAttr = nullptr;
4007 if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
4008 RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
4009
4010 if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
4011 return;
4012
4013 // Prefer the returns_nonnull attribute if it's present.
4014 SourceLocation AttrLoc;
4015 SanitizerMask CheckKind;
4016 SanitizerHandler Handler;
4017 if (RetNNAttr) {
4018 assert(!requiresReturnValueNullabilityCheck() &&
4019 "Cannot check nullability and the nonnull attribute");
4020 AttrLoc = RetNNAttr->getLocation();
4021 CheckKind = SanitizerKind::ReturnsNonnullAttribute;
4022 Handler = SanitizerHandler::NonnullReturn;
4023 } else {
4024 if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl))
4025 if (auto *TSI = DD->getTypeSourceInfo())
4026 if (auto FTL = TSI->getTypeLoc().getAsAdjusted<FunctionTypeLoc>())
4027 AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
4028 CheckKind = SanitizerKind::NullabilityReturn;
4029 Handler = SanitizerHandler::NullabilityReturn;
4030 }
4031
4032 SanitizerScope SanScope(this);
4033
4034 // Make sure the "return" source location is valid. If we're checking a
4035 // nullability annotation, make sure the preconditions for the check are met.
4036 llvm::BasicBlock *Check = createBasicBlock("nullcheck");
4037 llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck");
4038 llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load");
4039 llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr);
4040 if (requiresReturnValueNullabilityCheck())
4041 CanNullCheck =
4042 Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition);
4043 Builder.CreateCondBr(CanNullCheck, Check, NoCheck);
4044 EmitBlock(Check);
4045
4046 // Now do the null check.
4047 llvm::Value *Cond = Builder.CreateIsNotNull(RV);
4048 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)};
4049 llvm::Value *DynamicData[] = {SLocPtr};
4050 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData);
4051
4052 EmitBlock(NoCheck);
4053
4054#ifndef NDEBUG
4055 // The return location should not be used after the check has been emitted.
4056 ReturnLocation = Address::invalid();
4057#endif
4058}
4059
4061 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
4062 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
4063}
4064
4066 QualType Ty) {
4067 // FIXME: Generate IR in one pass, rather than going back and fixing up these
4068 // placeholders.
4069 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
4070 llvm::Type *IRPtrTy = llvm::PointerType::getUnqual(CGF.getLLVMContext());
4071 llvm::Value *Placeholder = llvm::PoisonValue::get(IRPtrTy);
4072
4073 // FIXME: When we generate this IR in one pass, we shouldn't need
4074 // this win32-specific alignment hack.
4076 Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
4077
4078 return AggValueSlot::forAddr(Address(Placeholder, IRTy, Align),
4079 Ty.getQualifiers(),
4084}
4085
4087 const VarDecl *param,
4088 SourceLocation loc) {
4089 // StartFunction converted the ABI-lowered parameter(s) into a
4090 // local alloca. We need to turn that into an r-value suitable
4091 // for EmitCall.
4092 Address local = GetAddrOfLocalVar(param);
4093
4094 QualType type = param->getType();
4095
4096 // GetAddrOfLocalVar returns a pointer-to-pointer for references,
4097 // but the argument needs to be the original pointer.
4098 if (type->isReferenceType()) {
4099 args.add(RValue::get(Builder.CreateLoad(local)), type);
4100
4101 // In ARC, move out of consumed arguments so that the release cleanup
4102 // entered by StartFunction doesn't cause an over-release. This isn't
4103 // optimal -O0 code generation, but it should get cleaned up when
4104 // optimization is enabled. This also assumes that delegate calls are
4105 // performed exactly once for a set of arguments, but that should be safe.
4106 } else if (getLangOpts().ObjCAutoRefCount &&
4107 param->hasAttr<NSConsumedAttr>() &&
4108 type->isObjCRetainableType()) {
4109 llvm::Value *ptr = Builder.CreateLoad(local);
4110 auto null =
4111 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
4112 Builder.CreateStore(null, local);
4113 args.add(RValue::get(ptr), type);
4114
4115 // For the most part, we just need to load the alloca, except that
4116 // aggregate r-values are actually pointers to temporaries.
4117 } else {
4118 args.add(convertTempToRValue(local, type, loc), type);
4119 }
4120
4121 // Deactivate the cleanup for the callee-destructed param that was pushed.
4122 if (type->isRecordType() && !CurFuncIsThunk &&
4124 param->needsDestruction(getContext())) {
4126 CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param));
4127 assert(cleanup.isValid() &&
4128 "cleanup for callee-destructed param not recorded");
4129 // This unreachable is a temporary marker which will be removed later.
4130 llvm::Instruction *isActive = Builder.CreateUnreachable();
4131 args.addArgCleanupDeactivation(cleanup, isActive);
4132 }
4133}
4134
4135static bool isProvablyNull(llvm::Value *addr) {
4136 return llvm::isa_and_nonnull<llvm::ConstantPointerNull>(addr);
4137}
4138
4140 return llvm::isKnownNonZero(Addr.getBasePointer(), CGF.CGM.getDataLayout());
4141}
4142
4143/// Emit the actual writing-back of a writeback.
4145 const CallArgList::Writeback &writeback) {
4146 const LValue &srcLV = writeback.Source;
4147 Address srcAddr = srcLV.getAddress();
4148 assert(!isProvablyNull(srcAddr.getBasePointer()) &&
4149 "shouldn't have writeback for provably null argument");
4150
4151 llvm::BasicBlock *contBB = nullptr;
4152
4153 // If the argument wasn't provably non-null, we need to null check
4154 // before doing the store.
4155 bool provablyNonNull = isProvablyNonNull(srcAddr, CGF);
4156
4157 if (!provablyNonNull) {
4158 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
4159 contBB = CGF.createBasicBlock("icr.done");
4160
4161 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
4162 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
4163 CGF.EmitBlock(writebackBB);
4164 }
4165
4166 // Load the value to writeback.
4167 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
4168
4169 // Cast it back, in case we're writing an id to a Foo* or something.
4170 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
4171 "icr.writeback-cast");
4172
4173 // Perform the writeback.
4174
4175 // If we have a "to use" value, it's something we need to emit a use
4176 // of. This has to be carefully threaded in: if it's done after the
4177 // release it's potentially undefined behavior (and the optimizer
4178 // will ignore it), and if it happens before the retain then the
4179 // optimizer could move the release there.
4180 if (writeback.ToUse) {
4181 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
4182
4183 // Retain the new value. No need to block-copy here: the block's
4184 // being passed up the stack.
4185 value = CGF.EmitARCRetainNonBlock(value);
4186
4187 // Emit the intrinsic use here.
4188 CGF.EmitARCIntrinsicUse(writeback.ToUse);
4189
4190 // Load the old value (primitively).
4191 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
4192
4193 // Put the new value in place (primitively).
4194 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
4195
4196 // Release the old value.
4197 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
4198
4199 // Otherwise, we can just do a normal lvalue store.
4200 } else {
4201 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
4202 }
4203
4204 // Jump to the continuation block.
4205 if (!provablyNonNull)
4206 CGF.EmitBlock(contBB);
4207}
4208
4210 const CallArgList &args) {
4211 for (const auto &I : args.writebacks())
4212 emitWriteback(CGF, I);
4213}
4214
4216 const CallArgList &CallArgs) {
4218 CallArgs.getCleanupsToDeactivate();
4219 // Iterate in reverse to increase the likelihood of popping the cleanup.
4220 for (const auto &I : llvm::reverse(Cleanups)) {
4221 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
4222 I.IsActiveIP->eraseFromParent();
4223 }
4224}
4225
4226static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
4227 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
4228 if (uop->getOpcode() == UO_AddrOf)
4229 return uop->getSubExpr();
4230 return nullptr;
4231}
4232
4233/// Emit an argument that's being passed call-by-writeback. That is,
4234/// we are passing the address of an __autoreleased temporary; it
4235/// might be copy-initialized with the current value of the given
4236/// address, but it will definitely be copied out of after the call.
4238 const ObjCIndirectCopyRestoreExpr *CRE) {
4239 LValue srcLV;
4240
4241 // Make an optimistic effort to emit the address as an l-value.
4242 // This can fail if the argument expression is more complicated.
4243 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
4244 srcLV = CGF.EmitLValue(lvExpr);
4245
4246 // Otherwise, just emit it as a scalar.
4247 } else {
4248 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
4249
4250 QualType srcAddrType =
4252 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
4253 }
4254 Address srcAddr = srcLV.getAddress();
4255
4256 // The dest and src types don't necessarily match in LLVM terms
4257 // because of the crazy ObjC compatibility rules.
4258
4259 llvm::PointerType *destType =
4260 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
4261 llvm::Type *destElemType =
4263
4264 // If the address is a constant null, just pass the appropriate null.
4265 if (isProvablyNull(srcAddr.getBasePointer())) {
4266 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
4267 CRE->getType());
4268 return;
4269 }
4270
4271 // Create the temporary.
4272 Address temp =
4273 CGF.CreateTempAlloca(destElemType, CGF.getPointerAlign(), "icr.temp");
4274 // Loading an l-value can introduce a cleanup if the l-value is __weak,
4275 // and that cleanup will be conditional if we can't prove that the l-value
4276 // isn't null, so we need to register a dominating point so that the cleanups
4277 // system will make valid IR.
4278 CodeGenFunction::ConditionalEvaluation condEval(CGF);
4279
4280 // Zero-initialize it if we're not doing a copy-initialization.
4281 bool shouldCopy = CRE->shouldCopy();
4282 if (!shouldCopy) {
4283 llvm::Value *null =
4284 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(destElemType));
4285 CGF.Builder.CreateStore(null, temp);
4286 }
4287
4288 llvm::BasicBlock *contBB = nullptr;
4289 llvm::BasicBlock *originBB = nullptr;
4290
4291 // If the address is *not* known to be non-null, we need to switch.
4292 llvm::Value *finalArgument;
4293
4294 bool provablyNonNull = isProvablyNonNull(srcAddr, CGF);
4295
4296 if (provablyNonNull) {
4297 finalArgument = temp.emitRawPointer(CGF);
4298 } else {
4299 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
4300
4301 finalArgument = CGF.Builder.CreateSelect(
4302 isNull, llvm::ConstantPointerNull::get(destType),
4303 temp.emitRawPointer(CGF), "icr.argument");
4304
4305 // If we need to copy, then the load has to be conditional, which
4306 // means we need control flow.
4307 if (shouldCopy) {
4308 originBB = CGF.Builder.GetInsertBlock();
4309 contBB = CGF.createBasicBlock("icr.cont");
4310 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
4311 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
4312 CGF.EmitBlock(copyBB);
4313 condEval.begin(CGF);
4314 }
4315 }
4316
4317 llvm::Value *valueToUse = nullptr;
4318
4319 // Perform a copy if necessary.
4320 if (shouldCopy) {
4321 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
4322 assert(srcRV.isScalar());
4323
4324 llvm::Value *src = srcRV.getScalarVal();
4325 src = CGF.Builder.CreateBitCast(src, destElemType, "icr.cast");
4326
4327 // Use an ordinary store, not a store-to-lvalue.
4328 CGF.Builder.CreateStore(src, temp);
4329
4330 // If optimization is enabled, and the value was held in a
4331 // __strong variable, we need to tell the optimizer that this
4332 // value has to stay alive until we're doing the store back.
4333 // This is because the temporary is effectively unretained,
4334 // and so otherwise we can violate the high-level semantics.
4335 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
4337 valueToUse = src;
4338 }
4339 }
4340
4341 // Finish the control flow if we needed it.
4342 if (shouldCopy && !provablyNonNull) {
4343 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
4344 CGF.EmitBlock(contBB);
4345
4346 // Make a phi for the value to intrinsically use.
4347 if (valueToUse) {
4348 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
4349 "icr.to-use");
4350 phiToUse->addIncoming(valueToUse, copyBB);
4351 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
4352 originBB);
4353 valueToUse = phiToUse;
4354 }
4355
4356 condEval.end(CGF);
4357 }
4358
4359 args.addWriteback(srcLV, temp, valueToUse);
4360 args.add(RValue::get(finalArgument), CRE->getType());
4361}
4362
4364 assert(!StackBase);
4365
4366 // Save the stack.
4367 StackBase = CGF.Builder.CreateStackSave("inalloca.save");
4368}
4369
4371 if (StackBase) {
4372 // Restore the stack after the call.
4373 CGF.Builder.CreateStackRestore(StackBase);
4374 }
4375}
4376
4378 SourceLocation ArgLoc,
4379 AbstractCallee AC,
4380 unsigned ParmNum) {
4381 if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
4382 SanOpts.has(SanitizerKind::NullabilityArg)))
4383 return;
4384
4385 // The param decl may be missing in a variadic function.
4386 auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr;
4387 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
4388
4389 // Prefer the nonnull attribute if it's present.
4390 const NonNullAttr *NNAttr = nullptr;
4391 if (SanOpts.has(SanitizerKind::NonnullAttribute))
4392 NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
4393
4394 bool CanCheckNullability = false;
4395 if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD &&
4396 !PVD->getType()->isRecordType()) {
4397 auto Nullability = PVD->getType()->getNullability();
4398 CanCheckNullability = Nullability &&
4399 *Nullability == NullabilityKind::NonNull &&
4400 PVD->getTypeSourceInfo();
4401 }
4402
4403 if (!NNAttr && !CanCheckNullability)
4404 return;
4405
4406 SourceLocation AttrLoc;
4407 SanitizerMask CheckKind;
4408 SanitizerHandler Handler;
4409 if (NNAttr) {
4410 AttrLoc = NNAttr->getLocation();
4411 CheckKind = SanitizerKind::NonnullAttribute;
4412 Handler = SanitizerHandler::NonnullArg;
4413 } else {
4414 AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
4415 CheckKind = SanitizerKind::NullabilityArg;
4416 Handler = SanitizerHandler::NullabilityArg;
4417 }
4418
4419 SanitizerScope SanScope(this);
4420 llvm::Value *Cond = EmitNonNullRValueCheck(RV, ArgType);
4421 llvm::Constant *StaticData[] = {
4423 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
4424 };
4425 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, std::nullopt);
4426}
4427
4429 SourceLocation ArgLoc,
4430 AbstractCallee AC, unsigned ParmNum) {
4431 if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
4432 SanOpts.has(SanitizerKind::NullabilityArg)))
4433 return;
4434
4435 EmitNonNullArgCheck(RValue::get(Addr, *this), ArgType, ArgLoc, AC, ParmNum);
4436}
4437
4438// Check if the call is going to use the inalloca convention. This needs to
4439// agree with CGFunctionInfo::usesInAlloca. The CGFunctionInfo is arranged
4440// later, so we can't check it directly.
4441static bool hasInAllocaArgs(CodeGenModule &CGM, CallingConv ExplicitCC,
4442 ArrayRef<QualType> ArgTypes) {
4443 // The Swift calling conventions don't go through the target-specific
4444 // argument classification, they never use inalloca.
4445 // TODO: Consider limiting inalloca use to only calling conventions supported
4446 // by MSVC.
4447 if (ExplicitCC == CC_Swift || ExplicitCC == CC_SwiftAsync)
4448 return false;
4449 if (!CGM.getTarget().getCXXABI().isMicrosoft())
4450 return false;
4451 return llvm::any_of(ArgTypes, [&](QualType Ty) {
4452 return isInAllocaArgument(CGM.getCXXABI(), Ty);
4453 });
4454}
4455
4456#ifndef NDEBUG
4457// Determine whether the given argument is an Objective-C method
4458// that may have type parameters in its signature.
4459static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
4460 const DeclContext *dc = method->getDeclContext();
4461 if (const ObjCInterfaceDecl *classDecl = dyn_cast<ObjCInterfaceDecl>(dc)) {
4462 return classDecl->getTypeParamListAsWritten();
4463 }
4464
4465 if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
4466 return catDecl->getTypeParamList();
4467 }
4468
4469 return false;
4470}
4471#endif
4472
4473/// EmitCallArgs - Emit call arguments for a function.
4475 CallArgList &Args, PrototypeWrapper Prototype,
4476 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
4477 AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
4479
4480 assert((ParamsToSkip == 0 || Prototype.P) &&
4481 "Can't skip parameters if type info is not provided");
4482
4483 // This variable only captures *explicitly* written conventions, not those
4484 // applied by default via command line flags or target defaults, such as
4485 // thiscall, aapcs, stdcall via -mrtd, etc. Computing that correctly would
4486 // require knowing if this is a C++ instance method or being able to see
4487 // unprototyped FunctionTypes.
4488 CallingConv ExplicitCC = CC_C;
4489
4490 // First, if a prototype was provided, use those argument types.
4491 bool IsVariadic = false;
4492 if (Prototype.P) {
4493 const auto *MD = Prototype.P.dyn_cast<const ObjCMethodDecl *>();
4494 if (MD) {
4495 IsVariadic = MD->isVariadic();
4496 ExplicitCC = getCallingConventionForDecl(
4497 MD, CGM.getTarget().getTriple().isOSWindows());
4498 ArgTypes.assign(MD->param_type_begin() + ParamsToSkip,
4499 MD->param_type_end());
4500 } else {
4501 const auto *FPT = Prototype.P.get<const FunctionProtoType *>();
4502 IsVariadic = FPT->isVariadic();
4503 ExplicitCC = FPT->getExtInfo().getCC();
4504 ArgTypes.assign(FPT->param_type_begin() + ParamsToSkip,
4505 FPT->param_type_end());
4506 }
4507
4508#ifndef NDEBUG
4509 // Check that the prototyped types match the argument expression types.
4510 bool isGenericMethod = MD && isObjCMethodWithTypeParams(MD);
4511 CallExpr::const_arg_iterator Arg = ArgRange.begin();
4512 for (QualType Ty : ArgTypes) {
4513 assert(Arg != ArgRange.end() && "Running over edge of argument list!");
4514 assert(
4515 (isGenericMethod || Ty->isVariablyModifiedType() ||
4516 Ty.getNonReferenceType()->isObjCRetainableType() ||
4517 getContext()
4518 .getCanonicalType(Ty.getNonReferenceType())
4519 .getTypePtr() ==
4520 getContext().getCanonicalType((*Arg)->getType()).getTypePtr()) &&
4521 "type mismatch in call argument!");
4522 ++Arg;
4523 }
4524
4525 // Either we've emitted all the call args, or we have a call to variadic
4526 // function.
4527 assert((Arg == ArgRange.end() || IsVariadic) &&
4528 "Extra arguments in non-variadic function!");
4529#endif
4530 }
4531
4532 // If we still have any arguments, emit them using the type of the argument.
4533 for (auto *A : llvm::drop_begin(ArgRange, ArgTypes.size()))
4534 ArgTypes.push_back(IsVariadic ? getVarArgType(A) : A->getType());
4535 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
4536
4537 // We must evaluate arguments from right to left in the MS C++ ABI,
4538 // because arguments are destroyed left to right in the callee. As a special
4539 // case, there are certain language constructs that require left-to-right
4540 // evaluation, and in those cases we consider the evaluation order requirement
4541 // to trump the "destruction order is reverse construction order" guarantee.
4542 bool LeftToRight =
4546
4547 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
4548 RValue EmittedArg) {
4549 if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
4550 return;
4551 auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
4552 if (PS == nullptr)
4553 return;
4554
4555 const auto &Context = getContext();
4556 auto SizeTy = Context.getSizeType();
4557 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
4558 assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?");
4559 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
4560 EmittedArg.getScalarVal(),
4561 PS->isDynamic());
4562 Args.add(RValue::get(V), SizeTy);
4563 // If we're emitting args in reverse, be sure to do so with
4564 // pass_object_size, as well.
4565 if (!LeftToRight)
4566 std::swap(Args.back(), *(&Args.back() - 1));
4567 };
4568
4569 // Insert a stack save if we're going to need any inalloca args.
4570 if (hasInAllocaArgs(CGM, ExplicitCC, ArgTypes)) {
4571 assert(getTarget().getTriple().getArch() == llvm::Triple::x86 &&
4572 "inalloca only supported on x86");
4573 Args.allocateArgumentMemory(*this);
4574 }
4575
4576 // Evaluate each argument in the appropriate order.
4577 size_t CallArgsStart = Args.size();
4578 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
4579 unsigned Idx = LeftToRight ? I : E - I - 1;
4580 CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
4581 unsigned InitialArgSize = Args.size();
4582 // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of
4583 // the argument and parameter match or the objc method is parameterized.
4584 assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) ||
4585 getContext().hasSameUnqualifiedType((*Arg)->getType(),
4586 ArgTypes[Idx]) ||
4587 (isa<ObjCMethodDecl>(AC.getDecl()) &&
4588 isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) &&
4589 "Argument and parameter types don't match");
4590 EmitCallArg(Args, *Arg, ArgTypes[Idx]);
4591 // In particular, we depend on it being the last arg in Args, and the
4592 // objectsize bits depend on there only being one arg if !LeftToRight.
4593 assert(InitialArgSize + 1 == Args.size() &&
4594 "The code below depends on only adding one arg per EmitCallArg");
4595 (void)InitialArgSize;
4596 // Since pointer argument are never emitted as LValue, it is safe to emit
4597 // non-null argument check for r-value only.
4598 if (!Args.back().hasLValue()) {
4599 RValue RVArg = Args.back().getKnownRValue();
4600 EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
4601 ParamsToSkip + Idx);
4602 // @llvm.objectsize should never have side-effects and shouldn't need
4603 // destruction/cleanups, so we can safely "emit" it after its arg,
4604 // regardless of right-to-leftness
4605 MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
4606 }
4607 }
4608
4609 if (!LeftToRight) {
4610 // Un-reverse the arguments we just evaluated so they match up with the LLVM
4611 // IR function.
4612 std::reverse(Args.begin() + CallArgsStart, Args.end());
4613 }
4614}
4615
4616namespace {
4617
4618struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
4619 DestroyUnpassedArg(Address Addr, QualType Ty)
4620 : Addr(Addr), Ty(Ty) {}
4621
4622 Address Addr;
4623 QualType Ty;
4624
4625 void Emit(CodeGenFunction &CGF, Flags flags) override {
4627 if (DtorKind == QualType::DK_cxx_destructor) {
4628 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
4629 assert(!Dtor->isTrivial());
4630 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
4631 /*Delegating=*/false, Addr, Ty);
4632 } else {
4633 CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty));
4634 }
4635 }
4636};
4637
4638struct DisableDebugLocationUpdates {
4639 CodeGenFunction &CGF;
4640 bool disabledDebugInfo;
4641 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
4642 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
4643 CGF.disableDebugInfo();
4644 }
4645 ~DisableDebugLocationUpdates() {
4646 if (disabledDebugInfo)
4647 CGF.enableDebugInfo();
4648 }
4649};
4650
4651} // end anonymous namespace
4652
4654 if (!HasLV)
4655 return RV;
4658 LV.isVolatile());
4659 IsUsed = true;
4660 return RValue::getAggregate(Copy.getAddress());
4661}
4662
4664 LValue Dst = CGF.MakeAddrLValue(Addr, Ty);
4665 if (!HasLV && RV.isScalar())
4666 CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*isInit=*/true);
4667 else if (!HasLV && RV.isComplex())
4668 CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true);
4669 else {
4670 auto Addr = HasLV ? LV.getAddress() : RV.getAggregateAddress();
4671 LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty);
4672 // We assume that call args are never copied into subobjects.
4674 HasLV ? LV.isVolatileQualified()
4676 }
4677 IsUsed = true;
4678}
4679
4681 QualType type) {
4682 DisableDebugLocationUpdates Dis(*this, E);
4683 if (const ObjCIndirectCopyRestoreExpr *CRE
4684 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
4685 assert(getLangOpts().ObjCAutoRefCount);
4686 return emitWritebackArg(*this, args, CRE);
4687 }
4688
4689 assert(type->isReferenceType() == E->isGLValue() &&
4690 "reference binding to unmaterialized r-value!");
4691
4692 if (E->isGLValue()) {
4693 assert(E->getObjectKind() == OK_Ordinary);
4694 return args.add(EmitReferenceBindingToExpr(E), type);
4695 }
4696
4697 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
4698
4699 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
4700 // However, we still have to push an EH-only cleanup in case we unwind before
4701 // we make it to the call.
4702 if (type->isRecordType() &&
4704 // If we're using inalloca, use the argument memory. Otherwise, use a
4705 // temporary.
4706 AggValueSlot Slot = args.isUsingInAlloca()
4707 ? createPlaceholderSlot(*this, type) : CreateAggTemp(type, "agg.tmp");
4708
4709 bool DestroyedInCallee = true, NeedsCleanup = true;
4710 if (const auto *RD = type->getAsCXXRecordDecl())
4711 DestroyedInCallee = RD->hasNonTrivialDestructor();
4712 else
4713 NeedsCleanup = type.isDestructedType();
4714
4715 if (DestroyedInCallee)
4717
4718 EmitAggExpr(E, Slot);
4719 RValue RV = Slot.asRValue();
4720 args.add(RV, type);
4721
4722 if (DestroyedInCallee && NeedsCleanup) {
4723 // Create a no-op GEP between the placeholder and the cleanup so we can
4724 // RAUW it successfully. It also serves as a marker of the first
4725 // instruction where the cleanup is active.
4726 pushFullExprCleanup<DestroyUnpassedArg>(NormalAndEHCleanup,
4727 Slot.getAddress(), type);
4728 // This unreachable is a temporary marker which will be removed later.
4729 llvm::Instruction *IsActive =
4730 Builder.CreateFlagLoad(llvm::Constant::getNullValue(Int8PtrTy));
4732 }
4733 return;
4734 }
4735
4736 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
4737 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue &&
4738 !type->isArrayParameterType()) {
4739 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
4740 assert(L.isSimple());
4741 args.addUncopiedAggregate(L, type);
4742 return;
4743 }
4744
4745 args.add(EmitAnyExprToTemp(E), type);
4746}
4747
4748QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
4749 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
4750 // implicitly widens null pointer constants that are arguments to varargs
4751 // functions to pointer-sized ints.
4752 if (!getTarget().getTriple().isOSWindows())
4753 return Arg->getType();
4754
4755 if (Arg->getType()->isIntegerType() &&
4756 getContext().getTypeSize(Arg->getType()) <
4757 getContext().getTargetInfo().getPointerWidth(LangAS::Default) &&
4760 return getContext().getIntPtrType();
4761 }
4762
4763 return Arg->getType();
4764}
4765
4766// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4767// optimizer it can aggressively ignore unwind edges.
4768void
4769CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
4770 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
4771 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
4772 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
4774}
4775
4776/// Emits a call to the given no-arguments nounwind runtime function.
4777llvm::CallInst *
4778CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4779 const llvm::Twine &name) {
4780 return EmitNounwindRuntimeCall(callee, ArrayRef<llvm::Value *>(), name);
4781}
4782
4783/// Emits a call to the given nounwind runtime function.
4784llvm::CallInst *
4785CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4786 ArrayRef<Address> args,
4787 const llvm::Twine &name) {
4789 for (auto arg : args)
4790 values.push_back(arg.emitRawPointer(*this));
4791 return EmitNounwindRuntimeCall(callee, values, name);
4792}
4793
4794llvm::CallInst *
4795CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4797 const llvm::Twine &name) {
4798 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
4799 call->setDoesNotThrow();
4800 return call;
4801}
4802
4803/// Emits a simple call (never an invoke) to the given no-arguments
4804/// runtime function.
4805llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
4806 const llvm::Twine &name) {
4807 return EmitRuntimeCall(callee, std::nullopt, name);
4808}
4809
4810// Calls which may throw must have operand bundles indicating which funclet
4811// they are nested within.
4813CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) {
4814 // There is no need for a funclet operand bundle if we aren't inside a
4815 // funclet.
4816 if (!CurrentFuncletPad)
4818
4819 // Skip intrinsics which cannot throw (as long as they don't lower into
4820 // regular function calls in the course of IR transformations).
4821 if (auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts())) {
4822 if (CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow()) {
4823 auto IID = CalleeFn->getIntrinsicID();
4824 if (!llvm::IntrinsicInst::mayLowerToFunctionCall(IID))
4826 }
4827 }
4828
4830 BundleList.emplace_back("funclet", CurrentFuncletPad);
4831 return BundleList;
4832}
4833
4834/// Emits a simple call (never an invoke) to the given runtime function.
4835llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
4837 const llvm::Twine &name) {
4838 llvm::CallInst *call = Builder.CreateCall(
4839 callee, args, getBundlesForFunclet(callee.getCallee()), name);
4840 call->setCallingConv(getRuntimeCC());
4841
4842 if (CGM.shouldEmitConvergenceTokens() && call->isConvergent())
4843 return addControlledConvergenceToken(call);
4844 return call;
4845}
4846
4847/// Emits a call or invoke to the given noreturn runtime function.
4849 llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) {
4851 getBundlesForFunclet(callee.getCallee());
4852
4853 if (getInvokeDest()) {
4854 llvm::InvokeInst *invoke =
4855 Builder.CreateInvoke(callee,
4857 getInvokeDest(),
4858 args,
4859 BundleList);
4860 invoke->setDoesNotReturn();
4861 invoke->setCallingConv(getRuntimeCC());
4862 } else {
4863 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
4864 call->setDoesNotReturn();
4865 call->setCallingConv(getRuntimeCC());
4866 Builder.CreateUnreachable();
4867 }
4868}
4869
4870/// Emits a call or invoke instruction to the given nullary runtime function.
4871llvm::CallBase *
4872CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4873 const Twine &name) {
4874 return EmitRuntimeCallOrInvoke(callee, std::nullopt, name);
4875}
4876
4877/// Emits a call or invoke instruction to the given runtime function.
4878llvm::CallBase *
4879CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4881 const Twine &name) {
4882 llvm::CallBase *call = EmitCallOrInvoke(callee, args, name);
4883 call->setCallingConv(getRuntimeCC());
4884 return call;
4885}
4886
4887/// Emits a call or invoke instruction to the given function, depending
4888/// on the current state of the EH stack.
4889llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee,
4891 const Twine &Name) {
4892 llvm::BasicBlock *InvokeDest = getInvokeDest();
4894 getBundlesForFunclet(Callee.getCallee());
4895
4896 llvm::CallBase *Inst;
4897 if (!InvokeDest)
4898 Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
4899 else {
4900 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
4901 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
4902 Name);
4903 EmitBlock(ContBB);
4904 }
4905
4906 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4907 // optimizer it can aggressively ignore unwind edges.
4908 if (CGM.getLangOpts().ObjCAutoRefCount)
4909 AddObjCARCExceptionMetadata(Inst);
4910
4911 return Inst;
4912}
4913
4914void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
4915 llvm::Value *New) {
4916 DeferredReplacements.push_back(
4917 std::make_pair(llvm::WeakTrackingVH(Old), New));
4918}
4919
4920namespace {
4921
4922/// Specify given \p NewAlign as the alignment of return value attribute. If
4923/// such attribute already exists, re-set it to the maximal one of two options.
4924[[nodiscard]] llvm::AttributeList
4925maybeRaiseRetAlignmentAttribute(llvm::LLVMContext &Ctx,
4926 const llvm::AttributeList &Attrs,
4927 llvm::Align NewAlign) {
4928 llvm::Align CurAlign = Attrs.getRetAlignment().valueOrOne();
4929 if (CurAlign >= NewAlign)
4930 return Attrs;
4931 llvm::Attribute AlignAttr = llvm::Attribute::getWithAlignment(Ctx, NewAlign);
4932 return Attrs.removeRetAttribute(Ctx, llvm::Attribute::AttrKind::Alignment)
4933 .addRetAttribute(Ctx, AlignAttr);
4934}
4935
4936template <typename AlignedAttrTy> class AbstractAssumeAlignedAttrEmitter {
4937protected:
4938 CodeGenFunction &CGF;
4939
4940 /// We do nothing if this is, or becomes, nullptr.
4941 const AlignedAttrTy *AA = nullptr;
4942
4943 llvm::Value *Alignment = nullptr; // May or may not be a constant.
4944 llvm::ConstantInt *OffsetCI = nullptr; // Constant, hopefully zero.
4945
4946 AbstractAssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
4947 : CGF(CGF_) {
4948 if (!FuncDecl)
4949 return;
4950 AA = FuncDecl->getAttr<AlignedAttrTy>();
4951 }
4952
4953public:
4954 /// If we can, materialize the alignment as an attribute on return value.
4955 [[nodiscard]] llvm::AttributeList
4956 TryEmitAsCallSiteAttribute(const llvm::AttributeList &Attrs) {
4957 if (!AA || OffsetCI || CGF.SanOpts.has(SanitizerKind::Alignment))
4958 return Attrs;
4959 const auto *AlignmentCI = dyn_cast<llvm::ConstantInt>(Alignment);
4960 if (!AlignmentCI)
4961 return Attrs;
4962 // We may legitimately have non-power-of-2 alignment here.
4963 // If so, this is UB land, emit it via `@llvm.assume` instead.
4964 if (!AlignmentCI->getValue().isPowerOf2())
4965 return Attrs;
4966 llvm::AttributeList NewAttrs = maybeRaiseRetAlignmentAttribute(
4967 CGF.getLLVMContext(), Attrs,
4968 llvm::Align(
4969 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment)));
4970 AA = nullptr; // We're done. Disallow doing anything else.
4971 return NewAttrs;
4972 }
4973
4974 /// Emit alignment assumption.
4975 /// This is a general fallback that we take if either there is an offset,
4976 /// or the alignment is variable or we are sanitizing for alignment.
4977 void EmitAsAnAssumption(SourceLocation Loc, QualType RetTy, RValue &Ret) {
4978 if (!AA)
4979 return;
4980 CGF.emitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc,
4981 AA->getLocation(), Alignment, OffsetCI);
4982 AA = nullptr; // We're done. Disallow doing anything else.
4983 }
4984};
4985
4986/// Helper data structure to emit `AssumeAlignedAttr`.
4987class AssumeAlignedAttrEmitter final
4988 : public AbstractAssumeAlignedAttrEmitter<AssumeAlignedAttr> {
4989public:
4990 AssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
4991 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
4992 if (!AA)
4993 return;
4994 // It is guaranteed that the alignment/offset are constants.
4995 Alignment = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AA->getAlignment()));
4996 if (Expr *Offset = AA->getOffset()) {
4997 OffsetCI = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(Offset));
4998 if (OffsetCI->isNullValue()) // Canonicalize zero offset to no offset.
4999 OffsetCI = nullptr;
5000 }
5001 }
5002};
5003
5004/// Helper data structure to emit `AllocAlignAttr`.
5005class AllocAlignAttrEmitter final
5006 : public AbstractAssumeAlignedAttrEmitter<AllocAlignAttr> {
5007public:
5008 AllocAlignAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl,
5009 const CallArgList &CallArgs)
5010 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
5011 if (!AA)
5012 return;
5013 // Alignment may or may not be a constant, and that is okay.
5014 Alignment = CallArgs[AA->getParamIndex().getLLVMIndex()]
5015 .getRValue(CGF)
5016 .getScalarVal();
5017 }
5018};
5019
5020} // namespace
5021
5022static unsigned getMaxVectorWidth(const llvm::Type *Ty) {
5023 if (auto *VT = dyn_cast<llvm::VectorType>(Ty))
5024 return VT->getPrimitiveSizeInBits().getKnownMinValue();
5025 if (auto *AT = dyn_cast<llvm::ArrayType>(Ty))
5026 return getMaxVectorWidth(AT->getElementType());
5027
5028 unsigned MaxVectorWidth = 0;
5029 if (auto *ST = dyn_cast<llvm::StructType>(Ty))
5030 for (auto *I : ST->elements())
5031 MaxVectorWidth = std::max(MaxVectorWidth, getMaxVectorWidth(I));
5032 return MaxVectorWidth;
5033}
5034
5036 const CGCallee &Callee,
5037 ReturnValueSlot ReturnValue,
5038 const CallArgList &CallArgs,
5039 llvm::CallBase **callOrInvoke, bool IsMustTail,
5041 bool IsVirtualFunctionPointerThunk) {
5042 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
5043
5044 assert(Callee.isOrdinary() || Callee.isVirtual());
5045
5046 // Handle struct-return functions by passing a pointer to the
5047 // location that we would like to return into.
5048 QualType RetTy = CallInfo.getReturnType();
5049 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
5050
5051 llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
5052
5053 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
5054 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
5055 // We can only guarantee that a function is called from the correct
5056 // context/function based on the appropriate target attributes,
5057 // so only check in the case where we have both always_inline and target
5058 // since otherwise we could be making a conditional call after a check for
5059 // the proper cpu features (and it won't cause code generation issues due to
5060 // function based code generation).
5061 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
5062 (TargetDecl->hasAttr<TargetAttr>() ||
5063 (CurFuncDecl && CurFuncDecl->hasAttr<TargetAttr>())))
5065 }
5066
5067 // Some architectures (such as x86-64) have the ABI changed based on
5068 // attribute-target/features. Give them a chance to diagnose.
5070 CGM, Loc, dyn_cast_or_null<FunctionDecl>(CurCodeDecl),
5071 dyn_cast_or_null<FunctionDecl>(TargetDecl), CallArgs, RetTy);
5072
5073 // 1. Set up the arguments.
5074
5075 // If we're using inalloca, insert the allocation after the stack save.
5076 // FIXME: Do this earlier rather than hacking it in here!
5077 RawAddress ArgMemory = RawAddress::invalid();
5078 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
5079 const llvm::DataLayout &DL = CGM.getDataLayout();
5080 llvm::Instruction *IP = CallArgs.getStackBase();
5081 llvm::AllocaInst *AI;
5082 if (IP) {
5083 IP = IP->getNextNode();
5084 AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(),
5085 "argmem", IP);
5086 } else {
5087 AI = CreateTempAlloca(ArgStruct, "argmem");
5088 }
5089 auto Align = CallInfo.getArgStructAlignment();
5090 AI->setAlignment(Align.getAsAlign());
5091 AI->setUsedWithInAlloca(true);
5092 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
5093 ArgMemory = RawAddress(AI, ArgStruct, Align);
5094 }
5095
5096 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
5097 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
5098
5099 // If the call returns a temporary with struct return, create a temporary
5100 // alloca to hold the result, unless one is given to us.
5101 Address SRetPtr = Address::invalid();
5102 RawAddress SRetAlloca = RawAddress::invalid();
5103 llvm::Value *UnusedReturnSizePtr = nullptr;
5104 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
5105 if (IsVirtualFunctionPointerThunk && RetAI.isIndirect()) {
5106 SRetPtr = makeNaturalAddressForPointer(CurFn->arg_begin() +
5107 IRFunctionArgs.getSRetArgNo(),
5108 RetTy, CharUnits::fromQuantity(1));
5109 } else if (!ReturnValue.isNull()) {
5110 SRetPtr = ReturnValue.getAddress();
5111 } else {
5112 SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca);
5113 if (HaveInsertPoint() && ReturnValue.isUnused()) {
5114 llvm::TypeSize size =
5115 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
5116 UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer());
5117 }
5118 }
5119 if (IRFunctionArgs.hasSRetArg()) {
5120 IRCallArgs[IRFunctionArgs.getSRetArgNo()] =
5121 getAsNaturalPointerTo(SRetPtr, RetTy);
5122 } else if (RetAI.isInAlloca()) {
5123 Address Addr =
5124 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
5125 Builder.CreateStore(getAsNaturalPointerTo(SRetPtr, RetTy), Addr);
5126 }
5127 }
5128
5129 RawAddress swiftErrorTemp = RawAddress::invalid();
5130 Address swiftErrorArg = Address::invalid();
5131
5132 // When passing arguments using temporary allocas, we need to add the
5133 // appropriate lifetime markers. This vector keeps track of all the lifetime
5134 // markers that need to be ended right after the call.
5135 SmallVector<CallLifetimeEnd, 2> CallLifetimeEndAfterCall;
5136
5137 // Translate all of the arguments as necessary to match the IR lowering.
5138 assert(CallInfo.arg_size() == CallArgs.size() &&
5139 "Mismatch between function signature & arguments.");
5140 unsigned ArgNo = 0;
5141 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
5142 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
5143 I != E; ++I, ++info_it, ++ArgNo) {
5144 const ABIArgInfo &ArgInfo = info_it->info;
5145
5146 // Insert a padding argument to ensure proper alignment.
5147 if (IRFunctionArgs.hasPaddingArg(ArgNo))
5148 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
5149 llvm::UndefValue::get(ArgInfo.getPaddingType());
5150
5151 unsigned FirstIRArg, NumIRArgs;
5152 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
5153
5154 bool ArgHasMaybeUndefAttr =
5155 IsArgumentMaybeUndef(TargetDecl, CallInfo.getNumRequiredArgs(), ArgNo);
5156
5157 switch (ArgInfo.getKind()) {
5158 case ABIArgInfo::InAlloca: {
5159 assert(NumIRArgs == 0);
5160 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
5161 if (I->isAggregate()) {
5162 RawAddress Addr = I->hasLValue()
5163 ? I->getKnownLValue().getAddress()
5164 : I->getKnownRValue().getAggregateAddress();
5165 llvm::Instruction *Placeholder =
5166 cast<llvm::Instruction>(Addr.getPointer());
5167
5168 if (!ArgInfo.getInAllocaIndirect()) {
5169 // Replace the placeholder with the appropriate argument slot GEP.
5170 CGBuilderTy::InsertPoint IP = Builder.saveIP();
5171 Builder.SetInsertPoint(Placeholder);
5172 Addr = Builder.CreateStructGEP(ArgMemory,
5173 ArgInfo.getInAllocaFieldIndex());
5174 Builder.restoreIP(IP);
5175 } else {
5176 // For indirect things such as overaligned structs, replace the
5177 // placeholder with a regular aggregate temporary alloca. Store the
5178 // address of this alloca into the struct.
5179 Addr = CreateMemTemp(info_it->type, "inalloca.indirect.tmp");
5181 ArgMemory, ArgInfo.getInAllocaFieldIndex());
5182 Builder.CreateStore(Addr.getPointer(), ArgSlot);
5183 }
5184 deferPlaceholderReplacement(Placeholder, Addr.getPointer());
5185 } else if (ArgInfo.getInAllocaIndirect()) {
5186 // Make a temporary alloca and store the address of it into the argument
5187 // struct.
5189 I->Ty, getContext().getTypeAlignInChars(I->Ty),
5190 "indirect-arg-temp");
5191 I->copyInto(*this, Addr);
5192 Address ArgSlot =
5193 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
5194 Builder.CreateStore(Addr.getPointer(), ArgSlot);
5195 } else {
5196 // Store the RValue into the argument struct.
5197 Address Addr =
5198 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
5199 Addr = Addr.withElementType(ConvertTypeForMem(I->Ty));
5200 I->copyInto(*this, Addr);
5201 }
5202 break;
5203 }
5204
5207 assert(NumIRArgs == 1);
5208 if (I->isAggregate()) {
5209 // We want to avoid creating an unnecessary temporary+copy here;
5210 // however, we need one in three cases:
5211 // 1. If the argument is not byval, and we are required to copy the
5212 // source. (This case doesn't occur on any common architecture.)
5213 // 2. If the argument is byval, RV is not sufficiently aligned, and
5214 // we cannot force it to be sufficiently aligned.
5215 // 3. If the argument is byval, but RV is not located in default
5216 // or alloca address space.
5217 Address Addr = I->hasLValue()
5218 ? I->getKnownLValue().getAddress()
5219 : I->getKnownRValue().getAggregateAddress();
5220 CharUnits Align = ArgInfo.getIndirectAlign();
5221 const llvm::DataLayout *TD = &CGM.getDataLayout();
5222
5223 assert((FirstIRArg >= IRFuncTy->getNumParams() ||
5224 IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() ==
5225 TD->getAllocaAddrSpace()) &&
5226 "indirect argument must be in alloca address space");
5227
5228 bool NeedCopy = false;
5229 if (Addr.getAlignment() < Align &&
5230 llvm::getOrEnforceKnownAlignment(Addr.emitRawPointer(*this),
5231 Align.getAsAlign(),
5232 *TD) < Align.getAsAlign()) {
5233 NeedCopy = true;
5234 } else if (I->hasLValue()) {
5235 auto LV = I->getKnownLValue();
5236 auto AS = LV.getAddressSpace();
5237
5238 bool isByValOrRef =
5239 ArgInfo.isIndirectAliased() || ArgInfo.getIndirectByVal();
5240
5241 if (!isByValOrRef ||
5242 (LV.getAlignment() < getContext().getTypeAlignInChars(I->Ty))) {
5243 NeedCopy = true;
5244 }
5245 if (!getLangOpts().OpenCL) {
5246 if ((isByValOrRef &&
5247 (AS != LangAS::Default &&
5248 AS != CGM.getASTAllocaAddressSpace()))) {
5249 NeedCopy = true;
5250 }
5251 }
5252 // For OpenCL even if RV is located in default or alloca address space
5253 // we don't want to perform address space cast for it.
5254 else if ((isByValOrRef &&
5255 Addr.getType()->getAddressSpace() != IRFuncTy->
5256 getParamType(FirstIRArg)->getPointerAddressSpace())) {
5257 NeedCopy = true;
5258 }
5259 }
5260
5261 if (!NeedCopy) {
5262 // Skip the extra memcpy call.
5263 llvm::Value *V = getAsNaturalPointerTo(Addr, I->Ty);
5264 auto *T = llvm::PointerType::get(
5265 CGM.getLLVMContext(), CGM.getDataLayout().getAllocaAddrSpace());
5266
5267 llvm::Value *Val = getTargetHooks().performAddrSpaceCast(
5269 true);
5270 if (ArgHasMaybeUndefAttr)
5271 Val = Builder.CreateFreeze(Val);
5272 IRCallArgs[FirstIRArg] = Val;
5273 break;
5274 }
5275 }
5276
5277 // For non-aggregate args and aggregate args meeting conditions above
5278 // we need to create an aligned temporary, and copy to it.
5280 I->Ty, ArgInfo.getIndirectAlign(), "byval-temp");
5281 llvm::Value *Val = getAsNaturalPointerTo(AI, I->Ty);
5282 if (ArgHasMaybeUndefAttr)
5283 Val = Builder.CreateFreeze(Val);
5284 IRCallArgs[FirstIRArg] = Val;
5285
5286 // Emit lifetime markers for the temporary alloca.
5287 llvm::TypeSize ByvalTempElementSize =
5288 CGM.getDataLayout().getTypeAllocSize(AI.getElementType());
5289 llvm::Value *LifetimeSize =
5290 EmitLifetimeStart(ByvalTempElementSize, AI.getPointer());
5291
5292 // Add cleanup code to emit the end lifetime marker after the call.
5293 if (LifetimeSize) // In case we disabled lifetime markers.
5294 CallLifetimeEndAfterCall.emplace_back(AI, LifetimeSize);
5295
5296 // Generate the copy.
5297 I->copyInto(*this, AI);
5298 break;
5299 }
5300
5301 case ABIArgInfo::Ignore:
5302 assert(NumIRArgs == 0);
5303 break;
5304
5305 case ABIArgInfo::Extend:
5306 case ABIArgInfo::Direct: {
5307 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
5308 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
5309 ArgInfo.getDirectOffset() == 0) {
5310 assert(NumIRArgs == 1);
5311 llvm::Value *V;
5312 if (!I->isAggregate())
5313 V = I->getKnownRValue().getScalarVal();
5314 else
5316 I->hasLValue() ? I->getKnownLValue().getAddress()
5317 : I->getKnownRValue().getAggregateAddress());
5318
5319 // Implement swifterror by copying into a new swifterror argument.
5320 // We'll write back in the normal path out of the call.
5321 if (CallInfo.getExtParameterInfo(ArgNo).getABI()
5323 assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
5324
5325 QualType pointeeTy = I->Ty->getPointeeType();
5326 swiftErrorArg = makeNaturalAddressForPointer(
5327 V, pointeeTy, getContext().getTypeAlignInChars(pointeeTy));
5328
5329 swiftErrorTemp =
5330 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
5331 V = swiftErrorTemp.getPointer();
5332 cast<llvm::AllocaInst>(V)->setSwiftError(true);
5333
5334 llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
5335 Builder.CreateStore(errorValue, swiftErrorTemp);
5336 }
5337
5338 // We might have to widen integers, but we should never truncate.
5339 if (ArgInfo.getCoerceToType() != V->getType() &&
5340 V->getType()->isIntegerTy())
5341 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
5342
5343 // If the argument doesn't match, perform a bitcast to coerce it. This
5344 // can happen due to trivial type mismatches.
5345 if (FirstIRArg < IRFuncTy->getNumParams() &&
5346 V->getType() != IRFuncTy->getParamType(FirstIRArg))
5347 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
5348
5349 if (ArgHasMaybeUndefAttr)
5350 V = Builder.CreateFreeze(V);
5351 IRCallArgs[FirstIRArg] = V;
5352 break;
5353 }
5354
5355 llvm::StructType *STy =
5356 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
5357 if (STy && ArgInfo.isDirect() && !ArgInfo.getCanBeFlattened()) {
5358 llvm::Type *SrcTy = ConvertTypeForMem(I->Ty);
5359 [[maybe_unused]] llvm::TypeSize SrcTypeSize =
5360 CGM.getDataLayout().getTypeAllocSize(SrcTy);
5361 [[maybe_unused]] llvm::TypeSize DstTypeSize =
5362 CGM.getDataLayout().getTypeAllocSize(STy);
5363 if (STy->containsHomogeneousScalableVectorTypes()) {
5364 assert(SrcTypeSize == DstTypeSize &&
5365 "Only allow non-fractional movement of structure with "
5366 "homogeneous scalable vector type");
5367
5368 IRCallArgs[FirstIRArg] = I->getKnownRValue().getScalarVal();
5369 break;
5370 }
5371 }
5372
5373 // FIXME: Avoid the conversion through memory if possible.
5374 Address Src = Address::invalid();
5375 if (!I->isAggregate()) {
5376 Src = CreateMemTemp(I->Ty, "coerce");
5377 I->copyInto(*this, Src);
5378 } else {
5379 Src = I->hasLValue() ? I->getKnownLValue().getAddress()
5380 : I->getKnownRValue().getAggregateAddress();
5381 }
5382
5383 // If the value is offset in memory, apply the offset now.
5384 Src = emitAddressAtOffset(*this, Src, ArgInfo);
5385
5386 // Fast-isel and the optimizer generally like scalar values better than
5387 // FCAs, so we flatten them if this is safe to do for this argument.
5388 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
5389 llvm::Type *SrcTy = Src.getElementType();
5390 llvm::TypeSize SrcTypeSize =
5391 CGM.getDataLayout().getTypeAllocSize(SrcTy);
5392 llvm::TypeSize DstTypeSize = CGM.getDataLayout().getTypeAllocSize(STy);
5393 if (SrcTypeSize.isScalable()) {
5394 assert(STy->containsHomogeneousScalableVectorTypes() &&
5395 "ABI only supports structure with homogeneous scalable vector "
5396 "type");
5397 assert(SrcTypeSize == DstTypeSize &&
5398 "Only allow non-fractional movement of structure with "
5399 "homogeneous scalable vector type");
5400 assert(NumIRArgs == STy->getNumElements());
5401
5402 llvm::Value *StoredStructValue =
5403 Builder.CreateLoad(Src, Src.getName() + ".tuple");
5404 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
5405 llvm::Value *Extract = Builder.CreateExtractValue(
5406 StoredStructValue, i, Src.getName() + ".extract" + Twine(i));
5407 IRCallArgs[FirstIRArg + i] = Extract;
5408 }
5409 } else {
5410 uint64_t SrcSize = SrcTypeSize.getFixedValue();
5411 uint64_t DstSize = DstTypeSize.getFixedValue();
5412
5413 // If the source type is smaller than the destination type of the
5414 // coerce-to logic, copy the source value into a temp alloca the size
5415 // of the destination type to allow loading all of it. The bits past
5416 // the source value are left undef.
5417 if (SrcSize < DstSize) {
5418 Address TempAlloca = CreateTempAlloca(STy, Src.getAlignment(),
5419 Src.getName() + ".coerce");
5420 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
5421 Src = TempAlloca;
5422 } else {
5423 Src = Src.withElementType(STy);
5424 }
5425
5426 assert(NumIRArgs == STy->getNumElements());
5427 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
5428 Address EltPtr = Builder.CreateStructGEP(Src, i);
5429 llvm::Value *LI = Builder.CreateLoad(EltPtr);
5430 if (ArgHasMaybeUndefAttr)
5431 LI = Builder.CreateFreeze(LI);
5432 IRCallArgs[FirstIRArg + i] = LI;
5433 }
5434 }
5435 } else {
5436 // In the simple case, just pass the coerced loaded value.
5437 assert(NumIRArgs == 1);
5438 llvm::Value *Load =
5439 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
5440
5441 if (CallInfo.isCmseNSCall()) {
5442 // For certain parameter types, clear padding bits, as they may reveal
5443 // sensitive information.
5444 // Small struct/union types are passed as integer arrays.
5445 auto *ATy = dyn_cast<llvm::ArrayType>(Load->getType());
5446 if (ATy != nullptr && isa<RecordType>(I->Ty.getCanonicalType()))
5447 Load = EmitCMSEClearRecord(Load, ATy, I->Ty);
5448 }
5449
5450 if (ArgHasMaybeUndefAttr)
5451 Load = Builder.CreateFreeze(Load);
5452 IRCallArgs[FirstIRArg] = Load;
5453 }
5454
5455 break;
5456 }
5457
5459 auto coercionType = ArgInfo.getCoerceAndExpandType();
5460 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
5461
5462 llvm::Value *tempSize = nullptr;
5463 Address addr = Address::invalid();
5464 RawAddress AllocaAddr = RawAddress::invalid();
5465 if (I->isAggregate()) {
5466 addr = I->hasLValue() ? I->getKnownLValue().getAddress()
5467 : I->getKnownRValue().getAggregateAddress();
5468
5469 } else {
5470 RValue RV = I->getKnownRValue();
5471 assert(RV.isScalar()); // complex should always just be direct
5472
5473 llvm::Type *scalarType = RV.getScalarVal()->getType();
5474 auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
5475 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlign(scalarType);
5476
5477 // Materialize to a temporary.
5478 addr = CreateTempAlloca(
5479 RV.getScalarVal()->getType(),
5480 CharUnits::fromQuantity(std::max(layout->getAlignment(), scalarAlign)),
5481 "tmp",
5482 /*ArraySize=*/nullptr, &AllocaAddr);
5483 tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer());
5484
5485 Builder.CreateStore(RV.getScalarVal(), addr);
5486 }
5487
5488 addr = addr.withElementType(coercionType);
5489
5490 unsigned IRArgPos = FirstIRArg;
5491 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
5492 llvm::Type *eltType = coercionType->getElementType(i);
5493 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
5494 Address eltAddr = Builder.CreateStructGEP(addr, i);
5495 llvm::Value *elt = Builder.CreateLoad(eltAddr);
5496 if (ArgHasMaybeUndefAttr)
5497 elt = Builder.CreateFreeze(elt);
5498 IRCallArgs[IRArgPos++] = elt;
5499 }
5500 assert(IRArgPos == FirstIRArg + NumIRArgs);
5501
5502 if (tempSize) {
5503 EmitLifetimeEnd(tempSize, AllocaAddr.getPointer());
5504 }
5505
5506 break;
5507 }
5508
5509 case ABIArgInfo::Expand: {
5510 unsigned IRArgPos = FirstIRArg;
5511 ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos);
5512 assert(IRArgPos == FirstIRArg + NumIRArgs);
5513 break;
5514 }
5515 }
5516 }
5517
5518 const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this);
5519 llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer();
5520
5521 // If we're using inalloca, set up that argument.
5522 if (ArgMemory.isValid()) {
5523 llvm::Value *Arg = ArgMemory.getPointer();
5524 assert(IRFunctionArgs.hasInallocaArg());
5525 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
5526 }
5527
5528 // 2. Prepare the function pointer.
5529
5530 // If the callee is a bitcast of a non-variadic function to have a
5531 // variadic function pointer type, check to see if we can remove the
5532 // bitcast. This comes up with unprototyped functions.
5533 //
5534 // This makes the IR nicer, but more importantly it ensures that we
5535 // can inline the function at -O0 if it is marked always_inline.
5536 auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT,
5537 llvm::Value *Ptr) -> llvm::Function * {
5538 if (!CalleeFT->isVarArg())
5539 return nullptr;
5540
5541 // Get underlying value if it's a bitcast
5542 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) {
5543 if (CE->getOpcode() == llvm::Instruction::BitCast)
5544 Ptr = CE->getOperand(0);
5545 }
5546
5547 llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr);
5548 if (!OrigFn)
5549 return nullptr;
5550
5551 llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
5552
5553 // If the original type is variadic, or if any of the component types
5554 // disagree, we cannot remove the cast.
5555 if (OrigFT->isVarArg() ||
5556 OrigFT->getNumParams() != CalleeFT->getNumParams() ||
5557 OrigFT->getReturnType() != CalleeFT->getReturnType())
5558 return nullptr;
5559
5560 for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
5561 if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
5562 return nullptr;
5563
5564 return OrigFn;
5565 };
5566
5567 if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) {
5568 CalleePtr = OrigFn;
5569 IRFuncTy = OrigFn->getFunctionType();
5570 }
5571
5572 // 3. Perform the actual call.
5573
5574 // Deactivate any cleanups that we're supposed to do immediately before
5575 // the call.
5576 if (!CallArgs.getCleanupsToDeactivate().empty())
5577 deactivateArgCleanupsBeforeCall(*this, CallArgs);
5578
5579 // Assert that the arguments we computed match up. The IR verifier
5580 // will catch this, but this is a common enough source of problems
5581 // during IRGen changes that it's way better for debugging to catch
5582 // it ourselves here.
5583#ifndef NDEBUG
5584 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
5585 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
5586 // Inalloca argument can have different type.
5587 if (IRFunctionArgs.hasInallocaArg() &&
5588 i == IRFunctionArgs.getInallocaArgNo())
5589 continue;
5590 if (i < IRFuncTy->getNumParams())
5591 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
5592 }
5593#endif
5594
5595 // Update the largest vector width if any arguments have vector types.
5596 for (unsigned i = 0; i < IRCallArgs.size(); ++i)
5597 LargestVectorWidth = std::max(LargestVectorWidth,
5598 getMaxVectorWidth(IRCallArgs[i]->getType()));
5599
5600 // Compute the calling convention and attributes.
5601 unsigned CallingConv;
5602 llvm::AttributeList Attrs;
5603 CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
5604 Callee.getAbstractInfo(), Attrs, CallingConv,
5605 /*AttrOnCallSite=*/true,
5606 /*IsThunk=*/false);
5607
5608 if (CallingConv == llvm::CallingConv::X86_VectorCall &&
5609 getTarget().getTriple().isWindowsArm64EC()) {
5610 CGM.Error(Loc, "__vectorcall calling convention is not currently "
5611 "supported");
5612 }
5613
5614 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
5615 if (FD->hasAttr<StrictFPAttr>())
5616 // All calls within a strictfp function are marked strictfp
5617 Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::StrictFP);
5618
5619 // If -ffast-math is enabled and the function is guarded by an
5620 // '__attribute__((optnone)) adjust the memory attribute so the BE emits the
5621 // library call instead of the intrinsic.
5622 if (FD->hasAttr<OptimizeNoneAttr>() && getLangOpts().FastMath)
5623 CGM.AdjustMemoryAttribute(CalleePtr->getName(), Callee.getAbstractInfo(),
5624 Attrs);
5625 }
5626 // Add call-site nomerge attribute if exists.
5628 Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoMerge);
5629
5630 // Add call-site noinline attribute if exists.
5632 Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoInline);
5633
5634 // Add call-site always_inline attribute if exists.
5636 Attrs =
5637 Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::AlwaysInline);
5638
5639 // Apply some call-site-specific attributes.
5640 // TODO: work this into building the attribute set.
5641
5642 // Apply always_inline to all calls within flatten functions.
5643 // FIXME: should this really take priority over __try, below?
5644 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
5646 !(TargetDecl && TargetDecl->hasAttr<NoInlineAttr>())) {
5647 Attrs =
5648 Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::AlwaysInline);
5649 }
5650
5651 // Disable inlining inside SEH __try blocks.
5652 if (isSEHTryScope()) {
5653 Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoInline);
5654 }
5655
5656 // Decide whether to use a call or an invoke.
5657 bool CannotThrow;
5659 // SEH cares about asynchronous exceptions, so everything can "throw."
5660 CannotThrow = false;
5661 } else if (isCleanupPadScope() &&
5663 // The MSVC++ personality will implicitly terminate the program if an
5664 // exception is thrown during a cleanup outside of a try/catch.
5665 // We don't need to model anything in IR to get this behavior.
5666 CannotThrow = true;
5667 } else {
5668 // Otherwise, nounwind call sites will never throw.
5669 CannotThrow = Attrs.hasFnAttr(llvm::Attribute::NoUnwind);
5670
5671 if (auto *FPtr = dyn_cast<llvm::Function>(CalleePtr))
5672 if (FPtr->hasFnAttribute(llvm::Attribute::NoUnwind))
5673 CannotThrow = true;
5674 }
5675
5676 // If we made a temporary, be sure to clean up after ourselves. Note that we
5677 // can't depend on being inside of an ExprWithCleanups, so we need to manually
5678 // pop this cleanup later on. Being eager about this is OK, since this
5679 // temporary is 'invisible' outside of the callee.
5680 if (UnusedReturnSizePtr)
5681 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca,
5682 UnusedReturnSizePtr);
5683
5684 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
5685
5687 getBundlesForFunclet(CalleePtr);
5688
5689 if (SanOpts.has(SanitizerKind::KCFI) &&
5690 !isa_and_nonnull<FunctionDecl>(TargetDecl))
5691 EmitKCFIOperandBundle(ConcreteCallee, BundleList);
5692
5693 // Add the pointer-authentication bundle.
5694 EmitPointerAuthOperandBundle(ConcreteCallee.getPointerAuthInfo(), BundleList);
5695
5696 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
5697 if (FD->hasAttr<StrictFPAttr>())
5698 // All calls within a strictfp function are marked strictfp
5699 Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::StrictFP);
5700
5701 AssumeAlignedAttrEmitter AssumeAlignedAttrEmitter(*this, TargetDecl);
5702 Attrs = AssumeAlignedAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
5703
5704 AllocAlignAttrEmitter AllocAlignAttrEmitter(*this, TargetDecl, CallArgs);
5705 Attrs = AllocAlignAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
5706
5707 // Emit the actual call/invoke instruction.
5708 llvm::CallBase *CI;
5709 if (!InvokeDest) {
5710 CI = Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList);
5711 } else {
5712 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
5713 CI = Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs,
5714 BundleList);
5715 EmitBlock(Cont);
5716 }
5717 if (CI->getCalledFunction() && CI->getCalledFunction()->hasName() &&
5718 CI->getCalledFunction()->getName().starts_with("_Z4sqrt")) {
5720 }
5721 if (callOrInvoke)
5722 *callOrInvoke = CI;
5723
5724 // If this is within a function that has the guard(nocf) attribute and is an
5725 // indirect call, add the "guard_nocf" attribute to this call to indicate that
5726 // Control Flow Guard checks should not be added, even if the call is inlined.
5727 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
5728 if (const auto *A = FD->getAttr<CFGuardAttr>()) {
5729 if (A->getGuard() == CFGuardAttr::GuardArg::nocf && !CI->getCalledFunction())
5730 Attrs = Attrs.addFnAttribute(getLLVMContext(), "guard_nocf");
5731 }
5732 }
5733
5734 // Apply the attributes and calling convention.
5735 CI->setAttributes(Attrs);
5736 CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
5737
5738 // Apply various metadata.
5739
5740 if (!CI->getType()->isVoidTy())
5741 CI->setName("call");
5742
5743 if (CGM.shouldEmitConvergenceTokens() && CI->isConvergent())
5745
5746 // Update largest vector width from the return type.
5747 LargestVectorWidth =
5748 std::max(LargestVectorWidth, getMaxVectorWidth(CI->getType()));
5749
5750 // Insert instrumentation or attach profile metadata at indirect call sites.
5751 // For more details, see the comment before the definition of
5752 // IPVK_IndirectCallTarget in InstrProfData.inc.
5753 if (!CI->getCalledFunction())
5754 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
5755 CI, CalleePtr);
5756
5757 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
5758 // optimizer it can aggressively ignore unwind edges.
5759 if (CGM.getLangOpts().ObjCAutoRefCount)
5760 AddObjCARCExceptionMetadata(CI);
5761
5762 // Set tail call kind if necessary.
5763 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
5764 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
5765 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
5766 else if (IsMustTail) {
5767 if (getTarget().getTriple().isPPC()) {
5768 if (getTarget().getTriple().isOSAIX())
5769 CGM.getDiags().Report(Loc, diag::err_aix_musttail_unsupported);
5770 else if (!getTarget().hasFeature("pcrelative-memops")) {
5771 if (getTarget().hasFeature("longcall"))
5772 CGM.getDiags().Report(Loc, diag::err_ppc_impossible_musttail) << 0;
5773 else if (Call->isIndirectCall())
5774 CGM.getDiags().Report(Loc, diag::err_ppc_impossible_musttail) << 1;
5775 else if (isa_and_nonnull<FunctionDecl>(TargetDecl)) {
5776 if (!cast<FunctionDecl>(TargetDecl)->isDefined())
5777 // The undefined callee may be a forward declaration. Without
5778 // knowning all symbols in the module, we won't know the symbol is
5779 // defined or not. Collect all these symbols for later diagnosing.
5781 {cast<FunctionDecl>(TargetDecl), Loc});
5782 else {
5783 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(
5784 GlobalDecl(cast<FunctionDecl>(TargetDecl)));
5785 if (llvm::GlobalValue::isWeakForLinker(Linkage) ||
5786 llvm::GlobalValue::isDiscardableIfUnused(Linkage))
5787 CGM.getDiags().Report(Loc, diag::err_ppc_impossible_musttail)
5788 << 2;
5789 }
5790 }
5791 }
5792 }
5793 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
5794 }
5795 }
5796
5797 // Add metadata for calls to MSAllocator functions
5798 if (getDebugInfo() && TargetDecl &&
5799 TargetDecl->hasAttr<MSAllocatorAttr>())
5801
5802 // Add metadata if calling an __attribute__((error(""))) or warning fn.
5803 if (TargetDecl && TargetDecl->hasAttr<ErrorAttr>()) {
5804 llvm::ConstantInt *Line =
5805 llvm::ConstantInt::get(Int64Ty, Loc.getRawEncoding());
5806 llvm::ConstantAsMetadata *MD = llvm::ConstantAsMetadata::get(Line);
5807 llvm::MDTuple *MDT = llvm::MDNode::get(getLLVMContext(), {MD});
5808 CI->setMetadata("srcloc", MDT);
5809 }
5810
5811 // 4. Finish the call.
5812
5813 // If the call doesn't return, finish the basic block and clear the
5814 // insertion point; this allows the rest of IRGen to discard
5815 // unreachable code.
5816 if (CI->doesNotReturn()) {
5817 if (UnusedReturnSizePtr)
5819
5820 // Strip away the noreturn attribute to better diagnose unreachable UB.
5821 if (SanOpts.has(SanitizerKind::Unreachable)) {
5822 // Also remove from function since CallBase::hasFnAttr additionally checks
5823 // attributes of the called function.
5824 if (auto *F = CI->getCalledFunction())
5825 F->removeFnAttr(llvm::Attribute::NoReturn);
5826 CI->removeFnAttr(llvm::Attribute::NoReturn);
5827
5828 // Avoid incompatibility with ASan which relies on the `noreturn`
5829 // attribute to insert handler calls.
5830 if (SanOpts.hasOneOf(SanitizerKind::Address |
5831 SanitizerKind::KernelAddress)) {
5832 SanitizerScope SanScope(this);
5833 llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder);
5834 Builder.SetInsertPoint(CI);
5835 auto *FnType = llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
5836 llvm::FunctionCallee Fn =
5837 CGM.CreateRuntimeFunction(FnType, "__asan_handle_no_return");
5839 }
5840 }
5841
5843 Builder.ClearInsertionPoint();
5844
5845 // FIXME: For now, emit a dummy basic block because expr emitters in
5846 // generally are not ready to handle emitting expressions at unreachable
5847 // points.
5849
5850 // Return a reasonable RValue.
5851 return GetUndefRValue(RetTy);
5852 }
5853
5854 // If this is a musttail call, return immediately. We do not branch to the
5855 // epilogue in this case.
5856 if (IsMustTail) {
5857 for (auto it = EHStack.find(CurrentCleanupScopeDepth); it != EHStack.end();
5858 ++it) {
5859 EHCleanupScope *Cleanup = dyn_cast<EHCleanupScope>(&*it);
5860 if (!(Cleanup && Cleanup->getCleanup()->isRedundantBeforeReturn()))
5861 CGM.ErrorUnsupported(MustTailCall, "tail call skipping over cleanups");
5862 }
5863 if (CI->getType()->isVoidTy())
5864 Builder.CreateRetVoid();
5865 else
5866 Builder.CreateRet(CI);
5867 Builder.ClearInsertionPoint();
5869 return GetUndefRValue(RetTy);
5870 }
5871
5872 // Perform the swifterror writeback.
5873 if (swiftErrorTemp.isValid()) {
5874 llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
5875 Builder.CreateStore(errorResult, swiftErrorArg);
5876 }
5877
5878 // Emit any call-associated writebacks immediately. Arguably this
5879 // should happen after any return-value munging.
5880 if (CallArgs.hasWritebacks())
5881 emitWritebacks(*this, CallArgs);
5882
5883 // The stack cleanup for inalloca arguments has to run out of the normal
5884 // lexical order, so deactivate it and run it manually here.
5885 CallArgs.freeArgumentMemory(*this);
5886
5887 // Extract the return value.
5888 RValue Ret;
5889
5890 // If the current function is a virtual function pointer thunk, avoid copying
5891 // the return value of the musttail call to a temporary.
5892 if (IsVirtualFunctionPointerThunk) {
5893 Ret = RValue::get(CI);
5894 } else {
5895 Ret = [&] {
5896 switch (RetAI.getKind()) {
5898 auto coercionType = RetAI.getCoerceAndExpandType();
5899
5900 Address addr = SRetPtr.withElementType(coercionType);
5901
5902 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
5903 bool requiresExtract = isa<llvm::StructType>(CI->getType());
5904
5905 unsigned unpaddedIndex = 0;
5906 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
5907 llvm::Type *eltType = coercionType->getElementType(i);
5909 continue;
5910 Address eltAddr = Builder.CreateStructGEP(addr, i);
5911 llvm::Value *elt = CI;
5912 if (requiresExtract)
5913 elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
5914 else
5915 assert(unpaddedIndex == 0);
5916 Builder.CreateStore(elt, eltAddr);
5917 }
5918 [[fallthrough]];
5919 }
5920
5922 case ABIArgInfo::Indirect: {
5923 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
5924 if (UnusedReturnSizePtr)
5926 return ret;
5927 }
5928
5929 case ABIArgInfo::Ignore:
5930 // If we are ignoring an argument that had a result, make sure to
5931 // construct the appropriate return value for our caller.
5932 return GetUndefRValue(RetTy);
5933
5934 case ABIArgInfo::Extend:
5935 case ABIArgInfo::Direct: {
5936 llvm::Type *RetIRTy = ConvertType(RetTy);
5937 if (RetAI.getCoerceToType() == RetIRTy &&
5938 RetAI.getDirectOffset() == 0) {
5939 switch (getEvaluationKind(RetTy)) {
5940 case TEK_Complex: {
5941 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
5942 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
5943 return RValue::getComplex(std::make_pair(Real, Imag));
5944 }
5945 case TEK_Aggregate: {
5946 Address DestPtr = ReturnValue.getAddress();
5947 bool DestIsVolatile = ReturnValue.isVolatile();
5948
5949 if (!DestPtr.isValid()) {
5950 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
5951 DestIsVolatile = false;
5952 }
5953 EmitAggregateStore(CI, DestPtr, DestIsVolatile);
5954 return RValue::getAggregate(DestPtr);
5955 }
5956 case TEK_Scalar: {
5957 // If the argument doesn't match, perform a bitcast to coerce it.
5958 // This can happen due to trivial type mismatches.
5959 llvm::Value *V = CI;
5960 if (V->getType() != RetIRTy)
5961 V = Builder.CreateBitCast(V, RetIRTy);
5962 return RValue::get(V);
5963 }
5964 }
5965 llvm_unreachable("bad evaluation kind");
5966 }
5967
5968 // If coercing a fixed vector from a scalable vector for ABI
5969 // compatibility, and the types match, use the llvm.vector.extract
5970 // intrinsic to perform the conversion.
5971 if (auto *FixedDstTy = dyn_cast<llvm::FixedVectorType>(RetIRTy)) {
5972 llvm::Value *V = CI;
5973 if (auto *ScalableSrcTy =
5974 dyn_cast<llvm::ScalableVectorType>(V->getType())) {
5975 if (FixedDstTy->getElementType() ==
5976 ScalableSrcTy->getElementType()) {
5977 llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty);
5978 V = Builder.CreateExtractVector(FixedDstTy, V, Zero,
5979 "cast.fixed");
5980 return RValue::get(V);
5981 }
5982 }
5983 }
5984
5985 Address DestPtr = ReturnValue.getValue();
5986 bool DestIsVolatile = ReturnValue.isVolatile();
5987
5988 if (!DestPtr.isValid()) {
5989 DestPtr = CreateMemTemp(RetTy, "coerce");
5990 DestIsVolatile = false;
5991 }
5992
5993 // An empty record can overlap other data (if declared with
5994 // no_unique_address); omit the store for such types - as there is no
5995 // actual data to store.
5996 if (!isEmptyRecord(getContext(), RetTy, true)) {
5997 // If the value is offset in memory, apply the offset now.
5998 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
5999 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
6000 }
6001
6002 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
6003 }
6004
6005 case ABIArgInfo::Expand:
6007 llvm_unreachable("Invalid ABI kind for return argument");
6008 }
6009
6010 llvm_unreachable("Unhandled ABIArgInfo::Kind");
6011 }();
6012 }
6013
6014 // Emit the assume_aligned check on the return value.
6015 if (Ret.isScalar() && TargetDecl) {
6016 AssumeAlignedAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
6017 AllocAlignAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
6018 }
6019
6020 // Explicitly call CallLifetimeEnd::Emit just to re-use the code even though
6021 // we can't use the full cleanup mechanism.
6022 for (CallLifetimeEnd &LifetimeEnd : CallLifetimeEndAfterCall)
6023 LifetimeEnd.Emit(*this, /*Flags=*/{});
6024
6025 if (!ReturnValue.isExternallyDestructed() &&
6027 pushDestroy(QualType::DK_nontrivial_c_struct, Ret.getAggregateAddress(),
6028 RetTy);
6029
6030 return Ret;
6031}
6032
6034 if (isVirtual()) {
6035 const CallExpr *CE = getVirtualCallExpr();
6038 CE ? CE->getBeginLoc() : SourceLocation());
6039 }
6040
6041 return *this;
6042}
6043
6044/* VarArg handling */
6045
6047 AggValueSlot Slot) {
6048 VAListAddr = VE->isMicrosoftABI() ? EmitMSVAListRef(VE->getSubExpr())
6049 : EmitVAListRef(VE->getSubExpr());
6050 QualType Ty = VE->getType();
6051 if (VE->isMicrosoftABI())
6052 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty, Slot);
6053 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty, Slot);
6054}
#define V(N, I)
Definition: ASTContext.h:3338
StringRef P
static void appendParameterTypes(const CodeGenTypes &CGT, SmallVectorImpl< CanQualType > &prefix, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &paramInfos, CanQual< FunctionProtoType > FPT)
Adds the formal parameters in FPT to the given prefix.
Definition: CGCall.cpp:155
static bool isInAllocaArgument(CGCXXABI &ABI, QualType type)
Definition: CGCall.cpp:4060
static uint64_t buildMultiCharMask(const SmallVectorImpl< uint64_t > &Bits, int Pos, int Size, int CharWidth, bool BigEndian)
Definition: CGCall.cpp:3736
static llvm::Value * tryRemoveRetainOfSelf(CodeGenFunction &CGF, llvm::Value *result)
If this is a +1 of the value of an immutable 'self', remove it.
Definition: CGCall.cpp:3493
static CanQualType GetReturnType(QualType RetTy)
Returns the "extra-canonicalized" return type, which discards qualifiers on the return type.
Definition: CGCall.cpp:110
static const NonNullAttr * getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD, QualType ArgType, unsigned ArgNo)
Returns the attribute (either parameter attribute, or function attribute), which declares argument Ar...
Definition: CGCall.cpp:2910
static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr, const ABIArgInfo &info)
Definition: CGCall.cpp:1428
static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty)
Definition: CGCall.cpp:4065
static void setBitRange(SmallVectorImpl< uint64_t > &Bits, int BitOffset, int BitWidth, int CharWidth)
Definition: CGCall.cpp:3615
static SmallVector< CanQualType, 16 > getArgTypesForCall(ASTContext &ctx, const CallArgList &args)
Definition: CGCall.cpp:385
static bool isProvablyNull(llvm::Value *addr)
Definition: CGCall.cpp:4135
static void AddAttributesFromFunctionProtoType(ASTContext &Ctx, llvm::AttrBuilder &FuncAttrs, const FunctionProtoType *FPT)
Definition: CGCall.cpp:1769
static void eraseUnusedBitCasts(llvm::Instruction *insn)
Definition: CGCall.cpp:3393
static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method)
Definition: CGCall.cpp:4459
static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs, const LangOptions &LangOpts, const NoBuiltinAttr *NBA=nullptr)
Definition: CGCall.cpp:2168
static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args, const ObjCIndirectCopyRestoreExpr *CRE)
Emit an argument that's being passed call-by-writeback.
Definition: CGCall.cpp:4237
static void overrideFunctionFeaturesWithTargetFeatures(llvm::AttrBuilder &FuncAttr, const llvm::Function &F, const TargetOptions &TargetOpts)
Merges target-features from \TargetOpts and \F, and sets the result in \FuncAttr.
Definition: CGCall.cpp:2047
static const CGFunctionInfo & arrangeFreeFunctionLikeCall(CodeGenTypes &CGT, CodeGenModule &CGM, const CallArgList &args, const FunctionType *fnType, unsigned numExtraRequiredArgs, bool chainCall)
Arrange a call as unto a free function, except possibly with an additional number of formal parameter...
Definition: CGCall.cpp:591
static llvm::Value * CreateCoercedLoad(Address Src, llvm::Type *Ty, CodeGenFunction &CGF)
CreateCoercedLoad - Create a load from.
Definition: CGCall.cpp:1263
static llvm::SmallVector< FunctionProtoType::ExtParameterInfo, 16 > getExtParameterInfosForCall(const FunctionProtoType *proto, unsigned prefixArgs, unsigned totalArgs)
Definition: CGCall.cpp:401
static CallingConv getCallingConventionForDecl(const ObjCMethodDecl *D, bool IsWindows)
Definition: CGCall.cpp:212
static int getExpansionSize(QualType Ty, const ASTContext &Context)
Definition: CGCall.cpp:994
static CanQual< FunctionProtoType > GetFormalType(const CXXMethodDecl *MD)
Returns the canonical formal type of the given C++ method.
Definition: CGCall.cpp:101
static bool DetermineNoUndef(QualType QTy, CodeGenTypes &Types, const llvm::DataLayout &DL, const ABIArgInfo &AI, bool CheckCoerce=true)
Definition: CGCall.cpp:2204
static const Expr * maybeGetUnaryAddrOfOperand(const Expr *E)
Definition: CGCall.cpp:4226
static void addDenormalModeAttrs(llvm::DenormalMode FPDenormalMode, llvm::DenormalMode FP32DenormalMode, llvm::AttrBuilder &FuncAttrs)
Add denormal-fp-math and denormal-fp-math-f32 as appropriate for the requested denormal behavior,...
Definition: CGCall.cpp:1868
static void emitWritebacks(CodeGenFunction &CGF, const CallArgList &args)
Definition: CGCall.cpp:4209
static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF, const CallArgList &CallArgs)
Definition: CGCall.cpp:4215
static bool isProvablyNonNull(Address Addr, CodeGenFunction &CGF)
Definition: CGCall.cpp:4139
static llvm::Value * emitArgumentDemotion(CodeGenFunction &CGF, const VarDecl *var, llvm::Value *value)
An argument came in as a promoted argument; demote it back to its declared type.
Definition: CGCall.cpp:2890
static void CreateCoercedStore(llvm::Value *Src, Address Dst, bool DstIsVolatile, CodeGenFunction &CGF)
CreateCoercedStore - Create a store to.
Definition: CGCall.cpp:1363
static SmallVector< CanQualType, 16 > getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args)
Definition: CGCall.cpp:393
static const CGFunctionInfo & arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod, SmallVectorImpl< CanQualType > &prefix, CanQual< FunctionProtoType > FTP)
Arrange the LLVM function layout for a value of the given function type, on top of any implicit param...
Definition: CGCall.cpp:188
static void addExtParameterInfosForCall(llvm::SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &paramInfos, const FunctionProtoType *proto, unsigned prefixArgs, unsigned totalArgs)
Definition: CGCall.cpp:125
static bool canApplyNoFPClass(const ABIArgInfo &AI, QualType ParamType, bool IsReturn)
Test if it's legal to apply nofpclass for the given parameter type and it's lowered IR type.
Definition: CGCall.cpp:2277
static void getTrivialDefaultFunctionAttributes(StringRef Name, bool HasOptnone, const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, bool AttrOnCallSite, llvm::AttrBuilder &FuncAttrs)
Definition: CGCall.cpp:1888
static llvm::FPClassTest getNoFPClassTestMask(const LangOptions &LangOpts)
Return the nofpclass mask that can be applied to floating-point parameters.
Definition: CGCall.cpp:2299
static void forConstantArrayExpansion(CodeGenFunction &CGF, ConstantArrayExpansion *CAE, Address BaseAddr, llvm::function_ref< void(Address)> Fn)
Definition: CGCall.cpp:1036
static bool IsArgumentMaybeUndef(const Decl *TargetDecl, unsigned NumRequiredArgs, unsigned ArgNo)
Check if the argument of a function has maybe_undef attribute.
Definition: CGCall.cpp:2255
static bool hasInAllocaArgs(CodeGenModule &CGM, CallingConv ExplicitCC, ArrayRef< QualType > ArgTypes)
Definition: CGCall.cpp:4441
static std::unique_ptr< TypeExpansion > getTypeExpansion(QualType Ty, const ASTContext &Context)
Definition: CGCall.cpp:940
static RawAddress CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty, CharUnits MinAlign, const Twine &Name="tmp")
Create a temporary allocation for the purposes of coercion.
Definition: CGCall.cpp:1157
static void setUsedBits(CodeGenModule &, QualType, int, SmallVectorImpl< uint64_t > &)
Definition: CGCall.cpp:3719
static llvm::StoreInst * findDominatingStoreToReturnValue(CodeGenFunction &CGF)
Heuristically search for a dominating store to the return-value slot.
Definition: CGCall.cpp:3550
static void setCUDAKernelCallingConvention(CanQualType &FTy, CodeGenModule &CGM, const FunctionDecl *FD)
Set calling convention for CUDA/HIP kernel.
Definition: CGCall.cpp:293
static llvm::Value * tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF, llvm::Value *result)
Try to emit a fused autorelease of a return result.
Definition: CGCall.cpp:3405
static Address EnterStructPointerForCoercedAccess(Address SrcPtr, llvm::StructType *SrcSTy, uint64_t DstSize, CodeGenFunction &CGF)
EnterStructPointerForCoercedAccess - Given a struct pointer that we are accessing some number of byte...
Definition: CGCall.cpp:1173
static llvm::Value * emitAutoreleaseOfResult(CodeGenFunction &CGF, llvm::Value *result)
Emit an ARC autorelease of the result of a function.
Definition: CGCall.cpp:3532
static void emitWriteback(CodeGenFunction &CGF, const CallArgList::Writeback &writeback)
Emit the actual writing-back of a writeback.
Definition: CGCall.cpp:4144
static bool HasStrictReturn(const CodeGenModule &Module, QualType RetTy, const Decl *TargetDecl)
Definition: CGCall.cpp:1833
static void addMergableDefaultFunctionAttributes(const CodeGenOptions &CodeGenOpts, llvm::AttrBuilder &FuncAttrs)
Add default attributes to a function, which have merge semantics under -mlink-builtin-bitcode and sho...
Definition: CGCall.cpp:1882
static llvm::Value * CoerceIntOrPtrToIntOrPtr(llvm::Value *Val, llvm::Type *Ty, CodeGenFunction &CGF)
CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both are either integers or p...
Definition: CGCall.cpp:1209
static void AddAttributesFromOMPAssumes(llvm::AttrBuilder &FuncAttrs, const Decl *Callee)
Definition: CGCall.cpp:1806
static unsigned getMaxVectorWidth(const llvm::Type *Ty)
Definition: CGCall.cpp:5022
CodeGenFunction::ComplexPairTy ComplexPairTy
const Decl * D
Expr * E
enum clang::sema::@1651::IndirectLocalPathEntry::EntryKind Kind
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
llvm::MachO::Target Target
Definition: MachO.h:51
static bool hasFeature(StringRef Feature, const LangOptions &LangOpts, const TargetInfo &Target)
Determine whether a translation unit built using the current language options has the given feature.
Definition: Module.cpp:100
static QualType getParamType(Sema &SemaRef, ArrayRef< ResultCandidate > Candidates, unsigned N)
Get the type of the Nth parameter from a given set of overload candidates.
SourceLocation Loc
Definition: SemaObjC.cpp:758
static QualType getPointeeType(const MemRegion *R)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:186
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2822
CanQualType getCanonicalParamType(QualType T) const
Return the canonical parameter type corresponding to the specific potentially non-canonical one.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
Definition: ASTContext.h:1145
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2124
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType IntTy
Definition: ASTContext.h:1127
TypeInfoChars getTypeInfoInChars(const Type *T) const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2391
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1118
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:778
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
QualType getIntPtrType() const
Return a type compatible with "intptr_t" (C99 7.18.1.4), as defined by the target.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2395
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3540
Attr - This represents one attribute.
Definition: Attr.h:42
const FunctionProtoType * getFunctionType() const
getFunctionType - Return the underlying function type for this block.
Definition: Expr.cpp:2513
This class is used for builtin types like 'int'.
Definition: Type.h:3000
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:249
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition: DeclCXX.cpp:2464
bool isVirtual() const
Definition: DeclCXX.h:2115
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2221
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1978
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:634
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2830
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1638
static CanQual< Type > CreateUnsafe(QualType Other)
Builds a canonical type from a QualType.
CanProxy< U > castAs() const
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition: CharUnits.h:189
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
llvm::DenormalMode FPDenormalMode
The floating-point denormal mode to use.
static StringRef getFramePointerKindName(FramePointerKind Kind)
std::vector< std::string > Reciprocals
llvm::DenormalMode FP32DenormalMode
The floating-point denormal mode to use, for float.
std::string TrapFuncName
If not an empty string, trap intrinsics are lowered to calls to this function instead of to trap inst...
std::vector< std::string > DefaultFunctionAttrs
std::string PreferVectorWidth
The preferred width for auto-vectorization transforms.
ABIArgInfo - Helper class to encapsulate information about how a specific C type should be passed to ...
unsigned getInAllocaFieldIndex() const
llvm::StructType * getCoerceAndExpandType() const
void setCoerceToType(llvm::Type *T)
llvm::Type * getUnpaddedCoerceAndExpandType() const
unsigned getDirectOffset() const
static bool isPaddingForCoerceAndExpand(llvm::Type *eltType)
bool getInAllocaSRet() const
Return true if this field of an inalloca struct should be returned to implement a struct return calli...
llvm::Type * getPaddingType() const
unsigned getDirectAlign() const
unsigned getIndirectAddrSpace() const
@ Extend
Extend - Valid only for integer argument types.
@ Ignore
Ignore - Ignore the argument (treat as void).
@ IndirectAliased
IndirectAliased - Similar to Indirect, but the pointer may be to an object that is otherwise referenc...
@ Expand
Expand - Only valid for aggregate argument types.
@ InAlloca
InAlloca - Pass the argument directly using the LLVM inalloca attribute.
@ Indirect
Indirect - Pass the argument indirectly via a hidden pointer with the specified alignment (0 indicate...
@ CoerceAndExpand
CoerceAndExpand - Only valid for aggregate argument types.
@ Direct
Direct - Pass the argument directly using the normal converted LLVM type, or by coercing to another s...
ArrayRef< llvm::Type * > getCoerceAndExpandTypeSequence() const
unsigned getInAllocaIndirect() const
llvm::Type * getCoerceToType() const
CharUnits getIndirectAlign() const
virtual RValue EmitMSVAArg(CodeGen::CodeGenFunction &CGF, CodeGen::Address VAListAddr, QualType Ty, AggValueSlot Slot) const
Emit the target dependent code to load a value of.
Definition: ABIInfo.cpp:42
virtual RValue EmitVAArg(CodeGen::CodeGenFunction &CGF, CodeGen::Address VAListAddr, QualType Ty, AggValueSlot Slot) const =0
EmitVAArg - Emit the target dependent code to load a value of.
virtual void computeInfo(CodeGen::CGFunctionInfo &FI) const =0
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition: Address.h:128
llvm::Value * getBasePointer() const
Definition: Address.h:193
static Address invalid()
Definition: Address.h:176
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition: Address.h:251
CharUnits getAlignment() const
Definition: Address.h:189
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition: Address.h:207
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition: Address.h:274
llvm::StringRef getName() const
Return the IR name of the pointer value.
Definition: Address.h:216
bool isValid() const
Definition: Address.h:177
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition: Address.h:199
An aggregate value slot.
Definition: CGValue.h:504
Address getAddress() const
Definition: CGValue.h:644
void setExternallyDestructed(bool destructed=true)
Definition: CGValue.h:613
static AggValueSlot forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
forAddr - Make a slot for an aggregate value.
Definition: CGValue.h:587
RValue asRValue() const
Definition: CGValue.h:666
const BlockExpr * BlockExpression
Definition: CGBlocks.h:278
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:135
Address CreateConstInBoundsByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Given a pointer to i8, adjust it by a given constant offset.
Definition: CGBuilder.h:304
llvm::Value * CreateIsNull(Address Addr, const Twine &Name="")
Definition: CGBuilder.h:354
Address CreateConstGEP2_32(Address Addr, unsigned Idx0, unsigned Idx1, const llvm::Twine &Name="")
Definition: CGBuilder.h:330
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition: CGBuilder.h:218
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:107
llvm::LoadInst * CreateFlagLoad(llvm::Value *Addr, const llvm::Twine &Name="")
Emit a load from an i1 flag variable.
Definition: CGBuilder.h:157
llvm::CallInst * CreateMemCpy(Address Dest, Address Src, llvm::Value *Size, bool IsVolatile=false)
Definition: CGBuilder.h:363
llvm::LoadInst * CreateAlignedLoad(llvm::Type *Ty, llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition: CGBuilder.h:127
Address CreateAddrSpaceCast(Address Addr, llvm::Type *Ty, llvm::Type *ElementTy, const llvm::Twine &Name="")
Definition: CGBuilder.h:188
Implements C++ ABI-specific code generation functions.
Definition: CGCXXABI.h:43
virtual bool hasMostDerivedReturn(GlobalDecl GD) const
Definition: CGCXXABI.h:131
virtual bool HasThisReturn(GlobalDecl GD) const
Returns true if the given constructor or destructor is one of the kinds that the ABI says returns 'th...
Definition: CGCXXABI.h:123
@ RAA_DirectInMemory
Pass it on the stack using its defined layout.
Definition: CGCXXABI.h:158
virtual CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD, Address This, llvm::Type *Ty, SourceLocation Loc)=0
Build a virtual function pointer in the ABI-specific way.
virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const =0
Returns how an argument of the given record type should be passed.
virtual const CXXRecordDecl * getThisArgumentTypeForMethod(GlobalDecl GD)
Get the type of the implicit "this" parameter used by a method.
Definition: CGCXXABI.h:387
virtual AddedStructorArgCounts buildStructorSignature(GlobalDecl GD, SmallVectorImpl< CanQualType > &ArgTys)=0
Build the signature of the given constructor or destructor variant by adding any required parameters.
Abstract information about a function or function prototype.
Definition: CGCall.h:41
const GlobalDecl getCalleeDecl() const
Definition: CGCall.h:59
const FunctionProtoType * getCalleeFunctionProtoType() const
Definition: CGCall.h:56
All available information about a concrete callee.
Definition: CGCall.h:63
CGCallee prepareConcreteCallee(CodeGenFunction &CGF) const
If this is a delayed callee computation of some sort, prepare a concrete callee.
Definition: CGCall.cpp:6033
bool isVirtual() const
Definition: CGCall.h:204
Address getThisAddress() const
Definition: CGCall.h:215
const CallExpr * getVirtualCallExpr() const
Definition: CGCall.h:207
llvm::Value * getFunctionPointer() const
Definition: CGCall.h:190
llvm::FunctionType * getVirtualFunctionType() const
Definition: CGCall.h:219
const CGPointerAuthInfo & getPointerAuthInfo() const
Definition: CGCall.h:186
GlobalDecl getVirtualMethodDecl() const
Definition: CGCall.h:211
void addHeapAllocSiteMetadata(llvm::CallBase *CallSite, QualType AllocatedTy, SourceLocation Loc)
Add heapallocsite metadata for MSAllocator calls.
CGFunctionInfo - Class to encapsulate the information about a function definition.
bool usesInAlloca() const
Return true if this function uses inalloca arguments.
FunctionType::ExtInfo getExtInfo() const
bool isReturnsRetained() const
In ARC, whether this function retains its return value.
void Profile(llvm::FoldingSetNodeID &ID)
const_arg_iterator arg_begin() const
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
CanQualType getReturnType() const
static CGFunctionInfo * create(unsigned llvmCC, bool instanceMethod, bool chainCall, bool delegateCall, const FunctionType::ExtInfo &extInfo, ArrayRef< ExtParameterInfo > paramInfos, CanQualType resultType, ArrayRef< CanQualType > argTypes, RequiredArgs required)
Definition: CGCall.cpp:829
MutableArrayRef< ArgInfo > arguments()
const_arg_iterator arg_end() const
unsigned getEffectiveCallingConvention() const
getEffectiveCallingConvention - Return the actual calling convention to use, which may depend on the ...
ExtParameterInfo getExtParameterInfo(unsigned argIndex) const
CharUnits getArgStructAlignment() const
RequiredArgs getRequiredArgs() const
unsigned getNumRequiredArgs() const
llvm::StructType * getArgStruct() const
Get the struct type used to represent all the arguments in memory.
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
const CGBitFieldInfo & getBitFieldInfo(const FieldDecl *FD) const
Return the BitFieldInfo that corresponds to the field FD.
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:274
llvm::Instruction * getStackBase() const
Definition: CGCall.h:346
void addUncopiedAggregate(LValue LV, QualType type)
Definition: CGCall.h:300
void addArgCleanupDeactivation(EHScopeStack::stable_iterator Cleanup, llvm::Instruction *IsActiveIP)
Definition: CGCall.h:333
ArrayRef< CallArgCleanup > getCleanupsToDeactivate() const
Definition: CGCall.h:341
bool hasWritebacks() const
Definition: CGCall.h:324
void add(RValue rvalue, QualType type)
Definition: CGCall.h:298
bool isUsingInAlloca() const
Returns if we're using an inalloca struct to pass arguments in memory.
Definition: CGCall.h:351
void allocateArgumentMemory(CodeGenFunction &CGF)
Definition: CGCall.cpp:4363
void freeArgumentMemory(CodeGenFunction &CGF) const
Definition: CGCall.cpp:4370
writeback_const_range writebacks() const
Definition: CGCall.h:329
void addWriteback(LValue srcLV, Address temporary, llvm::Value *toUse)
Definition: CGCall.h:319
static ParamValue forIndirect(Address addr)
static ParamValue forDirect(llvm::Value *value)
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
EHScopeStack::stable_iterator CurrentCleanupScopeDepth
llvm::Value * EmitLifetimeStart(llvm::TypeSize Size, llvm::Value *Addr)
void EmitPointerAuthOperandBundle(const CGPointerAuthInfo &Info, SmallVectorImpl< llvm::OperandBundleDef > &Bundles)
void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, llvm::Instruction *DominatingIP)
DeactivateCleanupBlock - Deactivates the given cleanup block.
llvm::Value * EmitNonNullRValueCheck(RValue RV, QualType T)
Create a check that a scalar RValue is non-null.
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
SanitizerSet SanOpts
Sanitizers enabled for this function.
void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc, AbstractCallee AC, unsigned ParmNum)
Create a check for a function parameter that may potentially be declared as non-null.
void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr)
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
static bool hasScalarEvaluationKind(QualType T)
bool isCleanupPadScope() const
Returns true while emitting a cleanuppad.
void EmitCallArgs(CallArgList &Args, PrototypeWrapper Prototype, llvm::iterator_range< CallExpr::const_arg_iterator > ArgRange, AbstractCallee AC=AbstractCallee(), unsigned ParamsToSkip=0, EvaluationOrder Order=EvaluationOrder::Default)
void EmitKCFIOperandBundle(const CGCallee &Callee, SmallVectorImpl< llvm::OperandBundleDef > &Bundles)
bool CurFuncIsThunk
In C++, whether we are code generating a thunk.
RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc)
void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, bool ForVirtualBase, bool Delegating, Address This, QualType ThisTy)
llvm::Value * EmitARCAutoreleaseReturnValue(llvm::Value *value)
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
bool isSEHTryScope() const
Returns true inside SEH __try blocks.
llvm::Value * getAsNaturalPointerTo(Address Addr, QualType PointeeType)
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
const LangOptions & getLangOpts() const
void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, SourceLocation EndLoc)
EmitFunctionEpilog - Emit the target specific LLVM code to return the given temporary.
LValue EmitLValueForFieldInitialization(LValue Base, const FieldDecl *Field)
EmitLValueForFieldInitialization - Like EmitLValueForField, except that if the Field is a reference,...
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
void EmitUnreachable(SourceLocation Loc)
Emit a reached-unreachable diagnostic if Loc is valid and runtime checking is enabled.
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
const CodeGen::CGBlockInfo * BlockInfo
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **callOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
Address makeNaturalAddressForPointer(llvm::Value *Ptr, QualType T, CharUnits Alignment=CharUnits::Zero(), bool ForPointeeType=false, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
Construct an address with the natural alignment of T.
SmallVector< llvm::OperandBundleDef, 1 > getBundlesForFunclet(llvm::Value *Callee)
void callCStructDestructor(LValue Dst)
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
RValue convertTempToRValue(Address addr, QualType type, SourceLocation Loc)
bool InNoMergeAttributedStmt
True if the current statement has nomerge attribute.
llvm::Type * ConvertTypeForMem(QualType T)
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
llvm::BasicBlock * getUnreachableBlock()
JumpDest ReturnBlock
ReturnBlock - Unified return block.
RawAddress CreateMemTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
@ ForceLeftToRight
! Language semantics require left-to-right evaluation.
@ ForceRightToLeft
! Language semantics require right-to-left evaluation.
RawAddress CreateMemTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen without...
const TargetInfo & getTarget() const
llvm::Value * EmitCMSEClearRecord(llvm::Value *V, llvm::IntegerType *ITy, QualType RTy)
llvm::Value * getTypeSize(QualType Ty)
Returns calculated size of the specified type.
void EmitFunctionProlog(const CGFunctionInfo &FI, llvm::Function *Fn, const FunctionArgList &Args)
EmitFunctionProlog - Emit the target specific LLVM code to load the arguments for the given function.
Address EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitPointerWithAlignment - Given an expression with a pointer type, emit the value and compute our be...
void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise)
RValue EmitAnyExprToTemp(const Expr *E)
EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will always be accessible even if...
void EmitReturnValueCheck(llvm::Value *RV)
Emit a test that checks if the return value RV is nonnull.
llvm::BasicBlock * getInvokeDest()
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerMask > > Checked, SanitizerHandler Check, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs)
Create a basic block that will either trap or call a handler function in the UBSan runtime with the p...
llvm::Value * EmitARCRetainAutoreleaseReturnValue(llvm::Value *value)
AggValueSlot CreateAggTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateAggTemp - Create a temporary memory object for the given aggregate type.
void EmitDelegateCallArg(CallArgList &args, const VarDecl *param, SourceLocation loc)
EmitDelegateCallArg - We are performing a delegate call; that is, the current function is delegating ...
ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc)
EmitLoadOfComplex - Load a complex number from the specified l-value.
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
Address EmitVAListRef(const Expr *E)
void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy, AggValueSlot::Overlap_t MayOverlap, bool isVolatile=false)
EmitAggregateCopy - Emit an aggregate copy.
void emitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty, SourceLocation Loc, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue=nullptr)
const TargetCodeGenInfo & getTargetHooks() const
RValue EmitReferenceBindingToExpr(const Expr *E)
Emits a reference binding to the passed in expression.
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type.
bool InNoInlineAttributedStmt
True if the current statement has noinline attribute.
void EmitAggregateStore(llvm::Value *Val, Address Dest, bool DestIsVolatile)
Build all the stores needed to initialize an aggregate at Dest with the value Val.
void SetSqrtFPAccuracy(llvm::Value *Val)
Set the minimum required accuracy of the given sqrt operation based on CodeGenOpts.
RValue EmitVAArg(VAArgExpr *VE, Address &VAListAddr, AggValueSlot Slot=AggValueSlot::ignored())
Generate code to get an argument from the passed in pointer and update it accordingly.
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
llvm::Value * EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, SourceLocation Loc, AlignmentSource Source=AlignmentSource::Type, bool isNontemporal=false)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl)
Address GetAddressOfBaseClass(Address Value, const CXXRecordDecl *Derived, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd, bool NullCheckValue, SourceLocation Loc)
GetAddressOfBaseClass - This function will add the necessary delta to the load of 'this' and returns ...
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
void PopCleanupBlock(bool FallThroughIsBranchThrough=false, bool ForDeactivation=false)
PopCleanupBlock - Will pop the cleanup entry on the stack and process all branch fixups.
bool AutoreleaseResult
In ARC, whether we should autorelease the return value.
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
llvm::Type * ConvertType(QualType T)
void EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee, ArrayRef< llvm::Value * > args)
CodeGenTypes & getTypes() const
llvm::CallBase * EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, ArrayRef< llvm::Value * > args, const Twine &name="")
llvm::CallBase * EmitCallOrInvoke(llvm::FunctionCallee Callee, ArrayRef< llvm::Value * > Args, const Twine &Name="")
bool InAlwaysInlineAttributedStmt
True if the current statement has always_inline attribute.
void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType)
EmitCallArg - Emit a single call argument.
void EmitARCIntrinsicUse(ArrayRef< llvm::Value * > values)
Address EmitMSVAListRef(const Expr *E)
Emit a "reference" to a __builtin_ms_va_list; this is always the value of the expression,...
llvm::Value * EmitARCRetainNonBlock(llvm::Value *value)
static bool hasAggregateEvaluationKind(QualType T)
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo)
EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
RValue GetUndefRValue(QualType Ty)
GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
llvm::Instruction * CurrentFuncletPad
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go.
llvm::LLVMContext & getLLVMContext()
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
CallType * addControlledConvergenceToken(CallType *Input)
This class organizes the cross-function state that is used while generating LLVM code.
llvm::MDNode * getNoObjCARCExceptionsMetadata()
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
bool ReturnTypeUsesFPRet(QualType ResultType)
Return true iff the given type uses 'fpret' when used as a return type.
Definition: CGCall.cpp:1598
DiagnosticsEngine & getDiags() const
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
const LangOptions & getLangOpts() const
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
const TargetInfo & getTarget() const
const llvm::DataLayout & getDataLayout() const
void addUndefinedGlobalForTailCall(std::pair< const FunctionDecl *, SourceLocation > Global)
ObjCEntrypoints & getObjCEntrypoints() const
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can't be done.
bool shouldEmitConvergenceTokens() const
CGCXXABI & getCXXABI() const
bool ReturnTypeUsesFP2Ret(QualType ResultType)
Return true iff the given type uses 'fp2ret' when used as a return type.
Definition: CGCall.cpp:1615
llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD)
bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI)
Return true iff the given type uses an argument slot when 'sret' is used as a return type.
Definition: CGCall.cpp:1593
bool ReturnTypeHasInReg(const CGFunctionInfo &FI)
Return true iff the given type has inreg set.
Definition: CGCall.cpp:1588
void AdjustMemoryAttribute(StringRef Name, CGCalleeInfo CalleeInfo, llvm::AttributeList &Attrs)
Adjust Memory attribute to ensure that the BE gets the right attribute.
Definition: CGCall.cpp:2308
void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info, CGCalleeInfo CalleeInfo, llvm::AttributeList &Attrs, unsigned &CallingConv, bool AttrOnCallSite, bool IsThunk)
Get the LLVM attributes and calling convention to use for a particular function type.
Definition: CGCall.cpp:2336
ASTContext & getContext() const
bool ReturnTypeUsesSRet(const CGFunctionInfo &FI)
Return true iff the given type uses 'sret' when used as a return type.
Definition: CGCall.cpp:1583
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
void addDefaultFunctionDefinitionAttributes(llvm::AttrBuilder &attrs)
Like the overload taking a Function &, but intended specifically for frontends that want to build on ...
Definition: CGCall.cpp:2161
CharUnits getNaturalPointeeTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
llvm::LLVMContext & getLLVMContext()
CharUnits getMinimumObjectSize(QualType Ty)
Returns the minimum object size for an object of the given type.
bool MayDropFunctionReturn(const ASTContext &Context, QualType ReturnType) const
Whether this function's return type has no side effects, and thus may be trivially discarded if it is...
Definition: CGCall.cpp:1821
void valueProfile(CGBuilderTy &Builder, uint32_t ValueKind, llvm::Instruction *ValueSite, llvm::Value *ValuePtr)
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
Definition: CodeGenTypes.h:54
const CGFunctionInfo & arrangeCXXMethodType(const CXXRecordDecl *RD, const FunctionProtoType *FTP, const CXXMethodDecl *MD)
Arrange the argument and result information for a call to an unknown C++ non-static member function o...
Definition: CGCall.cpp:279
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
const CGFunctionInfo & arrangeCXXMethodDeclaration(const CXXMethodDecl *MD)
C++ methods have some special rules and also have implicit parameters.
Definition: CGCall.cpp:307
ASTContext & getContext() const
Definition: CodeGenTypes.h:108
const CGFunctionInfo & arrangeLLVMFunctionInfo(CanQualType returnType, FnInfoOpts opts, ArrayRef< CanQualType > argTypes, FunctionType::ExtInfo info, ArrayRef< FunctionProtoType::ExtParameterInfo > paramInfos, RequiredArgs args)
"Arrange" the LLVM information for a call or type with the given signature.
Definition: CGCall.cpp:766
const ABIInfo & getABIInfo() const
Definition: CodeGenTypes.h:109
const CGFunctionInfo & arrangeFreeFunctionType(CanQual< FunctionProtoType > Ty)
Arrange the argument and result information for a value of the given freestanding function type.
Definition: CGCall.cpp:206
CanQualType DeriveThisType(const CXXRecordDecl *RD, const CXXMethodDecl *MD)
Derives the 'this' type for codegen purposes, i.e.
Definition: CGCall.cpp:87
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1632
bool inheritingCtorHasParams(const InheritedConstructor &Inherited, CXXCtorType Type)
Determine if a C++ inheriting constructor should have parameters matching those of its inherited cons...
Definition: CGCall.cpp:324
bool isFuncTypeConvertible(const FunctionType *FT)
isFuncTypeConvertible - Utility to check whether a function type can be converted to an LLVM type (i....
const CGFunctionInfo & arrangeBlockFunctionCall(const CallArgList &args, const FunctionType *type)
A block function is essentially a free function with an extra implicit argument.
Definition: CGCall.cpp:649
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
Definition: CGCall.cpp:680
const CGFunctionInfo & arrangeUnprototypedObjCMessageSend(QualType returnType, const CallArgList &args)
Definition: CGCall.cpp:533
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
unsigned getTargetAddressSpace(QualType T) const
void getExpandedTypes(QualType Ty, SmallVectorImpl< llvm::Type * >::iterator &TI)
getExpandedTypes - Expand the type
Definition: CGCall.cpp:1014
const CGFunctionInfo & arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD)
Objective-C methods are C functions with some implicit parameters.
Definition: CGCall.cpp:487
llvm::LLVMContext & getLLVMContext()
Definition: CodeGenTypes.h:112
const CGFunctionInfo & arrangeGlobalDeclaration(GlobalDecl GD)
Definition: CGCall.cpp:543
const CGFunctionInfo & arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD)
Arrange a thunk that takes 'this' as the first parameter followed by varargs.
Definition: CGCall.cpp:560
const CGFunctionInfo & arrangeCXXMethodCall(const CallArgList &args, const FunctionProtoType *type, RequiredArgs required, unsigned numPrefixArgs)
Arrange a call to a C++ method, passing the given arguments.
Definition: CGCall.cpp:702
const CGFunctionInfo & arrangeFreeFunctionCall(const CallArgList &Args, const FunctionType *Ty, bool ChainCall)
Figure out the rules for calling a function with the given formal type using the given arguments.
Definition: CGCall.cpp:639
const CGFunctionInfo & arrangeBuiltinFunctionCall(QualType resultType, const CallArgList &args)
Definition: CGCall.cpp:668
const CGFunctionInfo & arrangeFunctionDeclaration(const FunctionDecl *FD)
Free functions are functions that are compatible with an ordinary C function pointer type.
Definition: CGCall.cpp:463
const CGFunctionInfo & arrangeBlockFunctionDeclaration(const FunctionProtoType *type, const FunctionArgList &args)
Block invocation functions are C functions with an implicit parameter.
Definition: CGCall.cpp:656
unsigned ClangCallConvToLLVMCallConv(CallingConv CC)
Convert clang calling convention to LLVM callilng convention.
Definition: CGCall.cpp:50
llvm::Type * GetFunctionTypeForVTable(GlobalDecl GD)
GetFunctionTypeForVTable - Get the LLVM function type for use in a vtable, given a CXXMethodDecl.
Definition: CGCall.cpp:1759
const CGFunctionInfo & arrangeCXXConstructorCall(const CallArgList &Args, const CXXConstructorDecl *D, CXXCtorType CtorKind, unsigned ExtraPrefixArgs, unsigned ExtraSuffixArgs, bool PassProtoArgs=true)
Arrange a call to a C++ method, passing the given arguments.
Definition: CGCall.cpp:419
const CGFunctionInfo & arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD, QualType receiverType)
Arrange the argument and result information for the function type through which to perform a send to ...
Definition: CGCall.cpp:500
const CGFunctionInfo & arrangeCXXStructorDeclaration(GlobalDecl GD)
Definition: CGCall.cpp:334
const CGFunctionInfo & arrangeMSCtorClosure(const CXXConstructorDecl *CD, CXXCtorType CT)
Definition: CGCall.cpp:569
const CGFunctionInfo & arrangeCall(const CGFunctionInfo &declFI, const CallArgList &args)
Given a function info for a declaration, return the function info for a call with the given arguments...
Definition: CGCall.cpp:729
const CGFunctionInfo & arrangeNullaryFunction()
A nullary function is a freestanding function of type 'void ()'.
Definition: CGCall.cpp:722
A cleanup scope which generates the cleanup blocks lazily.
Definition: CGCleanup.h:243
EHScopeStack::Cleanup * getCleanup()
Definition: CGCleanup.h:418
Information for lazily generating a cleanup.
Definition: EHScopeStack.h:141
A saved depth on the scope stack.
Definition: EHScopeStack.h:101
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
Definition: EHScopeStack.h:393
iterator end() const
Returns an iterator pointing to the outermost EH scope.
Definition: CGCleanup.h:619
iterator find(stable_iterator save) const
Turn a stable reference to a scope depth into a unstable pointer to the EH stack.
Definition: CGCleanup.h:639
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition: CGCall.h:368
LValue - This represents an lvalue references.
Definition: CGValue.h:182
bool isBitField() const
Definition: CGValue.h:280
bool isSimple() const
Definition: CGValue.h:278
bool isVolatileQualified() const
Definition: CGValue.h:285
LangAS getAddressSpace() const
Definition: CGValue.h:341
CharUnits getAlignment() const
Definition: CGValue.h:343
static LValue MakeAddr(Address Addr, QualType type, ASTContext &Context, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition: CGValue.h:432
bool isVolatile() const
Definition: CGValue.h:328
Address getAddress() const
Definition: CGValue.h:361
ARCPreciseLifetime_t isARCPreciseLifetime() const
Definition: CGValue.h:312
Qualifiers::ObjCLifetime getObjCLifetime() const
Definition: CGValue.h:293
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition: CGValue.h:42
bool isScalar() const
Definition: CGValue.h:64
static RValue get(llvm::Value *V)
Definition: CGValue.h:98
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
Definition: CGValue.h:125
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Definition: CGValue.h:108
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
Definition: CGValue.h:83
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition: CGValue.h:71
bool isComplex() const
Definition: CGValue.h:65
bool isVolatileQualified() const
Definition: CGValue.h:68
std::pair< llvm::Value *, llvm::Value * > getComplexVal() const
getComplexVal - Return the real/imag components of this complex value.
Definition: CGValue.h:78
An abstract representation of an aligned address.
Definition: Address.h:42
CharUnits getAlignment() const
Return the alignment of this pointer.
Definition: Address.h:93
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition: Address.h:77
llvm::Value * getPointer() const
Definition: Address.h:66
static RawAddress invalid()
Definition: Address.h:61
bool isValid() const
Definition: Address.h:62
A class for recording the number of arguments that a function signature requires.
unsigned getNumRequiredArgs() const
static RequiredArgs forPrototypePlus(const FunctionProtoType *prototype, unsigned additional)
Compute the arguments required by the given formal prototype, given that there may be some additional...
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition: CGCall.h:372
virtual bool doesReturnSlotInterfereWithArgs() const
doesReturnSlotInterfereWithArgs - Return true if the target uses an argument slot for an 'sret' type.
Definition: TargetInfo.h:195
virtual void setCUDAKernelCallingConvention(const FunctionType *&FT) const
Definition: TargetInfo.h:378
Address performAddrSpaceCast(CodeGen::CodeGenFunction &CGF, Address Addr, LangAS SrcAddr, LangAS DestAddr, llvm::Type *DestTy, bool IsNonNull=false) const
static void setBranchProtectionFnAttributes(const TargetInfo::BranchProtectionInfo &BPI, llvm::Function &F)
Definition: TargetInfo.cpp:210
virtual void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller, const FunctionDecl *Callee, const CallArgList &Args, QualType ReturnType) const
Any further codegen related checks that need to be done on a function call in a target specific manne...
Definition: TargetInfo.h:95
virtual unsigned getOpenCLKernelCallingConv() const
Get LLVM calling convention for OpenCL kernel.
Definition: TargetInfo.cpp:106
virtual bool isNoProtoCallVariadic(const CodeGen::CallArgList &args, const FunctionNoProtoType *fnType) const
Determine whether a call to an unprototyped functions under the given calling convention should use t...
Definition: TargetInfo.cpp:87
Complex values, per C99 6.2.5p11.
Definition: Type.h:3108
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3578
bool constructsVirtualBase() const
Returns true if the constructed base class is a virtual base class subobject of this declaration's cl...
Definition: DeclCXX.h:3698
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1425
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
T * getAttr() const
Definition: DeclBase.h:579
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:565
DeclContext * getDeclContext()
Definition: DeclBase.h:454
bool hasAttr() const
Definition: DeclBase.h:583
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:783
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1547
This represents one expression.
Definition: Expr.h:110
bool isGLValue() const
Definition: Expr.h:280
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3066
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:830
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:444
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:3941
QualType getType() const
Definition: Expr.h:142
Represents a member of a struct/union/class.
Definition: Decl.h:3030
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3121
bool isZeroLengthBitField(const ASTContext &Ctx) const
Is this a zero-length bit-field? Such bit-fields aren't really bit-fields at all and instead act as a...
Definition: Decl.cpp:4585
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition: Decl.h:3124
Represents a function declaration or definition.
Definition: Decl.h:1932
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2302
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4638
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4973
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5253
unsigned getNumParams() const
Definition: Type.h:5226
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition: Type.h:5432
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5350
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.h:5345
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition: Type.h:5415
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:5411
Wrapper for source info for functions.
Definition: TypeLoc.h:1428
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4389
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4504
CallingConv getCC() const
Definition: Type.h:4451
ExtInfo withProducesResult(bool producesResult) const
Definition: Type.h:4470
bool getCmseNSCall() const
Definition: Type.h:4439
bool getNoCfCheck() const
Definition: Type.h:4441
unsigned getRegParm() const
Definition: Type.h:4444
bool getNoCallerSavedRegs() const
Definition: Type.h:4440
bool getHasRegParm() const
Definition: Type.h:4442
bool getNoReturn() const
Definition: Type.h:4437
bool getProducesResult() const
Definition: Type.h:4438
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: Type.h:4304
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition: Type.h:4317
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition: Type.h:4344
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4278
ExtInfo getExtInfo() const
Definition: Type.h:4612
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition: Type.h:4570
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition: Type.h:4566
QualType getReturnType() const
Definition: Type.h:4600
@ SME_PStateSMEnabledMask
Definition: Type.h:4544
@ SME_PStateSMCompatibleMask
Definition: Type.h:4545
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
CXXCtorType getCtorType() const
Definition: GlobalDecl.h:105
const Decl * getDecl() const
Definition: GlobalDecl.h:103
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2506
ConstructorUsingShadowDecl * getShadowDecl() const
Definition: DeclCXX.h:2518
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Definition: LangOptions.h:278
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
std::vector< std::string > NoBuiltinFuncs
A list of all -fno-builtin-* function names (e.g., memset).
Definition: LangOptions.h:528
FPExceptionModeKind getDefaultExceptionMode() const
Definition: LangOptions.h:757
bool isNoBuiltinFunc(StringRef Name) const
Is this a libc/libm function that is no longer recognized as a builtin because a -fno-builtin-* optio...
Definition: LangOptions.cpp:49
bool assumeFunctionsAreConvergent() const
Definition: LangOptions.h:646
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition: Type.h:4153
Describes a module or submodule.
Definition: Module.h:105
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2326
ObjCIndirectCopyRestoreExpr - Represents the passing of a function argument by indirect copy-restore ...
Definition: ExprObjC.h:1575
bool shouldCopy() const
shouldCopy - True if we should do the 'copy' part of the copy-restore.
Definition: ExprObjC.h:1603
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:418
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:373
bool isVariadic() const
Definition: DeclObjC.h:431
bool isDirectMethod() const
True if the method is tagged as objc_direct.
Definition: DeclObjC.cpp:871
QualType getReturnType() const
Definition: DeclObjC.h:329
Represents a parameter to a function.
Definition: Decl.h:1722
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3161
QualType getPointeeType() const
Definition: Type.h:3171
A (possibly-)qualified type.
Definition: Type.h:941
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:7821
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2748
@ DK_cxx_destructor
Definition: Type.h:1532
@ DK_nontrivial_c_struct
Definition: Type.h:1535
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7869
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7783
QualType getCanonicalType() const
Definition: Type.h:7795
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7816
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1542
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:348
LangAS getAddressSpace() const
Definition: Type.h:558
Represents a struct/union/class.
Definition: Decl.h:4141
bool hasFlexibleArrayMember() const
Definition: Decl.h:4174
field_iterator field_end() const
Definition: Decl.h:4350
field_range fields() const
Definition: Decl.h:4347
bool isParamDestroyedInCallee() const
Definition: Decl.h:4283
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4332
field_iterator field_begin() const
Definition: Decl.cpp:5057
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5936
RecordDecl * getDecl() const
Definition: Type.h:5946
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3402
Encodes a location in the source.
UIntTy getRawEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) 32-bit integer encoding for it.
bool isUnion() const
Definition: Decl.h:3763
bool areArgsDestroyedLeftToRightInCallee() const
Are arguments to a call destroyed left to right in the callee? This is a fundamental language change,...
Definition: TargetCXXABI.h:188
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
bool useObjCFPRetForRealType(FloatModeKind T) const
Check whether the given real type should use the "fpret" flavor of Objective-C message passing on thi...
Definition: TargetInfo.h:978
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
bool useObjCFP2RetForComplexLongDouble() const
Check whether _Complex long double should use the "fp2ret" flavor of Objective-C message passing on t...
Definition: TargetInfo.h:984
Options for controlling the target.
Definition: TargetOptions.h:26
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
Definition: TargetOptions.h:58
std::string TuneCPU
If given, the name of the target CPU to tune code for.
Definition: TargetOptions.h:39
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:36
The base class of the type hierarchy.
Definition: Type.h:1829
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isBlockPointerType() const
Definition: Type.h:8006
bool isVoidType() const
Definition: Type.h:8295
bool isIncompleteArrayType() const
Definition: Type.h:8072
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2352
bool isPointerType() const
Definition: Type.h:7996
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8335
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8583
bool isReferenceType() const
Definition: Type.h:8010
bool isScalarType() const
Definition: Type.h:8394
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isBitIntType() const
Definition: Type.h:8230
QualType getCanonicalTypeInternal() const
Definition: Type.h:2955
bool isMemberPointerType() const
Definition: Type.h:8046
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2421
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2362
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition: Type.cpp:2258
bool isAnyPointerType() const
Definition: Type.h:8000
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8516
bool isNullPtrType() const
Definition: Type.h:8328
bool isObjCRetainableType() const
Definition: Type.cpp:4941
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1886
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2188
Represents a call to the builtin function __builtin_va_arg.
Definition: Expr.h:4691
bool isMicrosoftABI() const
Returns whether this is really a Win64 ABI va_arg expression.
Definition: Expr.h:4712
const Expr * getSubExpr() const
Definition: Expr.h:4707
QualType getType() const
Definition: Decl.h:678
Represents a variable declaration or definition.
Definition: Decl.h:879
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition: Decl.cpp:2808
Represents a GCC generic vector type.
Definition: Type.h:3991
Defines the clang::TargetInfo interface.
void computeABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI)
Compute the ABI information of a swiftcall function.
void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI)
Definition: SPIR.cpp:112
@ NormalCleanup
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
Definition: EHScopeStack.h:84
void mergeDefaultFunctionDefinitionAttributes(llvm::Function &F, const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, const TargetOptions &TargetOpts, bool WillInternalize)
Adds attributes to F according to our CodeGenOpts and LangOpts, as though we had emitted it ourselves...
Definition: CGCall.cpp:2078
bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays, bool AsIfNoUniqueAddr=false)
isEmptyRecord - Return true iff a structure contains only empty fields.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
Definition: Format.cpp:3819
bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
Definition: Interp.h:275
bool This(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2230
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2204
bool Load(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1663
The JSON file list parser is used to communicate input to InstallAPI.
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
CXXCtorType
C++ constructor types.
Definition: ABI.h:24
@ Ctor_DefaultClosure
Default closure variant of a ctor.
Definition: ABI.h:29
@ Ctor_CopyingClosure
Copying closure variant of a ctor.
Definition: ABI.h:28
@ Ctor_Complete
Complete object ctor.
Definition: ABI.h:25
@ OpenCL
Definition: LangStandard.h:66
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
bool isInstanceMethod(const Decl *D)
Definition: Attr.h:120
@ NonNull
Values of this type can never be null.
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:148
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:24
@ Result
The result type of a method or function.
@ SwiftAsyncContext
This parameter (which must have pointer type) uses the special Swift asynchronous context-pointer ABI...
@ SwiftErrorResult
This parameter (which must have pointer-to-pointer type) uses the special Swift error-result ABI trea...
@ Ordinary
This parameter uses ordinary ABI rules for its type.
@ SwiftIndirectResult
This parameter (which must have pointer type) is a Swift indirect result parameter.
@ SwiftContext
This parameter (which must have pointer type) uses the special Swift context-pointer ABI treatment.
@ Dtor_Complete
Complete object dtor.
Definition: ABI.h:35
@ CanPassInRegs
The argument of this type can be passed directly in registers.
const FunctionProtoType * T
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_X86Pascal
Definition: Specifiers.h:281
@ CC_Swift
Definition: Specifiers.h:290
@ CC_IntelOclBicc
Definition: Specifiers.h:287
@ CC_OpenCLKernel
Definition: Specifiers.h:289
@ CC_PreserveMost
Definition: Specifiers.h:292
@ CC_Win64
Definition: Specifiers.h:282
@ CC_X86ThisCall
Definition: Specifiers.h:279
@ CC_AArch64VectorCall
Definition: Specifiers.h:294
@ CC_AAPCS
Definition: Specifiers.h:285
@ CC_PreserveNone
Definition: Specifiers.h:298
@ CC_C
Definition: Specifiers.h:276
@ CC_AMDGPUKernelCall
Definition: Specifiers.h:296
@ CC_M68kRTD
Definition: Specifiers.h:297
@ CC_SwiftAsync
Definition: Specifiers.h:291
@ CC_X86RegCall
Definition: Specifiers.h:284
@ CC_RISCVVectorCall
Definition: Specifiers.h:299
@ CC_X86VectorCall
Definition: Specifiers.h:280
@ CC_SpirFunction
Definition: Specifiers.h:288
@ CC_AArch64SVEPCS
Definition: Specifiers.h:295
@ CC_X86StdCall
Definition: Specifiers.h:277
@ CC_X86_64SysV
Definition: Specifiers.h:283
@ CC_PreserveAll
Definition: Specifiers.h:293
@ CC_X86FastCall
Definition: Specifiers.h:278
@ CC_AAPCS_VFP
Definition: Specifiers.h:286
unsigned long uint64_t
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
Definition: complex_cmath.h:40
Structure with information about how a bitfield should be accessed.
CharUnits StorageOffset
The offset of the bitfield storage from the start of the struct.
unsigned Offset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
unsigned Size
The total size of the bit-field, in bits.
unsigned StorageSize
The storage size in bits which should be used when accessing this bitfield.
Similar to AddedStructorArgs, but only notes the number of additional arguments.
Definition: CGCXXABI.h:350
llvm::Value * ToUse
A value to "use" after the writeback, or null.
Definition: CGCall.h:287
LValue Source
The original argument.
Definition: CGCall.h:281
Address Temporary
The temporary alloca.
Definition: CGCall.h:284
LValue getKnownLValue() const
Definition: CGCall.h:254
RValue getKnownRValue() const
Definition: CGCall.h:258
void copyInto(CodeGenFunction &CGF, Address A) const
Definition: CGCall.cpp:4663
bool hasLValue() const
Definition: CGCall.h:247
RValue getRValue(CodeGenFunction &CGF) const
Definition: CGCall.cpp:4653
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::CallingConv::ID getRuntimeCC() const
bool isMSVCXXPersonality() const
Definition: CGCleanup.h:695
static const EHPersonality & get(CodeGenModule &CGM, const FunctionDecl *FD)
llvm::Function * objc_retainAutoreleasedReturnValue
id objc_retainAutoreleasedReturnValue(id);
llvm::Function * objc_retain
id objc_retain(id);
llvm::InlineAsm * retainAutoreleasedReturnValueMarker
A void(void) inline asm to use to mark that the return value of a call will be immediately retain.
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:159
bool hasOneOf(SanitizerMask K) const
Check if one or more sanitizers are enabled.
Definition: Sanitizers.h:165
Iterator for iterating over Stmt * arrays that contain only T *.
Definition: Stmt.h:1316