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
1339void CodeGenFunction::CreateCoercedStore(llvm::Value *Src, Address Dst,
1340 llvm::TypeSize DstSize,
1341 bool DstIsVolatile) {
1342 if (!DstSize)
1343 return;
1344
1345 llvm::Type *SrcTy = Src->getType();
1346 llvm::TypeSize SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
1347
1348 // GEP into structs to try to make types match.
1349 // FIXME: This isn't really that useful with opaque types, but it impacts a
1350 // lot of regression tests.
1351 if (SrcTy != Dst.getElementType()) {
1352 if (llvm::StructType *DstSTy =
1353 dyn_cast<llvm::StructType>(Dst.getElementType())) {
1354 assert(!SrcSize.isScalable());
1355 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy,
1356 SrcSize.getFixedValue(), *this);
1357 }
1358 }
1359
1360 if (SrcSize.isScalable() || SrcSize <= DstSize) {
1361 if (SrcTy->isIntegerTy() && Dst.getElementType()->isPointerTy() &&
1362 SrcSize == CGM.getDataLayout().getTypeAllocSize(Dst.getElementType())) {
1363 // If the value is supposed to be a pointer, convert it before storing it.
1364 Src = CoerceIntOrPtrToIntOrPtr(Src, Dst.getElementType(), *this);
1365 Builder.CreateStore(Src, Dst, DstIsVolatile);
1366 } else if (llvm::StructType *STy =
1367 dyn_cast<llvm::StructType>(Src->getType())) {
1368 // Prefer scalar stores to first-class aggregate stores.
1369 Dst = Dst.withElementType(SrcTy);
1370 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1371 Address EltPtr = Builder.CreateStructGEP(Dst, i);
1372 llvm::Value *Elt = Builder.CreateExtractValue(Src, i);
1373 Builder.CreateStore(Elt, EltPtr, DstIsVolatile);
1374 }
1375 } else {
1376 Builder.CreateStore(Src, Dst.withElementType(SrcTy), DstIsVolatile);
1377 }
1378 } else if (SrcTy->isIntegerTy()) {
1379 // If the source is a simple integer, coerce it directly.
1380 llvm::Type *DstIntTy = Builder.getIntNTy(DstSize.getFixedValue() * 8);
1381 Src = CoerceIntOrPtrToIntOrPtr(Src, DstIntTy, *this);
1382 Builder.CreateStore(Src, Dst.withElementType(DstIntTy), DstIsVolatile);
1383 } else {
1384 // Otherwise do coercion through memory. This is stupid, but
1385 // simple.
1386
1387 // Generally SrcSize is never greater than DstSize, since this means we are
1388 // losing bits. However, this can happen in cases where the structure has
1389 // additional padding, for example due to a user specified alignment.
1390 //
1391 // FIXME: Assert that we aren't truncating non-padding bits when have access
1392 // to that information.
1393 RawAddress Tmp =
1394 CreateTempAllocaForCoercion(*this, SrcTy, Dst.getAlignment());
1395 Builder.CreateStore(Src, Tmp);
1397 Dst.getAlignment().getAsAlign(), Tmp.getPointer(),
1398 Tmp.getAlignment().getAsAlign(),
1399 Builder.CreateTypeSize(IntPtrTy, DstSize));
1400 }
1401}
1402
1404 const ABIArgInfo &info) {
1405 if (unsigned offset = info.getDirectOffset()) {
1406 addr = addr.withElementType(CGF.Int8Ty);
1407 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1408 CharUnits::fromQuantity(offset));
1409 addr = addr.withElementType(info.getCoerceToType());
1410 }
1411 return addr;
1412}
1413
1414namespace {
1415
1416/// Encapsulates information about the way function arguments from
1417/// CGFunctionInfo should be passed to actual LLVM IR function.
1418class ClangToLLVMArgMapping {
1419 static const unsigned InvalidIndex = ~0U;
1420 unsigned InallocaArgNo;
1421 unsigned SRetArgNo;
1422 unsigned TotalIRArgs;
1423
1424 /// Arguments of LLVM IR function corresponding to single Clang argument.
1425 struct IRArgs {
1426 unsigned PaddingArgIndex;
1427 // Argument is expanded to IR arguments at positions
1428 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1429 unsigned FirstArgIndex;
1430 unsigned NumberOfArgs;
1431
1432 IRArgs()
1433 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1434 NumberOfArgs(0) {}
1435 };
1436
1437 SmallVector<IRArgs, 8> ArgInfo;
1438
1439public:
1440 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1441 bool OnlyRequiredArgs = false)
1442 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1443 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1444 construct(Context, FI, OnlyRequiredArgs);
1445 }
1446
1447 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1448 unsigned getInallocaArgNo() const {
1449 assert(hasInallocaArg());
1450 return InallocaArgNo;
1451 }
1452
1453 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1454 unsigned getSRetArgNo() const {
1455 assert(hasSRetArg());
1456 return SRetArgNo;
1457 }
1458
1459 unsigned totalIRArgs() const { return TotalIRArgs; }
1460
1461 bool hasPaddingArg(unsigned ArgNo) const {
1462 assert(ArgNo < ArgInfo.size());
1463 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1464 }
1465 unsigned getPaddingArgNo(unsigned ArgNo) const {
1466 assert(hasPaddingArg(ArgNo));
1467 return ArgInfo[ArgNo].PaddingArgIndex;
1468 }
1469
1470 /// Returns index of first IR argument corresponding to ArgNo, and their
1471 /// quantity.
1472 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1473 assert(ArgNo < ArgInfo.size());
1474 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1475 ArgInfo[ArgNo].NumberOfArgs);
1476 }
1477
1478private:
1479 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1480 bool OnlyRequiredArgs);
1481};
1482
1483void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1484 const CGFunctionInfo &FI,
1485 bool OnlyRequiredArgs) {
1486 unsigned IRArgNo = 0;
1487 bool SwapThisWithSRet = false;
1488 const ABIArgInfo &RetAI = FI.getReturnInfo();
1489
1490 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1491 SwapThisWithSRet = RetAI.isSRetAfterThis();
1492 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1493 }
1494
1495 unsigned ArgNo = 0;
1496 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1497 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1498 ++I, ++ArgNo) {
1499 assert(I != FI.arg_end());
1500 QualType ArgType = I->type;
1501 const ABIArgInfo &AI = I->info;
1502 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1503 auto &IRArgs = ArgInfo[ArgNo];
1504
1505 if (AI.getPaddingType())
1506 IRArgs.PaddingArgIndex = IRArgNo++;
1507
1508 switch (AI.getKind()) {
1509 case ABIArgInfo::Extend:
1510 case ABIArgInfo::Direct: {
1511 // FIXME: handle sseregparm someday...
1512 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1513 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1514 IRArgs.NumberOfArgs = STy->getNumElements();
1515 } else {
1516 IRArgs.NumberOfArgs = 1;
1517 }
1518 break;
1519 }
1522 IRArgs.NumberOfArgs = 1;
1523 break;
1524 case ABIArgInfo::Ignore:
1526 // ignore and inalloca doesn't have matching LLVM parameters.
1527 IRArgs.NumberOfArgs = 0;
1528 break;
1530 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1531 break;
1532 case ABIArgInfo::Expand:
1533 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1534 break;
1535 }
1536
1537 if (IRArgs.NumberOfArgs > 0) {
1538 IRArgs.FirstArgIndex = IRArgNo;
1539 IRArgNo += IRArgs.NumberOfArgs;
1540 }
1541
1542 // Skip over the sret parameter when it comes second. We already handled it
1543 // above.
1544 if (IRArgNo == 1 && SwapThisWithSRet)
1545 IRArgNo++;
1546 }
1547 assert(ArgNo == ArgInfo.size());
1548
1549 if (FI.usesInAlloca())
1550 InallocaArgNo = IRArgNo++;
1551
1552 TotalIRArgs = IRArgNo;
1553}
1554} // namespace
1555
1556/***/
1557
1559 const auto &RI = FI.getReturnInfo();
1560 return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet());
1561}
1562
1564 const auto &RI = FI.getReturnInfo();
1565 return RI.getInReg();
1566}
1567
1569 return ReturnTypeUsesSRet(FI) &&
1571}
1572
1574 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1575 switch (BT->getKind()) {
1576 default:
1577 return false;
1578 case BuiltinType::Float:
1580 case BuiltinType::Double:
1582 case BuiltinType::LongDouble:
1584 }
1585 }
1586
1587 return false;
1588}
1589
1591 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1592 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1593 if (BT->getKind() == BuiltinType::LongDouble)
1595 }
1596 }
1597
1598 return false;
1599}
1600
1603 return GetFunctionType(FI);
1604}
1605
1606llvm::FunctionType *
1608
1609 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1610 (void)Inserted;
1611 assert(Inserted && "Recursively being processed?");
1612
1613 llvm::Type *resultType = nullptr;
1614 const ABIArgInfo &retAI = FI.getReturnInfo();
1615 switch (retAI.getKind()) {
1616 case ABIArgInfo::Expand:
1618 llvm_unreachable("Invalid ABI kind for return argument");
1619
1620 case ABIArgInfo::Extend:
1621 case ABIArgInfo::Direct:
1622 resultType = retAI.getCoerceToType();
1623 break;
1624
1626 if (retAI.getInAllocaSRet()) {
1627 // sret things on win32 aren't void, they return the sret pointer.
1628 QualType ret = FI.getReturnType();
1629 unsigned addressSpace = CGM.getTypes().getTargetAddressSpace(ret);
1630 resultType = llvm::PointerType::get(getLLVMContext(), addressSpace);
1631 } else {
1632 resultType = llvm::Type::getVoidTy(getLLVMContext());
1633 }
1634 break;
1635
1637 case ABIArgInfo::Ignore:
1638 resultType = llvm::Type::getVoidTy(getLLVMContext());
1639 break;
1640
1642 resultType = retAI.getUnpaddedCoerceAndExpandType();
1643 break;
1644 }
1645
1646 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1647 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1648
1649 // Add type for sret argument.
1650 if (IRFunctionArgs.hasSRetArg()) {
1651 QualType Ret = FI.getReturnType();
1652 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(Ret);
1653 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1654 llvm::PointerType::get(getLLVMContext(), AddressSpace);
1655 }
1656
1657 // Add type for inalloca argument.
1658 if (IRFunctionArgs.hasInallocaArg())
1659 ArgTypes[IRFunctionArgs.getInallocaArgNo()] =
1660 llvm::PointerType::getUnqual(getLLVMContext());
1661
1662 // Add in all of the required arguments.
1663 unsigned ArgNo = 0;
1665 ie = it + FI.getNumRequiredArgs();
1666 for (; it != ie; ++it, ++ArgNo) {
1667 const ABIArgInfo &ArgInfo = it->info;
1668
1669 // Insert a padding type to ensure proper alignment.
1670 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1671 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1672 ArgInfo.getPaddingType();
1673
1674 unsigned FirstIRArg, NumIRArgs;
1675 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1676
1677 switch (ArgInfo.getKind()) {
1678 case ABIArgInfo::Ignore:
1680 assert(NumIRArgs == 0);
1681 break;
1682
1684 assert(NumIRArgs == 1);
1685 // indirect arguments are always on the stack, which is alloca addr space.
1686 ArgTypes[FirstIRArg] = llvm::PointerType::get(
1687 getLLVMContext(), CGM.getDataLayout().getAllocaAddrSpace());
1688 break;
1690 assert(NumIRArgs == 1);
1691 ArgTypes[FirstIRArg] = llvm::PointerType::get(
1693 break;
1694 case ABIArgInfo::Extend:
1695 case ABIArgInfo::Direct: {
1696 // Fast-isel and the optimizer generally like scalar values better than
1697 // FCAs, so we flatten them if this is safe to do for this argument.
1698 llvm::Type *argType = ArgInfo.getCoerceToType();
1699 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
1700 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1701 assert(NumIRArgs == st->getNumElements());
1702 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
1703 ArgTypes[FirstIRArg + i] = st->getElementType(i);
1704 } else {
1705 assert(NumIRArgs == 1);
1706 ArgTypes[FirstIRArg] = argType;
1707 }
1708 break;
1709 }
1710
1712 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1713 for (auto *EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1714 *ArgTypesIter++ = EltTy;
1715 }
1716 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1717 break;
1718 }
1719
1720 case ABIArgInfo::Expand:
1721 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1722 getExpandedTypes(it->type, ArgTypesIter);
1723 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1724 break;
1725 }
1726 }
1727
1728 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1729 assert(Erased && "Not in set?");
1730
1731 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
1732}
1733
1735 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1736 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1737
1738 if (!isFuncTypeConvertible(FPT))
1739 return llvm::StructType::get(getLLVMContext());
1740
1741 return GetFunctionType(GD);
1742}
1743
1745 llvm::AttrBuilder &FuncAttrs,
1746 const FunctionProtoType *FPT) {
1747 if (!FPT)
1748 return;
1749
1751 FPT->isNothrow())
1752 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1753
1754 unsigned SMEBits = FPT->getAArch64SMEAttributes();
1756 FuncAttrs.addAttribute("aarch64_pstate_sm_enabled");
1758 FuncAttrs.addAttribute("aarch64_pstate_sm_compatible");
1759
1760 // ZA
1762 FuncAttrs.addAttribute("aarch64_preserves_za");
1764 FuncAttrs.addAttribute("aarch64_in_za");
1766 FuncAttrs.addAttribute("aarch64_out_za");
1768 FuncAttrs.addAttribute("aarch64_inout_za");
1769
1770 // ZT0
1772 FuncAttrs.addAttribute("aarch64_preserves_zt0");
1774 FuncAttrs.addAttribute("aarch64_in_zt0");
1776 FuncAttrs.addAttribute("aarch64_out_zt0");
1778 FuncAttrs.addAttribute("aarch64_inout_zt0");
1779}
1780
1781static void AddAttributesFromOMPAssumes(llvm::AttrBuilder &FuncAttrs,
1782 const Decl *Callee) {
1783 if (!Callee)
1784 return;
1785
1787
1788 for (const OMPAssumeAttr *AA : Callee->specific_attrs<OMPAssumeAttr>())
1789 AA->getAssumption().split(Attrs, ",");
1790
1791 if (!Attrs.empty())
1792 FuncAttrs.addAttribute(llvm::AssumptionAttrKey,
1793 llvm::join(Attrs.begin(), Attrs.end(), ","));
1794}
1795
1797 QualType ReturnType) const {
1798 // We can't just discard the return value for a record type with a
1799 // complex destructor or a non-trivially copyable type.
1800 if (const RecordType *RT =
1801 ReturnType.getCanonicalType()->getAs<RecordType>()) {
1802 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1803 return ClassDecl->hasTrivialDestructor();
1804 }
1805 return ReturnType.isTriviallyCopyableType(Context);
1806}
1807
1809 const Decl *TargetDecl) {
1810 // As-is msan can not tolerate noundef mismatch between caller and
1811 // implementation. Mismatch is possible for e.g. indirect calls from C-caller
1812 // into C++. Such mismatches lead to confusing false reports. To avoid
1813 // expensive workaround on msan we enforce initialization event in uncommon
1814 // cases where it's allowed.
1815 if (Module.getLangOpts().Sanitize.has(SanitizerKind::Memory))
1816 return true;
1817 // C++ explicitly makes returning undefined values UB. C's rule only applies
1818 // to used values, so we never mark them noundef for now.
1819 if (!Module.getLangOpts().CPlusPlus)
1820 return false;
1821 if (TargetDecl) {
1822 if (const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(TargetDecl)) {
1823 if (FDecl->isExternC())
1824 return false;
1825 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(TargetDecl)) {
1826 // Function pointer.
1827 if (VDecl->isExternC())
1828 return false;
1829 }
1830 }
1831
1832 // We don't want to be too aggressive with the return checking, unless
1833 // it's explicit in the code opts or we're using an appropriate sanitizer.
1834 // Try to respect what the programmer intended.
1835 return Module.getCodeGenOpts().StrictReturn ||
1836 !Module.MayDropFunctionReturn(Module.getContext(), RetTy) ||
1837 Module.getLangOpts().Sanitize.has(SanitizerKind::Return);
1838}
1839
1840/// Add denormal-fp-math and denormal-fp-math-f32 as appropriate for the
1841/// requested denormal behavior, accounting for the overriding behavior of the
1842/// -f32 case.
1843static void addDenormalModeAttrs(llvm::DenormalMode FPDenormalMode,
1844 llvm::DenormalMode FP32DenormalMode,
1845 llvm::AttrBuilder &FuncAttrs) {
1846 if (FPDenormalMode != llvm::DenormalMode::getDefault())
1847 FuncAttrs.addAttribute("denormal-fp-math", FPDenormalMode.str());
1848
1849 if (FP32DenormalMode != FPDenormalMode && FP32DenormalMode.isValid())
1850 FuncAttrs.addAttribute("denormal-fp-math-f32", FP32DenormalMode.str());
1851}
1852
1853/// Add default attributes to a function, which have merge semantics under
1854/// -mlink-builtin-bitcode and should not simply overwrite any existing
1855/// attributes in the linked library.
1856static void
1858 llvm::AttrBuilder &FuncAttrs) {
1859 addDenormalModeAttrs(CodeGenOpts.FPDenormalMode, CodeGenOpts.FP32DenormalMode,
1860 FuncAttrs);
1861}
1862
1864 StringRef Name, bool HasOptnone, const CodeGenOptions &CodeGenOpts,
1865 const LangOptions &LangOpts, bool AttrOnCallSite,
1866 llvm::AttrBuilder &FuncAttrs) {
1867 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1868 if (!HasOptnone) {
1869 if (CodeGenOpts.OptimizeSize)
1870 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1871 if (CodeGenOpts.OptimizeSize == 2)
1872 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1873 }
1874
1875 if (CodeGenOpts.DisableRedZone)
1876 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
1877 if (CodeGenOpts.IndirectTlsSegRefs)
1878 FuncAttrs.addAttribute("indirect-tls-seg-refs");
1879 if (CodeGenOpts.NoImplicitFloat)
1880 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
1881
1882 if (AttrOnCallSite) {
1883 // Attributes that should go on the call site only.
1884 // FIXME: Look for 'BuiltinAttr' on the function rather than re-checking
1885 // the -fno-builtin-foo list.
1886 if (!CodeGenOpts.SimplifyLibCalls || LangOpts.isNoBuiltinFunc(Name))
1887 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
1888 if (!CodeGenOpts.TrapFuncName.empty())
1889 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
1890 } else {
1891 switch (CodeGenOpts.getFramePointer()) {
1893 // This is the default behavior.
1894 break;
1898 FuncAttrs.addAttribute("frame-pointer",
1900 CodeGenOpts.getFramePointer()));
1901 }
1902
1903 if (CodeGenOpts.LessPreciseFPMAD)
1904 FuncAttrs.addAttribute("less-precise-fpmad", "true");
1905
1906 if (CodeGenOpts.NullPointerIsValid)
1907 FuncAttrs.addAttribute(llvm::Attribute::NullPointerIsValid);
1908
1910 FuncAttrs.addAttribute("no-trapping-math", "true");
1911
1912 // TODO: Are these all needed?
1913 // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
1914 if (LangOpts.NoHonorInfs)
1915 FuncAttrs.addAttribute("no-infs-fp-math", "true");
1916 if (LangOpts.NoHonorNaNs)
1917 FuncAttrs.addAttribute("no-nans-fp-math", "true");
1918 if (LangOpts.ApproxFunc)
1919 FuncAttrs.addAttribute("approx-func-fp-math", "true");
1920 if (LangOpts.AllowFPReassoc && LangOpts.AllowRecip &&
1921 LangOpts.NoSignedZero && LangOpts.ApproxFunc &&
1922 (LangOpts.getDefaultFPContractMode() ==
1924 LangOpts.getDefaultFPContractMode() ==
1926 FuncAttrs.addAttribute("unsafe-fp-math", "true");
1927 if (CodeGenOpts.SoftFloat)
1928 FuncAttrs.addAttribute("use-soft-float", "true");
1929 FuncAttrs.addAttribute("stack-protector-buffer-size",
1930 llvm::utostr(CodeGenOpts.SSPBufferSize));
1931 if (LangOpts.NoSignedZero)
1932 FuncAttrs.addAttribute("no-signed-zeros-fp-math", "true");
1933
1934 // TODO: Reciprocal estimate codegen options should apply to instructions?
1935 const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals;
1936 if (!Recips.empty())
1937 FuncAttrs.addAttribute("reciprocal-estimates",
1938 llvm::join(Recips, ","));
1939
1940 if (!CodeGenOpts.PreferVectorWidth.empty() &&
1941 CodeGenOpts.PreferVectorWidth != "none")
1942 FuncAttrs.addAttribute("prefer-vector-width",
1943 CodeGenOpts.PreferVectorWidth);
1944
1945 if (CodeGenOpts.StackRealignment)
1946 FuncAttrs.addAttribute("stackrealign");
1947 if (CodeGenOpts.Backchain)
1948 FuncAttrs.addAttribute("backchain");
1949 if (CodeGenOpts.EnableSegmentedStacks)
1950 FuncAttrs.addAttribute("split-stack");
1951
1952 if (CodeGenOpts.SpeculativeLoadHardening)
1953 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
1954
1955 // Add zero-call-used-regs attribute.
1956 switch (CodeGenOpts.getZeroCallUsedRegs()) {
1957 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Skip:
1958 FuncAttrs.removeAttribute("zero-call-used-regs");
1959 break;
1960 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPRArg:
1961 FuncAttrs.addAttribute("zero-call-used-regs", "used-gpr-arg");
1962 break;
1963 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPR:
1964 FuncAttrs.addAttribute("zero-call-used-regs", "used-gpr");
1965 break;
1966 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedArg:
1967 FuncAttrs.addAttribute("zero-call-used-regs", "used-arg");
1968 break;
1969 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Used:
1970 FuncAttrs.addAttribute("zero-call-used-regs", "used");
1971 break;
1972 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPRArg:
1973 FuncAttrs.addAttribute("zero-call-used-regs", "all-gpr-arg");
1974 break;
1975 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPR:
1976 FuncAttrs.addAttribute("zero-call-used-regs", "all-gpr");
1977 break;
1978 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllArg:
1979 FuncAttrs.addAttribute("zero-call-used-regs", "all-arg");
1980 break;
1981 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::All:
1982 FuncAttrs.addAttribute("zero-call-used-regs", "all");
1983 break;
1984 }
1985 }
1986
1987 if (LangOpts.assumeFunctionsAreConvergent()) {
1988 // Conservatively, mark all functions and calls in CUDA and OpenCL as
1989 // convergent (meaning, they may call an intrinsically convergent op, such
1990 // as __syncthreads() / barrier(), and so can't have certain optimizations
1991 // applied around them). LLVM will remove this attribute where it safely
1992 // can.
1993 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
1994 }
1995
1996 // TODO: NoUnwind attribute should be added for other GPU modes HIP,
1997 // OpenMP offload. AFAIK, neither of them support exceptions in device code.
1998 if ((LangOpts.CUDA && LangOpts.CUDAIsDevice) || LangOpts.OpenCL ||
1999 LangOpts.SYCLIsDevice) {
2000 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2001 }
2002
2003 if (CodeGenOpts.SaveRegParams && !AttrOnCallSite)
2004 FuncAttrs.addAttribute("save-reg-params");
2005
2006 for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) {
2007 StringRef Var, Value;
2008 std::tie(Var, Value) = Attr.split('=');
2009 FuncAttrs.addAttribute(Var, Value);
2010 }
2011
2014}
2015
2016/// Merges `target-features` from \TargetOpts and \F, and sets the result in
2017/// \FuncAttr
2018/// * features from \F are always kept
2019/// * a feature from \TargetOpts is kept if itself and its opposite are absent
2020/// from \F
2021static void
2023 const llvm::Function &F,
2024 const TargetOptions &TargetOpts) {
2025 auto FFeatures = F.getFnAttribute("target-features");
2026
2027 llvm::StringSet<> MergedNames;
2028 SmallVector<StringRef> MergedFeatures;
2029 MergedFeatures.reserve(TargetOpts.Features.size());
2030
2031 auto AddUnmergedFeatures = [&](auto &&FeatureRange) {
2032 for (StringRef Feature : FeatureRange) {
2033 if (Feature.empty())
2034 continue;
2035 assert(Feature[0] == '+' || Feature[0] == '-');
2036 StringRef Name = Feature.drop_front(1);
2037 bool Merged = !MergedNames.insert(Name).second;
2038 if (!Merged)
2039 MergedFeatures.push_back(Feature);
2040 }
2041 };
2042
2043 if (FFeatures.isValid())
2044 AddUnmergedFeatures(llvm::split(FFeatures.getValueAsString(), ','));
2045 AddUnmergedFeatures(TargetOpts.Features);
2046
2047 if (!MergedFeatures.empty()) {
2048 llvm::sort(MergedFeatures);
2049 FuncAttr.addAttribute("target-features", llvm::join(MergedFeatures, ","));
2050 }
2051}
2052
2054 llvm::Function &F, const CodeGenOptions &CodeGenOpts,
2055 const LangOptions &LangOpts, const TargetOptions &TargetOpts,
2056 bool WillInternalize) {
2057
2058 llvm::AttrBuilder FuncAttrs(F.getContext());
2059 // Here we only extract the options that are relevant compared to the version
2060 // from GetCPUAndFeaturesAttributes.
2061 if (!TargetOpts.CPU.empty())
2062 FuncAttrs.addAttribute("target-cpu", TargetOpts.CPU);
2063 if (!TargetOpts.TuneCPU.empty())
2064 FuncAttrs.addAttribute("tune-cpu", TargetOpts.TuneCPU);
2065
2066 ::getTrivialDefaultFunctionAttributes(F.getName(), F.hasOptNone(),
2067 CodeGenOpts, LangOpts,
2068 /*AttrOnCallSite=*/false, FuncAttrs);
2069
2070 if (!WillInternalize && F.isInterposable()) {
2071 // Do not promote "dynamic" denormal-fp-math to this translation unit's
2072 // setting for weak functions that won't be internalized. The user has no
2073 // real control for how builtin bitcode is linked, so we shouldn't assume
2074 // later copies will use a consistent mode.
2075 F.addFnAttrs(FuncAttrs);
2076 return;
2077 }
2078
2079 llvm::AttributeMask AttrsToRemove;
2080
2081 llvm::DenormalMode DenormModeToMerge = F.getDenormalModeRaw();
2082 llvm::DenormalMode DenormModeToMergeF32 = F.getDenormalModeF32Raw();
2083 llvm::DenormalMode Merged =
2084 CodeGenOpts.FPDenormalMode.mergeCalleeMode(DenormModeToMerge);
2085 llvm::DenormalMode MergedF32 = CodeGenOpts.FP32DenormalMode;
2086
2087 if (DenormModeToMergeF32.isValid()) {
2088 MergedF32 =
2089 CodeGenOpts.FP32DenormalMode.mergeCalleeMode(DenormModeToMergeF32);
2090 }
2091
2092 if (Merged == llvm::DenormalMode::getDefault()) {
2093 AttrsToRemove.addAttribute("denormal-fp-math");
2094 } else if (Merged != DenormModeToMerge) {
2095 // Overwrite existing attribute
2096 FuncAttrs.addAttribute("denormal-fp-math",
2097 CodeGenOpts.FPDenormalMode.str());
2098 }
2099
2100 if (MergedF32 == llvm::DenormalMode::getDefault()) {
2101 AttrsToRemove.addAttribute("denormal-fp-math-f32");
2102 } else if (MergedF32 != DenormModeToMergeF32) {
2103 // Overwrite existing attribute
2104 FuncAttrs.addAttribute("denormal-fp-math-f32",
2105 CodeGenOpts.FP32DenormalMode.str());
2106 }
2107
2108 F.removeFnAttrs(AttrsToRemove);
2109 addDenormalModeAttrs(Merged, MergedF32, FuncAttrs);
2110
2111 overrideFunctionFeaturesWithTargetFeatures(FuncAttrs, F, TargetOpts);
2112
2113 F.addFnAttrs(FuncAttrs);
2114}
2115
2116void CodeGenModule::getTrivialDefaultFunctionAttributes(
2117 StringRef Name, bool HasOptnone, bool AttrOnCallSite,
2118 llvm::AttrBuilder &FuncAttrs) {
2119 ::getTrivialDefaultFunctionAttributes(Name, HasOptnone, getCodeGenOpts(),
2120 getLangOpts(), AttrOnCallSite,
2121 FuncAttrs);
2122}
2123
2124void CodeGenModule::getDefaultFunctionAttributes(StringRef Name,
2125 bool HasOptnone,
2126 bool AttrOnCallSite,
2127 llvm::AttrBuilder &FuncAttrs) {
2128 getTrivialDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite,
2129 FuncAttrs);
2130 // If we're just getting the default, get the default values for mergeable
2131 // attributes.
2132 if (!AttrOnCallSite)
2133 addMergableDefaultFunctionAttributes(CodeGenOpts, FuncAttrs);
2134}
2135
2137 llvm::AttrBuilder &attrs) {
2138 getDefaultFunctionAttributes(/*function name*/ "", /*optnone*/ false,
2139 /*for call*/ false, attrs);
2140 GetCPUAndFeaturesAttributes(GlobalDecl(), attrs);
2141}
2142
2143static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs,
2144 const LangOptions &LangOpts,
2145 const NoBuiltinAttr *NBA = nullptr) {
2146 auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) {
2147 SmallString<32> AttributeName;
2148 AttributeName += "no-builtin-";
2149 AttributeName += BuiltinName;
2150 FuncAttrs.addAttribute(AttributeName);
2151 };
2152
2153 // First, handle the language options passed through -fno-builtin.
2154 if (LangOpts.NoBuiltin) {
2155 // -fno-builtin disables them all.
2156 FuncAttrs.addAttribute("no-builtins");
2157 return;
2158 }
2159
2160 // Then, add attributes for builtins specified through -fno-builtin-<name>.
2161 llvm::for_each(LangOpts.NoBuiltinFuncs, AddNoBuiltinAttr);
2162
2163 // Now, let's check the __attribute__((no_builtin("...")) attribute added to
2164 // the source.
2165 if (!NBA)
2166 return;
2167
2168 // If there is a wildcard in the builtin names specified through the
2169 // attribute, disable them all.
2170 if (llvm::is_contained(NBA->builtinNames(), "*")) {
2171 FuncAttrs.addAttribute("no-builtins");
2172 return;
2173 }
2174
2175 // And last, add the rest of the builtin names.
2176 llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr);
2177}
2178
2180 const llvm::DataLayout &DL, const ABIArgInfo &AI,
2181 bool CheckCoerce = true) {
2182 llvm::Type *Ty = Types.ConvertTypeForMem(QTy);
2183 if (AI.getKind() == ABIArgInfo::Indirect ||
2185 return true;
2186 if (AI.getKind() == ABIArgInfo::Extend)
2187 return true;
2188 if (!DL.typeSizeEqualsStoreSize(Ty))
2189 // TODO: This will result in a modest amount of values not marked noundef
2190 // when they could be. We care about values that *invisibly* contain undef
2191 // bits from the perspective of LLVM IR.
2192 return false;
2193 if (CheckCoerce && AI.canHaveCoerceToType()) {
2194 llvm::Type *CoerceTy = AI.getCoerceToType();
2195 if (llvm::TypeSize::isKnownGT(DL.getTypeSizeInBits(CoerceTy),
2196 DL.getTypeSizeInBits(Ty)))
2197 // If we're coercing to a type with a greater size than the canonical one,
2198 // we're introducing new undef bits.
2199 // Coercing to a type of smaller or equal size is ok, as we know that
2200 // there's no internal padding (typeSizeEqualsStoreSize).
2201 return false;
2202 }
2203 if (QTy->isBitIntType())
2204 return true;
2205 if (QTy->isReferenceType())
2206 return true;
2207 if (QTy->isNullPtrType())
2208 return false;
2209 if (QTy->isMemberPointerType())
2210 // TODO: Some member pointers are `noundef`, but it depends on the ABI. For
2211 // now, never mark them.
2212 return false;
2213 if (QTy->isScalarType()) {
2214 if (const ComplexType *Complex = dyn_cast<ComplexType>(QTy))
2215 return DetermineNoUndef(Complex->getElementType(), Types, DL, AI, false);
2216 return true;
2217 }
2218 if (const VectorType *Vector = dyn_cast<VectorType>(QTy))
2219 return DetermineNoUndef(Vector->getElementType(), Types, DL, AI, false);
2220 if (const MatrixType *Matrix = dyn_cast<MatrixType>(QTy))
2221 return DetermineNoUndef(Matrix->getElementType(), Types, DL, AI, false);
2222 if (const ArrayType *Array = dyn_cast<ArrayType>(QTy))
2223 return DetermineNoUndef(Array->getElementType(), Types, DL, AI, false);
2224
2225 // TODO: Some structs may be `noundef`, in specific situations.
2226 return false;
2227}
2228
2229/// Check if the argument of a function has maybe_undef attribute.
2230static bool IsArgumentMaybeUndef(const Decl *TargetDecl,
2231 unsigned NumRequiredArgs, unsigned ArgNo) {
2232 const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
2233 if (!FD)
2234 return false;
2235
2236 // Assume variadic arguments do not have maybe_undef attribute.
2237 if (ArgNo >= NumRequiredArgs)
2238 return false;
2239
2240 // Check if argument has maybe_undef attribute.
2241 if (ArgNo < FD->getNumParams()) {
2242 const ParmVarDecl *Param = FD->getParamDecl(ArgNo);
2243 if (Param && Param->hasAttr<MaybeUndefAttr>())
2244 return true;
2245 }
2246
2247 return false;
2248}
2249
2250/// Test if it's legal to apply nofpclass for the given parameter type and it's
2251/// lowered IR type.
2252static bool canApplyNoFPClass(const ABIArgInfo &AI, QualType ParamType,
2253 bool IsReturn) {
2254 // Should only apply to FP types in the source, not ABI promoted.
2255 if (!ParamType->hasFloatingRepresentation())
2256 return false;
2257
2258 // The promoted-to IR type also needs to support nofpclass.
2259 llvm::Type *IRTy = AI.getCoerceToType();
2260 if (llvm::AttributeFuncs::isNoFPClassCompatibleType(IRTy))
2261 return true;
2262
2263 if (llvm::StructType *ST = dyn_cast<llvm::StructType>(IRTy)) {
2264 return !IsReturn && AI.getCanBeFlattened() &&
2265 llvm::all_of(ST->elements(), [](llvm::Type *Ty) {
2266 return llvm::AttributeFuncs::isNoFPClassCompatibleType(Ty);
2267 });
2268 }
2269
2270 return false;
2271}
2272
2273/// Return the nofpclass mask that can be applied to floating-point parameters.
2274static llvm::FPClassTest getNoFPClassTestMask(const LangOptions &LangOpts) {
2275 llvm::FPClassTest Mask = llvm::fcNone;
2276 if (LangOpts.NoHonorInfs)
2277 Mask |= llvm::fcInf;
2278 if (LangOpts.NoHonorNaNs)
2279 Mask |= llvm::fcNan;
2280 return Mask;
2281}
2282
2284 CGCalleeInfo CalleeInfo,
2285 llvm::AttributeList &Attrs) {
2286 if (Attrs.getMemoryEffects().getModRef() == llvm::ModRefInfo::NoModRef) {
2287 Attrs = Attrs.removeFnAttribute(getLLVMContext(), llvm::Attribute::Memory);
2288 llvm::Attribute MemoryAttr = llvm::Attribute::getWithMemoryEffects(
2289 getLLVMContext(), llvm::MemoryEffects::writeOnly());
2290 Attrs = Attrs.addFnAttribute(getLLVMContext(), MemoryAttr);
2291 }
2292}
2293
2294/// Construct the IR attribute list of a function or call.
2295///
2296/// When adding an attribute, please consider where it should be handled:
2297///
2298/// - getDefaultFunctionAttributes is for attributes that are essentially
2299/// part of the global target configuration (but perhaps can be
2300/// overridden on a per-function basis). Adding attributes there
2301/// will cause them to also be set in frontends that build on Clang's
2302/// target-configuration logic, as well as for code defined in library
2303/// modules such as CUDA's libdevice.
2304///
2305/// - ConstructAttributeList builds on top of getDefaultFunctionAttributes
2306/// and adds declaration-specific, convention-specific, and
2307/// frontend-specific logic. The last is of particular importance:
2308/// attributes that restrict how the frontend generates code must be
2309/// added here rather than getDefaultFunctionAttributes.
2310///
2312 const CGFunctionInfo &FI,
2313 CGCalleeInfo CalleeInfo,
2314 llvm::AttributeList &AttrList,
2315 unsigned &CallingConv,
2316 bool AttrOnCallSite, bool IsThunk) {
2317 llvm::AttrBuilder FuncAttrs(getLLVMContext());
2318 llvm::AttrBuilder RetAttrs(getLLVMContext());
2319
2320 // Collect function IR attributes from the CC lowering.
2321 // We'll collect the paramete and result attributes later.
2323 if (FI.isNoReturn())
2324 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2325 if (FI.isCmseNSCall())
2326 FuncAttrs.addAttribute("cmse_nonsecure_call");
2327
2328 // Collect function IR attributes from the callee prototype if we have one.
2330 CalleeInfo.getCalleeFunctionProtoType());
2331
2332 const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl();
2333
2334 // Attach assumption attributes to the declaration. If this is a call
2335 // site, attach assumptions from the caller to the call as well.
2336 AddAttributesFromOMPAssumes(FuncAttrs, TargetDecl);
2337
2338 bool HasOptnone = false;
2339 // The NoBuiltinAttr attached to the target FunctionDecl.
2340 const NoBuiltinAttr *NBA = nullptr;
2341
2342 // Some ABIs may result in additional accesses to arguments that may
2343 // otherwise not be present.
2344 auto AddPotentialArgAccess = [&]() {
2345 llvm::Attribute A = FuncAttrs.getAttribute(llvm::Attribute::Memory);
2346 if (A.isValid())
2347 FuncAttrs.addMemoryAttr(A.getMemoryEffects() |
2348 llvm::MemoryEffects::argMemOnly());
2349 };
2350
2351 // Collect function IR attributes based on declaration-specific
2352 // information.
2353 // FIXME: handle sseregparm someday...
2354 if (TargetDecl) {
2355 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
2356 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
2357 if (TargetDecl->hasAttr<NoThrowAttr>())
2358 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2359 if (TargetDecl->hasAttr<NoReturnAttr>())
2360 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2361 if (TargetDecl->hasAttr<ColdAttr>())
2362 FuncAttrs.addAttribute(llvm::Attribute::Cold);
2363 if (TargetDecl->hasAttr<HotAttr>())
2364 FuncAttrs.addAttribute(llvm::Attribute::Hot);
2365 if (TargetDecl->hasAttr<NoDuplicateAttr>())
2366 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
2367 if (TargetDecl->hasAttr<ConvergentAttr>())
2368 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
2369
2370 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2372 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
2373 if (AttrOnCallSite && Fn->isReplaceableGlobalAllocationFunction()) {
2374 // A sane operator new returns a non-aliasing pointer.
2375 auto Kind = Fn->getDeclName().getCXXOverloadedOperator();
2376 if (getCodeGenOpts().AssumeSaneOperatorNew &&
2377 (Kind == OO_New || Kind == OO_Array_New))
2378 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2379 }
2380 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
2381 const bool IsVirtualCall = MD && MD->isVirtual();
2382 // Don't use [[noreturn]], _Noreturn or [[no_builtin]] for a call to a
2383 // virtual function. These attributes are not inherited by overloads.
2384 if (!(AttrOnCallSite && IsVirtualCall)) {
2385 if (Fn->isNoReturn())
2386 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2387 NBA = Fn->getAttr<NoBuiltinAttr>();
2388 }
2389 }
2390
2391 if (isa<FunctionDecl>(TargetDecl) || isa<VarDecl>(TargetDecl)) {
2392 // Only place nomerge attribute on call sites, never functions. This
2393 // allows it to work on indirect virtual function calls.
2394 if (AttrOnCallSite && TargetDecl->hasAttr<NoMergeAttr>())
2395 FuncAttrs.addAttribute(llvm::Attribute::NoMerge);
2396 }
2397
2398 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
2399 if (TargetDecl->hasAttr<ConstAttr>()) {
2400 FuncAttrs.addMemoryAttr(llvm::MemoryEffects::none());
2401 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2402 // gcc specifies that 'const' functions have greater restrictions than
2403 // 'pure' functions, so they also cannot have infinite loops.
2404 FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
2405 } else if (TargetDecl->hasAttr<PureAttr>()) {
2406 FuncAttrs.addMemoryAttr(llvm::MemoryEffects::readOnly());
2407 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2408 // gcc specifies that 'pure' functions cannot have infinite loops.
2409 FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
2410 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
2411 FuncAttrs.addMemoryAttr(llvm::MemoryEffects::inaccessibleOrArgMemOnly());
2412 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2413 }
2414 if (TargetDecl->hasAttr<RestrictAttr>())
2415 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2416 if (TargetDecl->hasAttr<ReturnsNonNullAttr>() &&
2417 !CodeGenOpts.NullPointerIsValid)
2418 RetAttrs.addAttribute(llvm::Attribute::NonNull);
2419 if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
2420 FuncAttrs.addAttribute("no_caller_saved_registers");
2421 if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>())
2422 FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck);
2423 if (TargetDecl->hasAttr<LeafAttr>())
2424 FuncAttrs.addAttribute(llvm::Attribute::NoCallback);
2425
2426 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
2427 if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
2428 std::optional<unsigned> NumElemsParam;
2429 if (AllocSize->getNumElemsParam().isValid())
2430 NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
2431 FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(),
2432 NumElemsParam);
2433 }
2434
2435 if (TargetDecl->hasAttr<OpenCLKernelAttr>()) {
2436 if (getLangOpts().OpenCLVersion <= 120) {
2437 // OpenCL v1.2 Work groups are always uniform
2438 FuncAttrs.addAttribute("uniform-work-group-size", "true");
2439 } else {
2440 // OpenCL v2.0 Work groups may be whether uniform or not.
2441 // '-cl-uniform-work-group-size' compile option gets a hint
2442 // to the compiler that the global work-size be a multiple of
2443 // the work-group size specified to clEnqueueNDRangeKernel
2444 // (i.e. work groups are uniform).
2445 FuncAttrs.addAttribute(
2446 "uniform-work-group-size",
2447 llvm::toStringRef(getLangOpts().OffloadUniformBlock));
2448 }
2449 }
2450
2451 if (TargetDecl->hasAttr<CUDAGlobalAttr>() &&
2452 getLangOpts().OffloadUniformBlock)
2453 FuncAttrs.addAttribute("uniform-work-group-size", "true");
2454
2455 if (TargetDecl->hasAttr<ArmLocallyStreamingAttr>())
2456 FuncAttrs.addAttribute("aarch64_pstate_sm_body");
2457 }
2458
2459 // Attach "no-builtins" attributes to:
2460 // * call sites: both `nobuiltin` and "no-builtins" or "no-builtin-<name>".
2461 // * definitions: "no-builtins" or "no-builtin-<name>" only.
2462 // The attributes can come from:
2463 // * LangOpts: -ffreestanding, -fno-builtin, -fno-builtin-<name>
2464 // * FunctionDecl attributes: __attribute__((no_builtin(...)))
2465 addNoBuiltinAttributes(FuncAttrs, getLangOpts(), NBA);
2466
2467 // Collect function IR attributes based on global settiings.
2468 getDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
2469
2470 // Override some default IR attributes based on declaration-specific
2471 // information.
2472 if (TargetDecl) {
2473 if (TargetDecl->hasAttr<NoSpeculativeLoadHardeningAttr>())
2474 FuncAttrs.removeAttribute(llvm::Attribute::SpeculativeLoadHardening);
2475 if (TargetDecl->hasAttr<SpeculativeLoadHardeningAttr>())
2476 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
2477 if (TargetDecl->hasAttr<NoSplitStackAttr>())
2478 FuncAttrs.removeAttribute("split-stack");
2479 if (TargetDecl->hasAttr<ZeroCallUsedRegsAttr>()) {
2480 // A function "__attribute__((...))" overrides the command-line flag.
2481 auto Kind =
2482 TargetDecl->getAttr<ZeroCallUsedRegsAttr>()->getZeroCallUsedRegs();
2483 FuncAttrs.removeAttribute("zero-call-used-regs");
2484 FuncAttrs.addAttribute(
2485 "zero-call-used-regs",
2486 ZeroCallUsedRegsAttr::ConvertZeroCallUsedRegsKindToStr(Kind));
2487 }
2488
2489 // Add NonLazyBind attribute to function declarations when -fno-plt
2490 // is used.
2491 // FIXME: what if we just haven't processed the function definition
2492 // yet, or if it's an external definition like C99 inline?
2493 if (CodeGenOpts.NoPLT) {
2494 if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2495 if (!Fn->isDefined() && !AttrOnCallSite) {
2496 FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind);
2497 }
2498 }
2499 }
2500 // Remove 'convergent' if requested.
2501 if (TargetDecl->hasAttr<NoConvergentAttr>())
2502 FuncAttrs.removeAttribute(llvm::Attribute::Convergent);
2503 }
2504
2505 // Add "sample-profile-suffix-elision-policy" attribute for internal linkage
2506 // functions with -funique-internal-linkage-names.
2507 if (TargetDecl && CodeGenOpts.UniqueInternalLinkageNames) {
2508 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
2509 if (!FD->isExternallyVisible())
2510 FuncAttrs.addAttribute("sample-profile-suffix-elision-policy",
2511 "selected");
2512 }
2513 }
2514
2515 // Collect non-call-site function IR attributes from declaration-specific
2516 // information.
2517 if (!AttrOnCallSite) {
2518 if (TargetDecl && TargetDecl->hasAttr<CmseNSEntryAttr>())
2519 FuncAttrs.addAttribute("cmse_nonsecure_entry");
2520
2521 // Whether tail calls are enabled.
2522 auto shouldDisableTailCalls = [&] {
2523 // Should this be honored in getDefaultFunctionAttributes?
2524 if (CodeGenOpts.DisableTailCalls)
2525 return true;
2526
2527 if (!TargetDecl)
2528 return false;
2529
2530 if (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
2531 TargetDecl->hasAttr<AnyX86InterruptAttr>())
2532 return true;
2533
2534 if (CodeGenOpts.NoEscapingBlockTailCalls) {
2535 if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl))
2536 if (!BD->doesNotEscape())
2537 return true;
2538 }
2539
2540 return false;
2541 };
2542 if (shouldDisableTailCalls())
2543 FuncAttrs.addAttribute("disable-tail-calls", "true");
2544
2545 // CPU/feature overrides. addDefaultFunctionDefinitionAttributes
2546 // handles these separately to set them based on the global defaults.
2547 GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs);
2548 }
2549
2550 // Collect attributes from arguments and return values.
2551 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
2552
2553 QualType RetTy = FI.getReturnType();
2554 const ABIArgInfo &RetAI = FI.getReturnInfo();
2555 const llvm::DataLayout &DL = getDataLayout();
2556
2557 // Determine if the return type could be partially undef
2558 if (CodeGenOpts.EnableNoundefAttrs &&
2559 HasStrictReturn(*this, RetTy, TargetDecl)) {
2560 if (!RetTy->isVoidType() && RetAI.getKind() != ABIArgInfo::Indirect &&
2561 DetermineNoUndef(RetTy, getTypes(), DL, RetAI))
2562 RetAttrs.addAttribute(llvm::Attribute::NoUndef);
2563 }
2564
2565 switch (RetAI.getKind()) {
2566 case ABIArgInfo::Extend:
2567 if (RetAI.isSignExt())
2568 RetAttrs.addAttribute(llvm::Attribute::SExt);
2569 else
2570 RetAttrs.addAttribute(llvm::Attribute::ZExt);
2571 [[fallthrough]];
2572 case ABIArgInfo::Direct:
2573 if (RetAI.getInReg())
2574 RetAttrs.addAttribute(llvm::Attribute::InReg);
2575
2576 if (canApplyNoFPClass(RetAI, RetTy, true))
2577 RetAttrs.addNoFPClassAttr(getNoFPClassTestMask(getLangOpts()));
2578
2579 break;
2580 case ABIArgInfo::Ignore:
2581 break;
2582
2584 case ABIArgInfo::Indirect: {
2585 // inalloca and sret disable readnone and readonly
2586 AddPotentialArgAccess();
2587 break;
2588 }
2589
2591 break;
2592
2593 case ABIArgInfo::Expand:
2595 llvm_unreachable("Invalid ABI kind for return argument");
2596 }
2597
2598 if (!IsThunk) {
2599 // FIXME: fix this properly, https://reviews.llvm.org/D100388
2600 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
2601 QualType PTy = RefTy->getPointeeType();
2602 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2603 RetAttrs.addDereferenceableAttr(
2604 getMinimumObjectSize(PTy).getQuantity());
2605 if (getTypes().getTargetAddressSpace(PTy) == 0 &&
2606 !CodeGenOpts.NullPointerIsValid)
2607 RetAttrs.addAttribute(llvm::Attribute::NonNull);
2608 if (PTy->isObjectType()) {
2609 llvm::Align Alignment =
2611 RetAttrs.addAlignmentAttr(Alignment);
2612 }
2613 }
2614 }
2615
2616 bool hasUsedSRet = false;
2617 SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs());
2618
2619 // Attach attributes to sret.
2620 if (IRFunctionArgs.hasSRetArg()) {
2621 llvm::AttrBuilder SRETAttrs(getLLVMContext());
2622 SRETAttrs.addStructRetAttr(getTypes().ConvertTypeForMem(RetTy));
2623 SRETAttrs.addAttribute(llvm::Attribute::Writable);
2624 SRETAttrs.addAttribute(llvm::Attribute::DeadOnUnwind);
2625 hasUsedSRet = true;
2626 if (RetAI.getInReg())
2627 SRETAttrs.addAttribute(llvm::Attribute::InReg);
2628 SRETAttrs.addAlignmentAttr(RetAI.getIndirectAlign().getQuantity());
2629 ArgAttrs[IRFunctionArgs.getSRetArgNo()] =
2630 llvm::AttributeSet::get(getLLVMContext(), SRETAttrs);
2631 }
2632
2633 // Attach attributes to inalloca argument.
2634 if (IRFunctionArgs.hasInallocaArg()) {
2635 llvm::AttrBuilder Attrs(getLLVMContext());
2636 Attrs.addInAllocaAttr(FI.getArgStruct());
2637 ArgAttrs[IRFunctionArgs.getInallocaArgNo()] =
2638 llvm::AttributeSet::get(getLLVMContext(), Attrs);
2639 }
2640
2641 // Apply `nonnull`, `dereferencable(N)` and `align N` to the `this` argument,
2642 // unless this is a thunk function.
2643 // FIXME: fix this properly, https://reviews.llvm.org/D100388
2644 if (FI.isInstanceMethod() && !IRFunctionArgs.hasInallocaArg() &&
2645 !FI.arg_begin()->type->isVoidPointerType() && !IsThunk) {
2646 auto IRArgs = IRFunctionArgs.getIRArgs(0);
2647
2648 assert(IRArgs.second == 1 && "Expected only a single `this` pointer.");
2649
2650 llvm::AttrBuilder Attrs(getLLVMContext());
2651
2652 QualType ThisTy =
2654
2655 if (!CodeGenOpts.NullPointerIsValid &&
2656 getTypes().getTargetAddressSpace(FI.arg_begin()->type) == 0) {
2657 Attrs.addAttribute(llvm::Attribute::NonNull);
2658 Attrs.addDereferenceableAttr(getMinimumObjectSize(ThisTy).getQuantity());
2659 } else {
2660 // FIXME dereferenceable should be correct here, regardless of
2661 // NullPointerIsValid. However, dereferenceable currently does not always
2662 // respect NullPointerIsValid and may imply nonnull and break the program.
2663 // See https://reviews.llvm.org/D66618 for discussions.
2664 Attrs.addDereferenceableOrNullAttr(
2667 .getQuantity());
2668 }
2669
2670 llvm::Align Alignment =
2671 getNaturalTypeAlignment(ThisTy, /*BaseInfo=*/nullptr,
2672 /*TBAAInfo=*/nullptr, /*forPointeeType=*/true)
2673 .getAsAlign();
2674 Attrs.addAlignmentAttr(Alignment);
2675
2676 ArgAttrs[IRArgs.first] = llvm::AttributeSet::get(getLLVMContext(), Attrs);
2677 }
2678
2679 unsigned ArgNo = 0;
2681 E = FI.arg_end();
2682 I != E; ++I, ++ArgNo) {
2683 QualType ParamType = I->type;
2684 const ABIArgInfo &AI = I->info;
2685 llvm::AttrBuilder Attrs(getLLVMContext());
2686
2687 // Add attribute for padding argument, if necessary.
2688 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
2689 if (AI.getPaddingInReg()) {
2690 ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2691 llvm::AttributeSet::get(
2693 llvm::AttrBuilder(getLLVMContext()).addAttribute(llvm::Attribute::InReg));
2694 }
2695 }
2696
2697 // Decide whether the argument we're handling could be partially undef
2698 if (CodeGenOpts.EnableNoundefAttrs &&
2699 DetermineNoUndef(ParamType, getTypes(), DL, AI)) {
2700 Attrs.addAttribute(llvm::Attribute::NoUndef);
2701 }
2702
2703 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
2704 // have the corresponding parameter variable. It doesn't make
2705 // sense to do it here because parameters are so messed up.
2706 switch (AI.getKind()) {
2707 case ABIArgInfo::Extend:
2708 if (AI.isSignExt())
2709 Attrs.addAttribute(llvm::Attribute::SExt);
2710 else
2711 Attrs.addAttribute(llvm::Attribute::ZExt);
2712 [[fallthrough]];
2713 case ABIArgInfo::Direct:
2714 if (ArgNo == 0 && FI.isChainCall())
2715 Attrs.addAttribute(llvm::Attribute::Nest);
2716 else if (AI.getInReg())
2717 Attrs.addAttribute(llvm::Attribute::InReg);
2718 Attrs.addStackAlignmentAttr(llvm::MaybeAlign(AI.getDirectAlign()));
2719
2720 if (canApplyNoFPClass(AI, ParamType, false))
2721 Attrs.addNoFPClassAttr(getNoFPClassTestMask(getLangOpts()));
2722 break;
2723 case ABIArgInfo::Indirect: {
2724 if (AI.getInReg())
2725 Attrs.addAttribute(llvm::Attribute::InReg);
2726
2727 if (AI.getIndirectByVal())
2728 Attrs.addByValAttr(getTypes().ConvertTypeForMem(ParamType));
2729
2730 auto *Decl = ParamType->getAsRecordDecl();
2731 if (CodeGenOpts.PassByValueIsNoAlias && Decl &&
2732 Decl->getArgPassingRestrictions() ==
2734 // When calling the function, the pointer passed in will be the only
2735 // reference to the underlying object. Mark it accordingly.
2736 Attrs.addAttribute(llvm::Attribute::NoAlias);
2737
2738 // TODO: We could add the byref attribute if not byval, but it would
2739 // require updating many testcases.
2740
2741 CharUnits Align = AI.getIndirectAlign();
2742
2743 // In a byval argument, it is important that the required
2744 // alignment of the type is honored, as LLVM might be creating a
2745 // *new* stack object, and needs to know what alignment to give
2746 // it. (Sometimes it can deduce a sensible alignment on its own,
2747 // but not if clang decides it must emit a packed struct, or the
2748 // user specifies increased alignment requirements.)
2749 //
2750 // This is different from indirect *not* byval, where the object
2751 // exists already, and the align attribute is purely
2752 // informative.
2753 assert(!Align.isZero());
2754
2755 // For now, only add this when we have a byval argument.
2756 // TODO: be less lazy about updating test cases.
2757 if (AI.getIndirectByVal())
2758 Attrs.addAlignmentAttr(Align.getQuantity());
2759
2760 // byval disables readnone and readonly.
2761 AddPotentialArgAccess();
2762 break;
2763 }
2765 CharUnits Align = AI.getIndirectAlign();
2766 Attrs.addByRefAttr(getTypes().ConvertTypeForMem(ParamType));
2767 Attrs.addAlignmentAttr(Align.getQuantity());
2768 break;
2769 }
2770 case ABIArgInfo::Ignore:
2771 case ABIArgInfo::Expand:
2773 break;
2774
2776 // inalloca disables readnone and readonly.
2777 AddPotentialArgAccess();
2778 continue;
2779 }
2780
2781 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
2782 QualType PTy = RefTy->getPointeeType();
2783 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2784 Attrs.addDereferenceableAttr(
2785 getMinimumObjectSize(PTy).getQuantity());
2786 if (getTypes().getTargetAddressSpace(PTy) == 0 &&
2787 !CodeGenOpts.NullPointerIsValid)
2788 Attrs.addAttribute(llvm::Attribute::NonNull);
2789 if (PTy->isObjectType()) {
2790 llvm::Align Alignment =
2792 Attrs.addAlignmentAttr(Alignment);
2793 }
2794 }
2795
2796 // From OpenCL spec v3.0.10 section 6.3.5 Alignment of Types:
2797 // > For arguments to a __kernel function declared to be a pointer to a
2798 // > data type, the OpenCL compiler can assume that the pointee is always
2799 // > appropriately aligned as required by the data type.
2800 if (TargetDecl && TargetDecl->hasAttr<OpenCLKernelAttr>() &&
2801 ParamType->isPointerType()) {
2802 QualType PTy = ParamType->getPointeeType();
2803 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2804 llvm::Align Alignment =
2806 Attrs.addAlignmentAttr(Alignment);
2807 }
2808 }
2809
2810 switch (FI.getExtParameterInfo(ArgNo).getABI()) {
2812 break;
2813
2815 // Add 'sret' if we haven't already used it for something, but
2816 // only if the result is void.
2817 if (!hasUsedSRet && RetTy->isVoidType()) {
2818 Attrs.addStructRetAttr(getTypes().ConvertTypeForMem(ParamType));
2819 hasUsedSRet = true;
2820 }
2821
2822 // Add 'noalias' in either case.
2823 Attrs.addAttribute(llvm::Attribute::NoAlias);
2824
2825 // Add 'dereferenceable' and 'alignment'.
2826 auto PTy = ParamType->getPointeeType();
2827 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2828 auto info = getContext().getTypeInfoInChars(PTy);
2829 Attrs.addDereferenceableAttr(info.Width.getQuantity());
2830 Attrs.addAlignmentAttr(info.Align.getAsAlign());
2831 }
2832 break;
2833 }
2834
2836 Attrs.addAttribute(llvm::Attribute::SwiftError);
2837 break;
2838
2840 Attrs.addAttribute(llvm::Attribute::SwiftSelf);
2841 break;
2842
2844 Attrs.addAttribute(llvm::Attribute::SwiftAsync);
2845 break;
2846 }
2847
2848 if (FI.getExtParameterInfo(ArgNo).isNoEscape())
2849 Attrs.addAttribute(llvm::Attribute::NoCapture);
2850
2851 if (Attrs.hasAttributes()) {
2852 unsigned FirstIRArg, NumIRArgs;
2853 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2854 for (unsigned i = 0; i < NumIRArgs; i++)
2855 ArgAttrs[FirstIRArg + i] = ArgAttrs[FirstIRArg + i].addAttributes(
2856 getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), Attrs));
2857 }
2858 }
2859 assert(ArgNo == FI.arg_size());
2860
2861 AttrList = llvm::AttributeList::get(
2862 getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs),
2863 llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs);
2864}
2865
2866/// An argument came in as a promoted argument; demote it back to its
2867/// declared type.
2868static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
2869 const VarDecl *var,
2870 llvm::Value *value) {
2871 llvm::Type *varType = CGF.ConvertType(var->getType());
2872
2873 // This can happen with promotions that actually don't change the
2874 // underlying type, like the enum promotions.
2875 if (value->getType() == varType) return value;
2876
2877 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
2878 && "unexpected promotion type");
2879
2880 if (isa<llvm::IntegerType>(varType))
2881 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2882
2883 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2884}
2885
2886/// Returns the attribute (either parameter attribute, or function
2887/// attribute), which declares argument ArgNo to be non-null.
2888static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2889 QualType ArgType, unsigned ArgNo) {
2890 // FIXME: __attribute__((nonnull)) can also be applied to:
2891 // - references to pointers, where the pointee is known to be
2892 // nonnull (apparently a Clang extension)
2893 // - transparent unions containing pointers
2894 // In the former case, LLVM IR cannot represent the constraint. In
2895 // the latter case, we have no guarantee that the transparent union
2896 // is in fact passed as a pointer.
2897 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2898 return nullptr;
2899 // First, check attribute on parameter itself.
2900 if (PVD) {
2901 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2902 return ParmNNAttr;
2903 }
2904 // Check function attributes.
2905 if (!FD)
2906 return nullptr;
2907 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
2908 if (NNAttr->isNonNull(ArgNo))
2909 return NNAttr;
2910 }
2911 return nullptr;
2912}
2913
2914namespace {
2915 struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2916 Address Temp;
2917 Address Arg;
2918 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
2919 void Emit(CodeGenFunction &CGF, Flags flags) override {
2920 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2921 CGF.Builder.CreateStore(errorValue, Arg);
2922 }
2923 };
2924}
2925
2927 llvm::Function *Fn,
2928 const FunctionArgList &Args) {
2929 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
2930 // Naked functions don't have prologues.
2931 return;
2932
2933 // If this is an implicit-return-zero function, go ahead and
2934 // initialize the return value. TODO: it might be nice to have
2935 // a more general mechanism for this that didn't require synthesized
2936 // return statements.
2937 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
2938 if (FD->hasImplicitReturnZero()) {
2939 QualType RetTy = FD->getReturnType().getUnqualifiedType();
2940 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
2941 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
2943 }
2944 }
2945
2946 // FIXME: We no longer need the types from FunctionArgList; lift up and
2947 // simplify.
2948
2949 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
2950 assert(Fn->arg_size() == IRFunctionArgs.totalIRArgs());
2951
2952 // If we're using inalloca, all the memory arguments are GEPs off of the last
2953 // parameter, which is a pointer to the complete memory area.
2954 Address ArgStruct = Address::invalid();
2955 if (IRFunctionArgs.hasInallocaArg())
2956 ArgStruct = Address(Fn->getArg(IRFunctionArgs.getInallocaArgNo()),
2958
2959 // Name the struct return parameter.
2960 if (IRFunctionArgs.hasSRetArg()) {
2961 auto AI = Fn->getArg(IRFunctionArgs.getSRetArgNo());
2962 AI->setName("agg.result");
2963 AI->addAttr(llvm::Attribute::NoAlias);
2964 }
2965
2966 // Track if we received the parameter as a pointer (indirect, byval, or
2967 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
2968 // into a local alloca for us.
2970 ArgVals.reserve(Args.size());
2971
2972 // Create a pointer value for every parameter declaration. This usually
2973 // entails copying one or more LLVM IR arguments into an alloca. Don't push
2974 // any cleanups or do anything that might unwind. We do that separately, so
2975 // we can push the cleanups in the correct order for the ABI.
2976 assert(FI.arg_size() == Args.size() &&
2977 "Mismatch between function signature & arguments.");
2978 unsigned ArgNo = 0;
2980 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
2981 i != e; ++i, ++info_it, ++ArgNo) {
2982 const VarDecl *Arg = *i;
2983 const ABIArgInfo &ArgI = info_it->info;
2984
2985 bool isPromoted =
2986 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
2987 // We are converting from ABIArgInfo type to VarDecl type directly, unless
2988 // the parameter is promoted. In this case we convert to
2989 // CGFunctionInfo::ArgInfo type with subsequent argument demotion.
2990 QualType Ty = isPromoted ? info_it->type : Arg->getType();
2991 assert(hasScalarEvaluationKind(Ty) ==
2993
2994 unsigned FirstIRArg, NumIRArgs;
2995 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2996
2997 switch (ArgI.getKind()) {
2998 case ABIArgInfo::InAlloca: {
2999 assert(NumIRArgs == 0);
3000 auto FieldIndex = ArgI.getInAllocaFieldIndex();
3001 Address V =
3002 Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName());
3003 if (ArgI.getInAllocaIndirect())
3005 getContext().getTypeAlignInChars(Ty));
3006 ArgVals.push_back(ParamValue::forIndirect(V));
3007 break;
3008 }
3009
3012 assert(NumIRArgs == 1);
3014 Fn->getArg(FirstIRArg), Ty, ArgI.getIndirectAlign(), false, nullptr,
3015 nullptr, KnownNonNull);
3016
3017 if (!hasScalarEvaluationKind(Ty)) {
3018 // Aggregates and complex variables are accessed by reference. All we
3019 // need to do is realign the value, if requested. Also, if the address
3020 // may be aliased, copy it to ensure that the parameter variable is
3021 // mutable and has a unique adress, as C requires.
3022 if (ArgI.getIndirectRealign() || ArgI.isIndirectAliased()) {
3023 RawAddress AlignedTemp = CreateMemTemp(Ty, "coerce");
3024
3025 // Copy from the incoming argument pointer to the temporary with the
3026 // appropriate alignment.
3027 //
3028 // FIXME: We should have a common utility for generating an aggregate
3029 // copy.
3032 AlignedTemp.getPointer(), AlignedTemp.getAlignment().getAsAlign(),
3033 ParamAddr.emitRawPointer(*this),
3034 ParamAddr.getAlignment().getAsAlign(),
3035 llvm::ConstantInt::get(IntPtrTy, Size.getQuantity()));
3036 ParamAddr = AlignedTemp;
3037 }
3038 ArgVals.push_back(ParamValue::forIndirect(ParamAddr));
3039 } else {
3040 // Load scalar value from indirect argument.
3041 llvm::Value *V =
3042 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc());
3043
3044 if (isPromoted)
3045 V = emitArgumentDemotion(*this, Arg, V);
3046 ArgVals.push_back(ParamValue::forDirect(V));
3047 }
3048 break;
3049 }
3050
3051 case ABIArgInfo::Extend:
3052 case ABIArgInfo::Direct: {
3053 auto AI = Fn->getArg(FirstIRArg);
3054 llvm::Type *LTy = ConvertType(Arg->getType());
3055
3056 // Prepare parameter attributes. So far, only attributes for pointer
3057 // parameters are prepared. See
3058 // http://llvm.org/docs/LangRef.html#paramattrs.
3059 if (ArgI.getDirectOffset() == 0 && LTy->isPointerTy() &&
3060 ArgI.getCoerceToType()->isPointerTy()) {
3061 assert(NumIRArgs == 1);
3062
3063 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
3064 // Set `nonnull` attribute if any.
3065 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
3066 PVD->getFunctionScopeIndex()) &&
3067 !CGM.getCodeGenOpts().NullPointerIsValid)
3068 AI->addAttr(llvm::Attribute::NonNull);
3069
3070 QualType OTy = PVD->getOriginalType();
3071 if (const auto *ArrTy =
3072 getContext().getAsConstantArrayType(OTy)) {
3073 // A C99 array parameter declaration with the static keyword also
3074 // indicates dereferenceability, and if the size is constant we can
3075 // use the dereferenceable attribute (which requires the size in
3076 // bytes).
3077 if (ArrTy->getSizeModifier() == ArraySizeModifier::Static) {
3078 QualType ETy = ArrTy->getElementType();
3079 llvm::Align Alignment =
3081 AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(Alignment));
3082 uint64_t ArrSize = ArrTy->getZExtSize();
3083 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
3084 ArrSize) {
3085 llvm::AttrBuilder Attrs(getLLVMContext());
3086 Attrs.addDereferenceableAttr(
3087 getContext().getTypeSizeInChars(ETy).getQuantity() *
3088 ArrSize);
3089 AI->addAttrs(Attrs);
3090 } else if (getContext().getTargetInfo().getNullPointerValue(
3091 ETy.getAddressSpace()) == 0 &&
3092 !CGM.getCodeGenOpts().NullPointerIsValid) {
3093 AI->addAttr(llvm::Attribute::NonNull);
3094 }
3095 }
3096 } else if (const auto *ArrTy =
3097 getContext().getAsVariableArrayType(OTy)) {
3098 // For C99 VLAs with the static keyword, we don't know the size so
3099 // we can't use the dereferenceable attribute, but in addrspace(0)
3100 // we know that it must be nonnull.
3101 if (ArrTy->getSizeModifier() == ArraySizeModifier::Static) {
3102 QualType ETy = ArrTy->getElementType();
3103 llvm::Align Alignment =
3105 AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(Alignment));
3106 if (!getTypes().getTargetAddressSpace(ETy) &&
3107 !CGM.getCodeGenOpts().NullPointerIsValid)
3108 AI->addAttr(llvm::Attribute::NonNull);
3109 }
3110 }
3111
3112 // Set `align` attribute if any.
3113 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
3114 if (!AVAttr)
3115 if (const auto *TOTy = OTy->getAs<TypedefType>())
3116 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
3117 if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) {
3118 // If alignment-assumption sanitizer is enabled, we do *not* add
3119 // alignment attribute here, but emit normal alignment assumption,
3120 // so the UBSAN check could function.
3121 llvm::ConstantInt *AlignmentCI =
3122 cast<llvm::ConstantInt>(EmitScalarExpr(AVAttr->getAlignment()));
3123 uint64_t AlignmentInt =
3124 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment);
3125 if (AI->getParamAlign().valueOrOne() < AlignmentInt) {
3126 AI->removeAttr(llvm::Attribute::AttrKind::Alignment);
3127 AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(
3128 llvm::Align(AlignmentInt)));
3129 }
3130 }
3131 }
3132
3133 // Set 'noalias' if an argument type has the `restrict` qualifier.
3134 if (Arg->getType().isRestrictQualified())
3135 AI->addAttr(llvm::Attribute::NoAlias);
3136 }
3137
3138 // Prepare the argument value. If we have the trivial case, handle it
3139 // with no muss and fuss.
3140 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
3141 ArgI.getCoerceToType() == ConvertType(Ty) &&
3142 ArgI.getDirectOffset() == 0) {
3143 assert(NumIRArgs == 1);
3144
3145 // LLVM expects swifterror parameters to be used in very restricted
3146 // ways. Copy the value into a less-restricted temporary.
3147 llvm::Value *V = AI;
3148 if (FI.getExtParameterInfo(ArgNo).getABI()
3150 QualType pointeeTy = Ty->getPointeeType();
3151 assert(pointeeTy->isPointerType());
3152 RawAddress temp =
3153 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
3155 V, pointeeTy, getContext().getTypeAlignInChars(pointeeTy));
3156 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
3157 Builder.CreateStore(incomingErrorValue, temp);
3158 V = temp.getPointer();
3159
3160 // Push a cleanup to copy the value back at the end of the function.
3161 // The convention does not guarantee that the value will be written
3162 // back if the function exits with an unwind exception.
3163 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
3164 }
3165
3166 // Ensure the argument is the correct type.
3167 if (V->getType() != ArgI.getCoerceToType())
3168 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
3169
3170 if (isPromoted)
3171 V = emitArgumentDemotion(*this, Arg, V);
3172
3173 // Because of merging of function types from multiple decls it is
3174 // possible for the type of an argument to not match the corresponding
3175 // type in the function type. Since we are codegening the callee
3176 // in here, add a cast to the argument type.
3177 llvm::Type *LTy = ConvertType(Arg->getType());
3178 if (V->getType() != LTy)
3179 V = Builder.CreateBitCast(V, LTy);
3180
3181 ArgVals.push_back(ParamValue::forDirect(V));
3182 break;
3183 }
3184
3185 // VLST arguments are coerced to VLATs at the function boundary for
3186 // ABI consistency. If this is a VLST that was coerced to
3187 // a VLAT at the function boundary and the types match up, use
3188 // llvm.vector.extract to convert back to the original VLST.
3189 if (auto *VecTyTo = dyn_cast<llvm::FixedVectorType>(ConvertType(Ty))) {
3190 llvm::Value *Coerced = Fn->getArg(FirstIRArg);
3191 if (auto *VecTyFrom =
3192 dyn_cast<llvm::ScalableVectorType>(Coerced->getType())) {
3193 // If we are casting a scalable i1 predicate vector to a fixed i8
3194 // vector, bitcast the source and use a vector extract.
3195 if (VecTyFrom->getElementType()->isIntegerTy(1) &&
3196 VecTyFrom->getElementCount().isKnownMultipleOf(8) &&
3197 VecTyTo->getElementType() == Builder.getInt8Ty()) {
3198 VecTyFrom = llvm::ScalableVectorType::get(
3199 VecTyTo->getElementType(),
3200 VecTyFrom->getElementCount().getKnownMinValue() / 8);
3201 Coerced = Builder.CreateBitCast(Coerced, VecTyFrom);
3202 }
3203 if (VecTyFrom->getElementType() == VecTyTo->getElementType()) {
3204 llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty);
3205
3206 assert(NumIRArgs == 1);
3207 Coerced->setName(Arg->getName() + ".coerce");
3208 ArgVals.push_back(ParamValue::forDirect(Builder.CreateExtractVector(
3209 VecTyTo, Coerced, Zero, "cast.fixed")));
3210 break;
3211 }
3212 }
3213 }
3214
3215 llvm::StructType *STy =
3216 dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
3217 if (ArgI.isDirect() && !ArgI.getCanBeFlattened() && STy &&
3218 STy->getNumElements() > 1) {
3219 [[maybe_unused]] llvm::TypeSize StructSize =
3220 CGM.getDataLayout().getTypeAllocSize(STy);
3221 [[maybe_unused]] llvm::TypeSize PtrElementSize =
3222 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(Ty));
3223 if (STy->containsHomogeneousScalableVectorTypes()) {
3224 assert(StructSize == PtrElementSize &&
3225 "Only allow non-fractional movement of structure with"
3226 "homogeneous scalable vector type");
3227
3228 ArgVals.push_back(ParamValue::forDirect(AI));
3229 break;
3230 }
3231 }
3232
3233 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
3234 Arg->getName());
3235
3236 // Pointer to store into.
3237 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
3238
3239 // Fast-isel and the optimizer generally like scalar values better than
3240 // FCAs, so we flatten them if this is safe to do for this argument.
3241 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
3242 STy->getNumElements() > 1) {
3243 llvm::TypeSize StructSize = CGM.getDataLayout().getTypeAllocSize(STy);
3244 llvm::TypeSize PtrElementSize =
3245 CGM.getDataLayout().getTypeAllocSize(Ptr.getElementType());
3246 if (StructSize.isScalable()) {
3247 assert(STy->containsHomogeneousScalableVectorTypes() &&
3248 "ABI only supports structure with homogeneous scalable vector "
3249 "type");
3250 assert(StructSize == PtrElementSize &&
3251 "Only allow non-fractional movement of structure with"
3252 "homogeneous scalable vector type");
3253 assert(STy->getNumElements() == NumIRArgs);
3254
3255 llvm::Value *LoadedStructValue = llvm::PoisonValue::get(STy);
3256 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3257 auto *AI = Fn->getArg(FirstIRArg + i);
3258 AI->setName(Arg->getName() + ".coerce" + Twine(i));
3259 LoadedStructValue =
3260 Builder.CreateInsertValue(LoadedStructValue, AI, i);
3261 }
3262
3263 Builder.CreateStore(LoadedStructValue, Ptr);
3264 } else {
3265 uint64_t SrcSize = StructSize.getFixedValue();
3266 uint64_t DstSize = PtrElementSize.getFixedValue();
3267
3268 Address AddrToStoreInto = Address::invalid();
3269 if (SrcSize <= DstSize) {
3270 AddrToStoreInto = Ptr.withElementType(STy);
3271 } else {
3272 AddrToStoreInto =
3273 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
3274 }
3275
3276 assert(STy->getNumElements() == NumIRArgs);
3277 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3278 auto AI = Fn->getArg(FirstIRArg + i);
3279 AI->setName(Arg->getName() + ".coerce" + Twine(i));
3280 Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i);
3281 Builder.CreateStore(AI, EltPtr);
3282 }
3283
3284 if (SrcSize > DstSize) {
3285 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
3286 }
3287 }
3288 } else {
3289 // Simple case, just do a coerced store of the argument into the alloca.
3290 assert(NumIRArgs == 1);
3291 auto AI = Fn->getArg(FirstIRArg);
3292 AI->setName(Arg->getName() + ".coerce");
3294 AI, Ptr,
3295 llvm::TypeSize::getFixed(
3296 getContext().getTypeSizeInChars(Ty).getQuantity() -
3297 ArgI.getDirectOffset()),
3298 /*DstIsVolatile=*/false);
3299 }
3300
3301 // Match to what EmitParmDecl is expecting for this type.
3303 llvm::Value *V =
3304 EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc());
3305 if (isPromoted)
3306 V = emitArgumentDemotion(*this, Arg, V);
3307 ArgVals.push_back(ParamValue::forDirect(V));
3308 } else {
3309 ArgVals.push_back(ParamValue::forIndirect(Alloca));
3310 }
3311 break;
3312 }
3313
3315 // Reconstruct into a temporary.
3316 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
3317 ArgVals.push_back(ParamValue::forIndirect(alloca));
3318
3319 auto coercionType = ArgI.getCoerceAndExpandType();
3320 alloca = alloca.withElementType(coercionType);
3321
3322 unsigned argIndex = FirstIRArg;
3323 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3324 llvm::Type *eltType = coercionType->getElementType(i);
3326 continue;
3327
3328 auto eltAddr = Builder.CreateStructGEP(alloca, i);
3329 auto elt = Fn->getArg(argIndex++);
3330 Builder.CreateStore(elt, eltAddr);
3331 }
3332 assert(argIndex == FirstIRArg + NumIRArgs);
3333 break;
3334 }
3335
3336 case ABIArgInfo::Expand: {
3337 // If this structure was expanded into multiple arguments then
3338 // we need to create a temporary and reconstruct it from the
3339 // arguments.
3340 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
3341 LValue LV = MakeAddrLValue(Alloca, Ty);
3342 ArgVals.push_back(ParamValue::forIndirect(Alloca));
3343
3344 auto FnArgIter = Fn->arg_begin() + FirstIRArg;
3345 ExpandTypeFromArgs(Ty, LV, FnArgIter);
3346 assert(FnArgIter == Fn->arg_begin() + FirstIRArg + NumIRArgs);
3347 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
3348 auto AI = Fn->getArg(FirstIRArg + i);
3349 AI->setName(Arg->getName() + "." + Twine(i));
3350 }
3351 break;
3352 }
3353
3354 case ABIArgInfo::Ignore:
3355 assert(NumIRArgs == 0);
3356 // Initialize the local variable appropriately.
3357 if (!hasScalarEvaluationKind(Ty)) {
3358 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
3359 } else {
3360 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
3361 ArgVals.push_back(ParamValue::forDirect(U));
3362 }
3363 break;
3364 }
3365 }
3366
3367 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3368 for (int I = Args.size() - 1; I >= 0; --I)
3369 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
3370 } else {
3371 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3372 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
3373 }
3374}
3375
3376static void eraseUnusedBitCasts(llvm::Instruction *insn) {
3377 while (insn->use_empty()) {
3378 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
3379 if (!bitcast) return;
3380
3381 // This is "safe" because we would have used a ConstantExpr otherwise.
3382 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
3383 bitcast->eraseFromParent();
3384 }
3385}
3386
3387/// Try to emit a fused autorelease of a return result.
3389 llvm::Value *result) {
3390 // We must be immediately followed the cast.
3391 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
3392 if (BB->empty()) return nullptr;
3393 if (&BB->back() != result) return nullptr;
3394
3395 llvm::Type *resultType = result->getType();
3396
3397 // result is in a BasicBlock and is therefore an Instruction.
3398 llvm::Instruction *generator = cast<llvm::Instruction>(result);
3399
3401
3402 // Look for:
3403 // %generator = bitcast %type1* %generator2 to %type2*
3404 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
3405 // We would have emitted this as a constant if the operand weren't
3406 // an Instruction.
3407 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
3408
3409 // Require the generator to be immediately followed by the cast.
3410 if (generator->getNextNode() != bitcast)
3411 return nullptr;
3412
3413 InstsToKill.push_back(bitcast);
3414 }
3415
3416 // Look for:
3417 // %generator = call i8* @objc_retain(i8* %originalResult)
3418 // or
3419 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
3420 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
3421 if (!call) return nullptr;
3422
3423 bool doRetainAutorelease;
3424
3425 if (call->getCalledOperand() == CGF.CGM.getObjCEntrypoints().objc_retain) {
3426 doRetainAutorelease = true;
3427 } else if (call->getCalledOperand() ==
3429 doRetainAutorelease = false;
3430
3431 // If we emitted an assembly marker for this call (and the
3432 // ARCEntrypoints field should have been set if so), go looking
3433 // for that call. If we can't find it, we can't do this
3434 // optimization. But it should always be the immediately previous
3435 // instruction, unless we needed bitcasts around the call.
3437 llvm::Instruction *prev = call->getPrevNode();
3438 assert(prev);
3439 if (isa<llvm::BitCastInst>(prev)) {
3440 prev = prev->getPrevNode();
3441 assert(prev);
3442 }
3443 assert(isa<llvm::CallInst>(prev));
3444 assert(cast<llvm::CallInst>(prev)->getCalledOperand() ==
3446 InstsToKill.push_back(prev);
3447 }
3448 } else {
3449 return nullptr;
3450 }
3451
3452 result = call->getArgOperand(0);
3453 InstsToKill.push_back(call);
3454
3455 // Keep killing bitcasts, for sanity. Note that we no longer care
3456 // about precise ordering as long as there's exactly one use.
3457 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
3458 if (!bitcast->hasOneUse()) break;
3459 InstsToKill.push_back(bitcast);
3460 result = bitcast->getOperand(0);
3461 }
3462
3463 // Delete all the unnecessary instructions, from latest to earliest.
3464 for (auto *I : InstsToKill)
3465 I->eraseFromParent();
3466
3467 // Do the fused retain/autorelease if we were asked to.
3468 if (doRetainAutorelease)
3469 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
3470
3471 // Cast back to the result type.
3472 return CGF.Builder.CreateBitCast(result, resultType);
3473}
3474
3475/// If this is a +1 of the value of an immutable 'self', remove it.
3477 llvm::Value *result) {
3478 // This is only applicable to a method with an immutable 'self'.
3479 const ObjCMethodDecl *method =
3480 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
3481 if (!method) return nullptr;
3482 const VarDecl *self = method->getSelfDecl();
3483 if (!self->getType().isConstQualified()) return nullptr;
3484
3485 // Look for a retain call. Note: stripPointerCasts looks through returned arg
3486 // functions, which would cause us to miss the retain.
3487 llvm::CallInst *retainCall = dyn_cast<llvm::CallInst>(result);
3488 if (!retainCall || retainCall->getCalledOperand() !=
3490 return nullptr;
3491
3492 // Look for an ordinary load of 'self'.
3493 llvm::Value *retainedValue = retainCall->getArgOperand(0);
3494 llvm::LoadInst *load =
3495 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
3496 if (!load || load->isAtomic() || load->isVolatile() ||
3497 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getBasePointer())
3498 return nullptr;
3499
3500 // Okay! Burn it all down. This relies for correctness on the
3501 // assumption that the retain is emitted as part of the return and
3502 // that thereafter everything is used "linearly".
3503 llvm::Type *resultType = result->getType();
3504 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
3505 assert(retainCall->use_empty());
3506 retainCall->eraseFromParent();
3507 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
3508
3509 return CGF.Builder.CreateBitCast(load, resultType);
3510}
3511
3512/// Emit an ARC autorelease of the result of a function.
3513///
3514/// \return the value to actually return from the function
3516 llvm::Value *result) {
3517 // If we're returning 'self', kill the initial retain. This is a
3518 // heuristic attempt to "encourage correctness" in the really unfortunate
3519 // case where we have a return of self during a dealloc and we desperately
3520 // need to avoid the possible autorelease.
3521 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
3522 return self;
3523
3524 // At -O0, try to emit a fused retain/autorelease.
3525 if (CGF.shouldUseFusedARCCalls())
3526 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
3527 return fused;
3528
3529 return CGF.EmitARCAutoreleaseReturnValue(result);
3530}
3531
3532/// Heuristically search for a dominating store to the return-value slot.
3534 llvm::Value *ReturnValuePtr = CGF.ReturnValue.getBasePointer();
3535
3536 // Check if a User is a store which pointerOperand is the ReturnValue.
3537 // We are looking for stores to the ReturnValue, not for stores of the
3538 // ReturnValue to some other location.
3539 auto GetStoreIfValid = [&CGF,
3540 ReturnValuePtr](llvm::User *U) -> llvm::StoreInst * {
3541 auto *SI = dyn_cast<llvm::StoreInst>(U);
3542 if (!SI || SI->getPointerOperand() != ReturnValuePtr ||
3543 SI->getValueOperand()->getType() != CGF.ReturnValue.getElementType())
3544 return nullptr;
3545 // These aren't actually possible for non-coerced returns, and we
3546 // only care about non-coerced returns on this code path.
3547 // All memory instructions inside __try block are volatile.
3548 assert(!SI->isAtomic() &&
3549 (!SI->isVolatile() || CGF.currentFunctionUsesSEHTry()));
3550 return SI;
3551 };
3552 // If there are multiple uses of the return-value slot, just check
3553 // for something immediately preceding the IP. Sometimes this can
3554 // happen with how we generate implicit-returns; it can also happen
3555 // with noreturn cleanups.
3556 if (!ReturnValuePtr->hasOneUse()) {
3557 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
3558 if (IP->empty()) return nullptr;
3559
3560 // Look at directly preceding instruction, skipping bitcasts and lifetime
3561 // markers.
3562 for (llvm::Instruction &I : make_range(IP->rbegin(), IP->rend())) {
3563 if (isa<llvm::BitCastInst>(&I))
3564 continue;
3565 if (auto *II = dyn_cast<llvm::IntrinsicInst>(&I))
3566 if (II->getIntrinsicID() == llvm::Intrinsic::lifetime_end)
3567 continue;
3568
3569 return GetStoreIfValid(&I);
3570 }
3571 return nullptr;
3572 }
3573
3574 llvm::StoreInst *store = GetStoreIfValid(ReturnValuePtr->user_back());
3575 if (!store) return nullptr;
3576
3577 // Now do a first-and-dirty dominance check: just walk up the
3578 // single-predecessors chain from the current insertion point.
3579 llvm::BasicBlock *StoreBB = store->getParent();
3580 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
3582 while (IP != StoreBB) {
3583 if (!SeenBBs.insert(IP).second || !(IP = IP->getSinglePredecessor()))
3584 return nullptr;
3585 }
3586
3587 // Okay, the store's basic block dominates the insertion point; we
3588 // can do our thing.
3589 return store;
3590}
3591
3592// Helper functions for EmitCMSEClearRecord
3593
3594// Set the bits corresponding to a field having width `BitWidth` and located at
3595// offset `BitOffset` (from the least significant bit) within a storage unit of
3596// `Bits.size()` bytes. Each element of `Bits` corresponds to one target byte.
3597// Use little-endian layout, i.e.`Bits[0]` is the LSB.
3598static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int BitOffset,
3599 int BitWidth, int CharWidth) {
3600 assert(CharWidth <= 64);
3601 assert(static_cast<unsigned>(BitWidth) <= Bits.size() * CharWidth);
3602
3603 int Pos = 0;
3604 if (BitOffset >= CharWidth) {
3605 Pos += BitOffset / CharWidth;
3606 BitOffset = BitOffset % CharWidth;
3607 }
3608
3609 const uint64_t Used = (uint64_t(1) << CharWidth) - 1;
3610 if (BitOffset + BitWidth >= CharWidth) {
3611 Bits[Pos++] |= (Used << BitOffset) & Used;
3612 BitWidth -= CharWidth - BitOffset;
3613 BitOffset = 0;
3614 }
3615
3616 while (BitWidth >= CharWidth) {
3617 Bits[Pos++] = Used;
3618 BitWidth -= CharWidth;
3619 }
3620
3621 if (BitWidth > 0)
3622 Bits[Pos++] |= (Used >> (CharWidth - BitWidth)) << BitOffset;
3623}
3624
3625// Set the bits corresponding to a field having width `BitWidth` and located at
3626// offset `BitOffset` (from the least significant bit) within a storage unit of
3627// `StorageSize` bytes, located at `StorageOffset` in `Bits`. Each element of
3628// `Bits` corresponds to one target byte. Use target endian layout.
3629static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int StorageOffset,
3630 int StorageSize, int BitOffset, int BitWidth,
3631 int CharWidth, bool BigEndian) {
3632
3633 SmallVector<uint64_t, 8> TmpBits(StorageSize);
3634 setBitRange(TmpBits, BitOffset, BitWidth, CharWidth);
3635
3636 if (BigEndian)
3637 std::reverse(TmpBits.begin(), TmpBits.end());
3638
3639 for (uint64_t V : TmpBits)
3640 Bits[StorageOffset++] |= V;
3641}
3642
3643static void setUsedBits(CodeGenModule &, QualType, int,
3645
3646// Set the bits in `Bits`, which correspond to the value representations of
3647// the actual members of the record type `RTy`. Note that this function does
3648// not handle base classes, virtual tables, etc, since they cannot happen in
3649// CMSE function arguments or return. The bit mask corresponds to the target
3650// memory layout, i.e. it's endian dependent.
3651static void setUsedBits(CodeGenModule &CGM, const RecordType *RTy, int Offset,
3653 ASTContext &Context = CGM.getContext();
3654 int CharWidth = Context.getCharWidth();
3655 const RecordDecl *RD = RTy->getDecl()->getDefinition();
3656 const ASTRecordLayout &ASTLayout = Context.getASTRecordLayout(RD);
3657 const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(RD);
3658
3659 int Idx = 0;
3660 for (auto I = RD->field_begin(), E = RD->field_end(); I != E; ++I, ++Idx) {
3661 const FieldDecl *F = *I;
3662
3663 if (F->isUnnamedBitField() || F->isZeroLengthBitField(Context) ||
3665 continue;
3666
3667 if (F->isBitField()) {
3668 const CGBitFieldInfo &BFI = Layout.getBitFieldInfo(F);
3669 setBitRange(Bits, Offset + BFI.StorageOffset.getQuantity(),
3670 BFI.StorageSize / CharWidth, BFI.Offset,
3671 BFI.Size, CharWidth,
3672 CGM.getDataLayout().isBigEndian());
3673 continue;
3674 }
3675
3676 setUsedBits(CGM, F->getType(),
3677 Offset + ASTLayout.getFieldOffset(Idx) / CharWidth, Bits);
3678 }
3679}
3680
3681// Set the bits in `Bits`, which correspond to the value representations of
3682// the elements of an array type `ATy`.
3683static void setUsedBits(CodeGenModule &CGM, const ConstantArrayType *ATy,
3684 int Offset, SmallVectorImpl<uint64_t> &Bits) {
3685 const ASTContext &Context = CGM.getContext();
3686
3687 QualType ETy = Context.getBaseElementType(ATy);
3688 int Size = Context.getTypeSizeInChars(ETy).getQuantity();
3689 SmallVector<uint64_t, 4> TmpBits(Size);
3690 setUsedBits(CGM, ETy, 0, TmpBits);
3691
3692 for (int I = 0, N = Context.getConstantArrayElementCount(ATy); I < N; ++I) {
3693 auto Src = TmpBits.begin();
3694 auto Dst = Bits.begin() + Offset + I * Size;
3695 for (int J = 0; J < Size; ++J)
3696 *Dst++ |= *Src++;
3697 }
3698}
3699
3700// Set the bits in `Bits`, which correspond to the value representations of
3701// the type `QTy`.
3702static void setUsedBits(CodeGenModule &CGM, QualType QTy, int Offset,
3704 if (const auto *RTy = QTy->getAs<RecordType>())
3705 return setUsedBits(CGM, RTy, Offset, Bits);
3706
3707 ASTContext &Context = CGM.getContext();
3708 if (const auto *ATy = Context.getAsConstantArrayType(QTy))
3709 return setUsedBits(CGM, ATy, Offset, Bits);
3710
3711 int Size = Context.getTypeSizeInChars(QTy).getQuantity();
3712 if (Size <= 0)
3713 return;
3714
3715 std::fill_n(Bits.begin() + Offset, Size,
3716 (uint64_t(1) << Context.getCharWidth()) - 1);
3717}
3718
3720 int Pos, int Size, int CharWidth,
3721 bool BigEndian) {
3722 assert(Size > 0);
3723 uint64_t Mask = 0;
3724 if (BigEndian) {
3725 for (auto P = Bits.begin() + Pos, E = Bits.begin() + Pos + Size; P != E;
3726 ++P)
3727 Mask = (Mask << CharWidth) | *P;
3728 } else {
3729 auto P = Bits.begin() + Pos + Size, End = Bits.begin() + Pos;
3730 do
3731 Mask = (Mask << CharWidth) | *--P;
3732 while (P != End);
3733 }
3734 return Mask;
3735}
3736
3737// Emit code to clear the bits in a record, which aren't a part of any user
3738// declared member, when the record is a function return.
3739llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3740 llvm::IntegerType *ITy,
3741 QualType QTy) {
3742 assert(Src->getType() == ITy);
3743 assert(ITy->getScalarSizeInBits() <= 64);
3744
3745 const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3746 int Size = DataLayout.getTypeStoreSize(ITy);
3747 SmallVector<uint64_t, 4> Bits(Size);
3748 setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
3749
3750 int CharWidth = CGM.getContext().getCharWidth();
3751 uint64_t Mask =
3752 buildMultiCharMask(Bits, 0, Size, CharWidth, DataLayout.isBigEndian());
3753
3754 return Builder.CreateAnd(Src, Mask, "cmse.clear");
3755}
3756
3757// Emit code to clear the bits in a record, which aren't a part of any user
3758// declared member, when the record is a function argument.
3759llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3760 llvm::ArrayType *ATy,
3761 QualType QTy) {
3762 const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3763 int Size = DataLayout.getTypeStoreSize(ATy);
3764 SmallVector<uint64_t, 16> Bits(Size);
3765 setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
3766
3767 // Clear each element of the LLVM array.
3768 int CharWidth = CGM.getContext().getCharWidth();
3769 int CharsPerElt =
3770 ATy->getArrayElementType()->getScalarSizeInBits() / CharWidth;
3771 int MaskIndex = 0;
3772 llvm::Value *R = llvm::PoisonValue::get(ATy);
3773 for (int I = 0, N = ATy->getArrayNumElements(); I != N; ++I) {
3774 uint64_t Mask = buildMultiCharMask(Bits, MaskIndex, CharsPerElt, CharWidth,
3775 DataLayout.isBigEndian());
3776 MaskIndex += CharsPerElt;
3777 llvm::Value *T0 = Builder.CreateExtractValue(Src, I);
3778 llvm::Value *T1 = Builder.CreateAnd(T0, Mask, "cmse.clear");
3779 R = Builder.CreateInsertValue(R, T1, I);
3780 }
3781
3782 return R;
3783}
3784
3786 bool EmitRetDbgLoc,
3787 SourceLocation EndLoc) {
3788 if (FI.isNoReturn()) {
3789 // Noreturn functions don't return.
3790 EmitUnreachable(EndLoc);
3791 return;
3792 }
3793
3794 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
3795 // Naked functions don't have epilogues.
3796 Builder.CreateUnreachable();
3797 return;
3798 }
3799
3800 // Functions with no result always return void.
3801 if (!ReturnValue.isValid()) {
3802 Builder.CreateRetVoid();
3803 return;
3804 }
3805
3806 llvm::DebugLoc RetDbgLoc;
3807 llvm::Value *RV = nullptr;
3808 QualType RetTy = FI.getReturnType();
3809 const ABIArgInfo &RetAI = FI.getReturnInfo();
3810
3811 switch (RetAI.getKind()) {
3813 // Aggregates get evaluated directly into the destination. Sometimes we
3814 // need to return the sret value in a register, though.
3815 assert(hasAggregateEvaluationKind(RetTy));
3816 if (RetAI.getInAllocaSRet()) {
3817 llvm::Function::arg_iterator EI = CurFn->arg_end();
3818 --EI;
3819 llvm::Value *ArgStruct = &*EI;
3820 llvm::Value *SRet = Builder.CreateStructGEP(
3821 FI.getArgStruct(), ArgStruct, RetAI.getInAllocaFieldIndex());
3822 llvm::Type *Ty =
3823 cast<llvm::GetElementPtrInst>(SRet)->getResultElementType();
3824 RV = Builder.CreateAlignedLoad(Ty, SRet, getPointerAlign(), "sret");
3825 }
3826 break;
3827
3828 case ABIArgInfo::Indirect: {
3829 auto AI = CurFn->arg_begin();
3830 if (RetAI.isSRetAfterThis())
3831 ++AI;
3832 switch (getEvaluationKind(RetTy)) {
3833 case TEK_Complex: {
3834 ComplexPairTy RT =
3837 /*isInit*/ true);
3838 break;
3839 }
3840 case TEK_Aggregate:
3841 // Do nothing; aggregates get evaluated directly into the destination.
3842 break;
3843 case TEK_Scalar: {
3844 LValueBaseInfo BaseInfo;
3845 TBAAAccessInfo TBAAInfo;
3846 CharUnits Alignment =
3847 CGM.getNaturalTypeAlignment(RetTy, &BaseInfo, &TBAAInfo);
3848 Address ArgAddr(&*AI, ConvertType(RetTy), Alignment);
3849 LValue ArgVal =
3850 LValue::MakeAddr(ArgAddr, RetTy, getContext(), BaseInfo, TBAAInfo);
3852 EmitLoadOfScalar(MakeAddrLValue(ReturnValue, RetTy), EndLoc), ArgVal,
3853 /*isInit*/ true);
3854 break;
3855 }
3856 }
3857 break;
3858 }
3859
3860 case ABIArgInfo::Extend:
3861 case ABIArgInfo::Direct:
3862 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
3863 RetAI.getDirectOffset() == 0) {
3864 // The internal return value temp always will have pointer-to-return-type
3865 // type, just do a load.
3866
3867 // If there is a dominating store to ReturnValue, we can elide
3868 // the load, zap the store, and usually zap the alloca.
3869 if (llvm::StoreInst *SI =
3871 // Reuse the debug location from the store unless there is
3872 // cleanup code to be emitted between the store and return
3873 // instruction.
3874 if (EmitRetDbgLoc && !AutoreleaseResult)
3875 RetDbgLoc = SI->getDebugLoc();
3876 // Get the stored value and nuke the now-dead store.
3877 RV = SI->getValueOperand();
3878 SI->eraseFromParent();
3879
3880 // Otherwise, we have to do a simple load.
3881 } else {
3883 }
3884 } else {
3885 // If the value is offset in memory, apply the offset now.
3886 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
3887
3888 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
3889 }
3890
3891 // In ARC, end functions that return a retainable type with a call
3892 // to objc_autoreleaseReturnValue.
3893 if (AutoreleaseResult) {
3894#ifndef NDEBUG
3895 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
3896 // been stripped of the typedefs, so we cannot use RetTy here. Get the
3897 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
3898 // CurCodeDecl or BlockInfo.
3899 QualType RT;
3900
3901 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
3902 RT = FD->getReturnType();
3903 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
3904 RT = MD->getReturnType();
3905 else if (isa<BlockDecl>(CurCodeDecl))
3907 else
3908 llvm_unreachable("Unexpected function/method type");
3909
3910 assert(getLangOpts().ObjCAutoRefCount &&
3911 !FI.isReturnsRetained() &&
3912 RT->isObjCRetainableType());
3913#endif
3914 RV = emitAutoreleaseOfResult(*this, RV);
3915 }
3916
3917 break;
3918
3919 case ABIArgInfo::Ignore:
3920 break;
3921
3923 auto coercionType = RetAI.getCoerceAndExpandType();
3924
3925 // Load all of the coerced elements out into results.
3927 Address addr = ReturnValue.withElementType(coercionType);
3928 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3929 auto coercedEltType = coercionType->getElementType(i);
3930 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
3931 continue;
3932
3933 auto eltAddr = Builder.CreateStructGEP(addr, i);
3934 auto elt = Builder.CreateLoad(eltAddr);
3935 results.push_back(elt);
3936 }
3937
3938 // If we have one result, it's the single direct result type.
3939 if (results.size() == 1) {
3940 RV = results[0];
3941
3942 // Otherwise, we need to make a first-class aggregate.
3943 } else {
3944 // Construct a return type that lacks padding elements.
3945 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
3946
3947 RV = llvm::PoisonValue::get(returnType);
3948 for (unsigned i = 0, e = results.size(); i != e; ++i) {
3949 RV = Builder.CreateInsertValue(RV, results[i], i);
3950 }
3951 }
3952 break;
3953 }
3954 case ABIArgInfo::Expand:
3956 llvm_unreachable("Invalid ABI kind for return argument");
3957 }
3958
3959 llvm::Instruction *Ret;
3960 if (RV) {
3961 if (CurFuncDecl && CurFuncDecl->hasAttr<CmseNSEntryAttr>()) {
3962 // For certain return types, clear padding bits, as they may reveal
3963 // sensitive information.
3964 // Small struct/union types are passed as integers.
3965 auto *ITy = dyn_cast<llvm::IntegerType>(RV->getType());
3966 if (ITy != nullptr && isa<RecordType>(RetTy.getCanonicalType()))
3967 RV = EmitCMSEClearRecord(RV, ITy, RetTy);
3968 }
3970 Ret = Builder.CreateRet(RV);
3971 } else {
3972 Ret = Builder.CreateRetVoid();
3973 }
3974
3975 if (RetDbgLoc)
3976 Ret->setDebugLoc(std::move(RetDbgLoc));
3977}
3978
3979void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) {
3980 // A current decl may not be available when emitting vtable thunks.
3981 if (!CurCodeDecl)
3982 return;
3983
3984 // If the return block isn't reachable, neither is this check, so don't emit
3985 // it.
3986 if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty())
3987 return;
3988
3989 ReturnsNonNullAttr *RetNNAttr = nullptr;
3990 if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
3991 RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
3992
3993 if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
3994 return;
3995
3996 // Prefer the returns_nonnull attribute if it's present.
3997 SourceLocation AttrLoc;
3998 SanitizerMask CheckKind;
3999 SanitizerHandler Handler;
4000 if (RetNNAttr) {
4001 assert(!requiresReturnValueNullabilityCheck() &&
4002 "Cannot check nullability and the nonnull attribute");
4003 AttrLoc = RetNNAttr->getLocation();
4004 CheckKind = SanitizerKind::ReturnsNonnullAttribute;
4005 Handler = SanitizerHandler::NonnullReturn;
4006 } else {
4007 if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl))
4008 if (auto *TSI = DD->getTypeSourceInfo())
4009 if (auto FTL = TSI->getTypeLoc().getAsAdjusted<FunctionTypeLoc>())
4010 AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
4011 CheckKind = SanitizerKind::NullabilityReturn;
4012 Handler = SanitizerHandler::NullabilityReturn;
4013 }
4014
4015 SanitizerScope SanScope(this);
4016
4017 // Make sure the "return" source location is valid. If we're checking a
4018 // nullability annotation, make sure the preconditions for the check are met.
4019 llvm::BasicBlock *Check = createBasicBlock("nullcheck");
4020 llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck");
4021 llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load");
4022 llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr);
4023 if (requiresReturnValueNullabilityCheck())
4024 CanNullCheck =
4025 Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition);
4026 Builder.CreateCondBr(CanNullCheck, Check, NoCheck);
4027 EmitBlock(Check);
4028
4029 // Now do the null check.
4030 llvm::Value *Cond = Builder.CreateIsNotNull(RV);
4031 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)};
4032 llvm::Value *DynamicData[] = {SLocPtr};
4033 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData);
4034
4035 EmitBlock(NoCheck);
4036
4037#ifndef NDEBUG
4038 // The return location should not be used after the check has been emitted.
4039 ReturnLocation = Address::invalid();
4040#endif
4041}
4042
4044 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
4045 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
4046}
4047
4049 QualType Ty) {
4050 // FIXME: Generate IR in one pass, rather than going back and fixing up these
4051 // placeholders.
4052 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
4053 llvm::Type *IRPtrTy = llvm::PointerType::getUnqual(CGF.getLLVMContext());
4054 llvm::Value *Placeholder = llvm::PoisonValue::get(IRPtrTy);
4055
4056 // FIXME: When we generate this IR in one pass, we shouldn't need
4057 // this win32-specific alignment hack.
4059 Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
4060
4061 return AggValueSlot::forAddr(Address(Placeholder, IRTy, Align),
4062 Ty.getQualifiers(),
4067}
4068
4070 const VarDecl *param,
4071 SourceLocation loc) {
4072 // StartFunction converted the ABI-lowered parameter(s) into a
4073 // local alloca. We need to turn that into an r-value suitable
4074 // for EmitCall.
4075 Address local = GetAddrOfLocalVar(param);
4076
4077 QualType type = param->getType();
4078
4079 // GetAddrOfLocalVar returns a pointer-to-pointer for references,
4080 // but the argument needs to be the original pointer.
4081 if (type->isReferenceType()) {
4082 args.add(RValue::get(Builder.CreateLoad(local)), type);
4083
4084 // In ARC, move out of consumed arguments so that the release cleanup
4085 // entered by StartFunction doesn't cause an over-release. This isn't
4086 // optimal -O0 code generation, but it should get cleaned up when
4087 // optimization is enabled. This also assumes that delegate calls are
4088 // performed exactly once for a set of arguments, but that should be safe.
4089 } else if (getLangOpts().ObjCAutoRefCount &&
4090 param->hasAttr<NSConsumedAttr>() &&
4091 type->isObjCRetainableType()) {
4092 llvm::Value *ptr = Builder.CreateLoad(local);
4093 auto null =
4094 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
4095 Builder.CreateStore(null, local);
4096 args.add(RValue::get(ptr), type);
4097
4098 // For the most part, we just need to load the alloca, except that
4099 // aggregate r-values are actually pointers to temporaries.
4100 } else {
4101 args.add(convertTempToRValue(local, type, loc), type);
4102 }
4103
4104 // Deactivate the cleanup for the callee-destructed param that was pushed.
4105 if (type->isRecordType() && !CurFuncIsThunk &&
4107 param->needsDestruction(getContext())) {
4109 CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param));
4110 assert(cleanup.isValid() &&
4111 "cleanup for callee-destructed param not recorded");
4112 // This unreachable is a temporary marker which will be removed later.
4113 llvm::Instruction *isActive = Builder.CreateUnreachable();
4114 args.addArgCleanupDeactivation(cleanup, isActive);
4115 }
4116}
4117
4118static bool isProvablyNull(llvm::Value *addr) {
4119 return llvm::isa_and_nonnull<llvm::ConstantPointerNull>(addr);
4120}
4121
4123 return llvm::isKnownNonZero(Addr.getBasePointer(), CGF.CGM.getDataLayout());
4124}
4125
4126/// Emit the actual writing-back of a writeback.
4128 const CallArgList::Writeback &writeback) {
4129 const LValue &srcLV = writeback.Source;
4130 Address srcAddr = srcLV.getAddress();
4131 assert(!isProvablyNull(srcAddr.getBasePointer()) &&
4132 "shouldn't have writeback for provably null argument");
4133
4134 llvm::BasicBlock *contBB = nullptr;
4135
4136 // If the argument wasn't provably non-null, we need to null check
4137 // before doing the store.
4138 bool provablyNonNull = isProvablyNonNull(srcAddr, CGF);
4139
4140 if (!provablyNonNull) {
4141 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
4142 contBB = CGF.createBasicBlock("icr.done");
4143
4144 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
4145 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
4146 CGF.EmitBlock(writebackBB);
4147 }
4148
4149 // Load the value to writeback.
4150 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
4151
4152 // Cast it back, in case we're writing an id to a Foo* or something.
4153 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
4154 "icr.writeback-cast");
4155
4156 // Perform the writeback.
4157
4158 // If we have a "to use" value, it's something we need to emit a use
4159 // of. This has to be carefully threaded in: if it's done after the
4160 // release it's potentially undefined behavior (and the optimizer
4161 // will ignore it), and if it happens before the retain then the
4162 // optimizer could move the release there.
4163 if (writeback.ToUse) {
4164 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
4165
4166 // Retain the new value. No need to block-copy here: the block's
4167 // being passed up the stack.
4168 value = CGF.EmitARCRetainNonBlock(value);
4169
4170 // Emit the intrinsic use here.
4171 CGF.EmitARCIntrinsicUse(writeback.ToUse);
4172
4173 // Load the old value (primitively).
4174 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
4175
4176 // Put the new value in place (primitively).
4177 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
4178
4179 // Release the old value.
4180 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
4181
4182 // Otherwise, we can just do a normal lvalue store.
4183 } else {
4184 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
4185 }
4186
4187 // Jump to the continuation block.
4188 if (!provablyNonNull)
4189 CGF.EmitBlock(contBB);
4190}
4191
4193 const CallArgList &args) {
4194 for (const auto &I : args.writebacks())
4195 emitWriteback(CGF, I);
4196}
4197
4199 const CallArgList &CallArgs) {
4201 CallArgs.getCleanupsToDeactivate();
4202 // Iterate in reverse to increase the likelihood of popping the cleanup.
4203 for (const auto &I : llvm::reverse(Cleanups)) {
4204 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
4205 I.IsActiveIP->eraseFromParent();
4206 }
4207}
4208
4209static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
4210 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
4211 if (uop->getOpcode() == UO_AddrOf)
4212 return uop->getSubExpr();
4213 return nullptr;
4214}
4215
4216/// Emit an argument that's being passed call-by-writeback. That is,
4217/// we are passing the address of an __autoreleased temporary; it
4218/// might be copy-initialized with the current value of the given
4219/// address, but it will definitely be copied out of after the call.
4221 const ObjCIndirectCopyRestoreExpr *CRE) {
4222 LValue srcLV;
4223
4224 // Make an optimistic effort to emit the address as an l-value.
4225 // This can fail if the argument expression is more complicated.
4226 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
4227 srcLV = CGF.EmitLValue(lvExpr);
4228
4229 // Otherwise, just emit it as a scalar.
4230 } else {
4231 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
4232
4233 QualType srcAddrType =
4235 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
4236 }
4237 Address srcAddr = srcLV.getAddress();
4238
4239 // The dest and src types don't necessarily match in LLVM terms
4240 // because of the crazy ObjC compatibility rules.
4241
4242 llvm::PointerType *destType =
4243 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
4244 llvm::Type *destElemType =
4246
4247 // If the address is a constant null, just pass the appropriate null.
4248 if (isProvablyNull(srcAddr.getBasePointer())) {
4249 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
4250 CRE->getType());
4251 return;
4252 }
4253
4254 // Create the temporary.
4255 Address temp =
4256 CGF.CreateTempAlloca(destElemType, CGF.getPointerAlign(), "icr.temp");
4257 // Loading an l-value can introduce a cleanup if the l-value is __weak,
4258 // and that cleanup will be conditional if we can't prove that the l-value
4259 // isn't null, so we need to register a dominating point so that the cleanups
4260 // system will make valid IR.
4261 CodeGenFunction::ConditionalEvaluation condEval(CGF);
4262
4263 // Zero-initialize it if we're not doing a copy-initialization.
4264 bool shouldCopy = CRE->shouldCopy();
4265 if (!shouldCopy) {
4266 llvm::Value *null =
4267 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(destElemType));
4268 CGF.Builder.CreateStore(null, temp);
4269 }
4270
4271 llvm::BasicBlock *contBB = nullptr;
4272 llvm::BasicBlock *originBB = nullptr;
4273
4274 // If the address is *not* known to be non-null, we need to switch.
4275 llvm::Value *finalArgument;
4276
4277 bool provablyNonNull = isProvablyNonNull(srcAddr, CGF);
4278
4279 if (provablyNonNull) {
4280 finalArgument = temp.emitRawPointer(CGF);
4281 } else {
4282 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
4283
4284 finalArgument = CGF.Builder.CreateSelect(
4285 isNull, llvm::ConstantPointerNull::get(destType),
4286 temp.emitRawPointer(CGF), "icr.argument");
4287
4288 // If we need to copy, then the load has to be conditional, which
4289 // means we need control flow.
4290 if (shouldCopy) {
4291 originBB = CGF.Builder.GetInsertBlock();
4292 contBB = CGF.createBasicBlock("icr.cont");
4293 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
4294 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
4295 CGF.EmitBlock(copyBB);
4296 condEval.begin(CGF);
4297 }
4298 }
4299
4300 llvm::Value *valueToUse = nullptr;
4301
4302 // Perform a copy if necessary.
4303 if (shouldCopy) {
4304 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
4305 assert(srcRV.isScalar());
4306
4307 llvm::Value *src = srcRV.getScalarVal();
4308 src = CGF.Builder.CreateBitCast(src, destElemType, "icr.cast");
4309
4310 // Use an ordinary store, not a store-to-lvalue.
4311 CGF.Builder.CreateStore(src, temp);
4312
4313 // If optimization is enabled, and the value was held in a
4314 // __strong variable, we need to tell the optimizer that this
4315 // value has to stay alive until we're doing the store back.
4316 // This is because the temporary is effectively unretained,
4317 // and so otherwise we can violate the high-level semantics.
4318 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
4320 valueToUse = src;
4321 }
4322 }
4323
4324 // Finish the control flow if we needed it.
4325 if (shouldCopy && !provablyNonNull) {
4326 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
4327 CGF.EmitBlock(contBB);
4328
4329 // Make a phi for the value to intrinsically use.
4330 if (valueToUse) {
4331 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
4332 "icr.to-use");
4333 phiToUse->addIncoming(valueToUse, copyBB);
4334 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
4335 originBB);
4336 valueToUse = phiToUse;
4337 }
4338
4339 condEval.end(CGF);
4340 }
4341
4342 args.addWriteback(srcLV, temp, valueToUse);
4343 args.add(RValue::get(finalArgument), CRE->getType());
4344}
4345
4347 assert(!StackBase);
4348
4349 // Save the stack.
4350 StackBase = CGF.Builder.CreateStackSave("inalloca.save");
4351}
4352
4354 if (StackBase) {
4355 // Restore the stack after the call.
4356 CGF.Builder.CreateStackRestore(StackBase);
4357 }
4358}
4359
4361 SourceLocation ArgLoc,
4362 AbstractCallee AC,
4363 unsigned ParmNum) {
4364 if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
4365 SanOpts.has(SanitizerKind::NullabilityArg)))
4366 return;
4367
4368 // The param decl may be missing in a variadic function.
4369 auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr;
4370 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
4371
4372 // Prefer the nonnull attribute if it's present.
4373 const NonNullAttr *NNAttr = nullptr;
4374 if (SanOpts.has(SanitizerKind::NonnullAttribute))
4375 NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
4376
4377 bool CanCheckNullability = false;
4378 if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD &&
4379 !PVD->getType()->isRecordType()) {
4380 auto Nullability = PVD->getType()->getNullability();
4381 CanCheckNullability = Nullability &&
4382 *Nullability == NullabilityKind::NonNull &&
4383 PVD->getTypeSourceInfo();
4384 }
4385
4386 if (!NNAttr && !CanCheckNullability)
4387 return;
4388
4389 SourceLocation AttrLoc;
4390 SanitizerMask CheckKind;
4391 SanitizerHandler Handler;
4392 if (NNAttr) {
4393 AttrLoc = NNAttr->getLocation();
4394 CheckKind = SanitizerKind::NonnullAttribute;
4395 Handler = SanitizerHandler::NonnullArg;
4396 } else {
4397 AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
4398 CheckKind = SanitizerKind::NullabilityArg;
4399 Handler = SanitizerHandler::NullabilityArg;
4400 }
4401
4402 SanitizerScope SanScope(this);
4403 llvm::Value *Cond = EmitNonNullRValueCheck(RV, ArgType);
4404 llvm::Constant *StaticData[] = {
4406 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
4407 };
4408 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, std::nullopt);
4409}
4410
4412 SourceLocation ArgLoc,
4413 AbstractCallee AC, unsigned ParmNum) {
4414 if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
4415 SanOpts.has(SanitizerKind::NullabilityArg)))
4416 return;
4417
4418 EmitNonNullArgCheck(RValue::get(Addr, *this), ArgType, ArgLoc, AC, ParmNum);
4419}
4420
4421// Check if the call is going to use the inalloca convention. This needs to
4422// agree with CGFunctionInfo::usesInAlloca. The CGFunctionInfo is arranged
4423// later, so we can't check it directly.
4424static bool hasInAllocaArgs(CodeGenModule &CGM, CallingConv ExplicitCC,
4425 ArrayRef<QualType> ArgTypes) {
4426 // The Swift calling conventions don't go through the target-specific
4427 // argument classification, they never use inalloca.
4428 // TODO: Consider limiting inalloca use to only calling conventions supported
4429 // by MSVC.
4430 if (ExplicitCC == CC_Swift || ExplicitCC == CC_SwiftAsync)
4431 return false;
4432 if (!CGM.getTarget().getCXXABI().isMicrosoft())
4433 return false;
4434 return llvm::any_of(ArgTypes, [&](QualType Ty) {
4435 return isInAllocaArgument(CGM.getCXXABI(), Ty);
4436 });
4437}
4438
4439#ifndef NDEBUG
4440// Determine whether the given argument is an Objective-C method
4441// that may have type parameters in its signature.
4442static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
4443 const DeclContext *dc = method->getDeclContext();
4444 if (const ObjCInterfaceDecl *classDecl = dyn_cast<ObjCInterfaceDecl>(dc)) {
4445 return classDecl->getTypeParamListAsWritten();
4446 }
4447
4448 if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
4449 return catDecl->getTypeParamList();
4450 }
4451
4452 return false;
4453}
4454#endif
4455
4456/// EmitCallArgs - Emit call arguments for a function.
4458 CallArgList &Args, PrototypeWrapper Prototype,
4459 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
4460 AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
4462
4463 assert((ParamsToSkip == 0 || Prototype.P) &&
4464 "Can't skip parameters if type info is not provided");
4465
4466 // This variable only captures *explicitly* written conventions, not those
4467 // applied by default via command line flags or target defaults, such as
4468 // thiscall, aapcs, stdcall via -mrtd, etc. Computing that correctly would
4469 // require knowing if this is a C++ instance method or being able to see
4470 // unprototyped FunctionTypes.
4471 CallingConv ExplicitCC = CC_C;
4472
4473 // First, if a prototype was provided, use those argument types.
4474 bool IsVariadic = false;
4475 if (Prototype.P) {
4476 const auto *MD = Prototype.P.dyn_cast<const ObjCMethodDecl *>();
4477 if (MD) {
4478 IsVariadic = MD->isVariadic();
4479 ExplicitCC = getCallingConventionForDecl(
4480 MD, CGM.getTarget().getTriple().isOSWindows());
4481 ArgTypes.assign(MD->param_type_begin() + ParamsToSkip,
4482 MD->param_type_end());
4483 } else {
4484 const auto *FPT = Prototype.P.get<const FunctionProtoType *>();
4485 IsVariadic = FPT->isVariadic();
4486 ExplicitCC = FPT->getExtInfo().getCC();
4487 ArgTypes.assign(FPT->param_type_begin() + ParamsToSkip,
4488 FPT->param_type_end());
4489 }
4490
4491#ifndef NDEBUG
4492 // Check that the prototyped types match the argument expression types.
4493 bool isGenericMethod = MD && isObjCMethodWithTypeParams(MD);
4494 CallExpr::const_arg_iterator Arg = ArgRange.begin();
4495 for (QualType Ty : ArgTypes) {
4496 assert(Arg != ArgRange.end() && "Running over edge of argument list!");
4497 assert(
4498 (isGenericMethod || Ty->isVariablyModifiedType() ||
4499 Ty.getNonReferenceType()->isObjCRetainableType() ||
4500 getContext()
4501 .getCanonicalType(Ty.getNonReferenceType())
4502 .getTypePtr() ==
4503 getContext().getCanonicalType((*Arg)->getType()).getTypePtr()) &&
4504 "type mismatch in call argument!");
4505 ++Arg;
4506 }
4507
4508 // Either we've emitted all the call args, or we have a call to variadic
4509 // function.
4510 assert((Arg == ArgRange.end() || IsVariadic) &&
4511 "Extra arguments in non-variadic function!");
4512#endif
4513 }
4514
4515 // If we still have any arguments, emit them using the type of the argument.
4516 for (auto *A : llvm::drop_begin(ArgRange, ArgTypes.size()))
4517 ArgTypes.push_back(IsVariadic ? getVarArgType(A) : A->getType());
4518 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
4519
4520 // We must evaluate arguments from right to left in the MS C++ ABI,
4521 // because arguments are destroyed left to right in the callee. As a special
4522 // case, there are certain language constructs that require left-to-right
4523 // evaluation, and in those cases we consider the evaluation order requirement
4524 // to trump the "destruction order is reverse construction order" guarantee.
4525 bool LeftToRight =
4529
4530 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
4531 RValue EmittedArg) {
4532 if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
4533 return;
4534 auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
4535 if (PS == nullptr)
4536 return;
4537
4538 const auto &Context = getContext();
4539 auto SizeTy = Context.getSizeType();
4540 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
4541 assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?");
4542 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
4543 EmittedArg.getScalarVal(),
4544 PS->isDynamic());
4545 Args.add(RValue::get(V), SizeTy);
4546 // If we're emitting args in reverse, be sure to do so with
4547 // pass_object_size, as well.
4548 if (!LeftToRight)
4549 std::swap(Args.back(), *(&Args.back() - 1));
4550 };
4551
4552 // Insert a stack save if we're going to need any inalloca args.
4553 if (hasInAllocaArgs(CGM, ExplicitCC, ArgTypes)) {
4554 assert(getTarget().getTriple().getArch() == llvm::Triple::x86 &&
4555 "inalloca only supported on x86");
4556 Args.allocateArgumentMemory(*this);
4557 }
4558
4559 // Evaluate each argument in the appropriate order.
4560 size_t CallArgsStart = Args.size();
4561 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
4562 unsigned Idx = LeftToRight ? I : E - I - 1;
4563 CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
4564 unsigned InitialArgSize = Args.size();
4565 // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of
4566 // the argument and parameter match or the objc method is parameterized.
4567 assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) ||
4568 getContext().hasSameUnqualifiedType((*Arg)->getType(),
4569 ArgTypes[Idx]) ||
4570 (isa<ObjCMethodDecl>(AC.getDecl()) &&
4571 isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) &&
4572 "Argument and parameter types don't match");
4573 EmitCallArg(Args, *Arg, ArgTypes[Idx]);
4574 // In particular, we depend on it being the last arg in Args, and the
4575 // objectsize bits depend on there only being one arg if !LeftToRight.
4576 assert(InitialArgSize + 1 == Args.size() &&
4577 "The code below depends on only adding one arg per EmitCallArg");
4578 (void)InitialArgSize;
4579 // Since pointer argument are never emitted as LValue, it is safe to emit
4580 // non-null argument check for r-value only.
4581 if (!Args.back().hasLValue()) {
4582 RValue RVArg = Args.back().getKnownRValue();
4583 EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
4584 ParamsToSkip + Idx);
4585 // @llvm.objectsize should never have side-effects and shouldn't need
4586 // destruction/cleanups, so we can safely "emit" it after its arg,
4587 // regardless of right-to-leftness
4588 MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
4589 }
4590 }
4591
4592 if (!LeftToRight) {
4593 // Un-reverse the arguments we just evaluated so they match up with the LLVM
4594 // IR function.
4595 std::reverse(Args.begin() + CallArgsStart, Args.end());
4596 }
4597}
4598
4599namespace {
4600
4601struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
4602 DestroyUnpassedArg(Address Addr, QualType Ty)
4603 : Addr(Addr), Ty(Ty) {}
4604
4605 Address Addr;
4606 QualType Ty;
4607
4608 void Emit(CodeGenFunction &CGF, Flags flags) override {
4610 if (DtorKind == QualType::DK_cxx_destructor) {
4611 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
4612 assert(!Dtor->isTrivial());
4613 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
4614 /*Delegating=*/false, Addr, Ty);
4615 } else {
4616 CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty));
4617 }
4618 }
4619};
4620
4621struct DisableDebugLocationUpdates {
4622 CodeGenFunction &CGF;
4623 bool disabledDebugInfo;
4624 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
4625 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
4626 CGF.disableDebugInfo();
4627 }
4628 ~DisableDebugLocationUpdates() {
4629 if (disabledDebugInfo)
4630 CGF.enableDebugInfo();
4631 }
4632};
4633
4634} // end anonymous namespace
4635
4637 if (!HasLV)
4638 return RV;
4641 LV.isVolatile());
4642 IsUsed = true;
4643 return RValue::getAggregate(Copy.getAddress());
4644}
4645
4647 LValue Dst = CGF.MakeAddrLValue(Addr, Ty);
4648 if (!HasLV && RV.isScalar())
4649 CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*isInit=*/true);
4650 else if (!HasLV && RV.isComplex())
4651 CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true);
4652 else {
4653 auto Addr = HasLV ? LV.getAddress() : RV.getAggregateAddress();
4654 LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty);
4655 // We assume that call args are never copied into subobjects.
4657 HasLV ? LV.isVolatileQualified()
4659 }
4660 IsUsed = true;
4661}
4662
4664 QualType type) {
4665 DisableDebugLocationUpdates Dis(*this, E);
4666 if (const ObjCIndirectCopyRestoreExpr *CRE
4667 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
4668 assert(getLangOpts().ObjCAutoRefCount);
4669 return emitWritebackArg(*this, args, CRE);
4670 }
4671
4672 assert(type->isReferenceType() == E->isGLValue() &&
4673 "reference binding to unmaterialized r-value!");
4674
4675 if (E->isGLValue()) {
4676 assert(E->getObjectKind() == OK_Ordinary);
4677 return args.add(EmitReferenceBindingToExpr(E), type);
4678 }
4679
4680 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
4681
4682 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
4683 // However, we still have to push an EH-only cleanup in case we unwind before
4684 // we make it to the call.
4685 if (type->isRecordType() &&
4687 // If we're using inalloca, use the argument memory. Otherwise, use a
4688 // temporary.
4689 AggValueSlot Slot = args.isUsingInAlloca()
4690 ? createPlaceholderSlot(*this, type) : CreateAggTemp(type, "agg.tmp");
4691
4692 bool DestroyedInCallee = true, NeedsCleanup = true;
4693 if (const auto *RD = type->getAsCXXRecordDecl())
4694 DestroyedInCallee = RD->hasNonTrivialDestructor();
4695 else
4696 NeedsCleanup = type.isDestructedType();
4697
4698 if (DestroyedInCallee)
4700
4701 EmitAggExpr(E, Slot);
4702 RValue RV = Slot.asRValue();
4703 args.add(RV, type);
4704
4705 if (DestroyedInCallee && NeedsCleanup) {
4706 // Create a no-op GEP between the placeholder and the cleanup so we can
4707 // RAUW it successfully. It also serves as a marker of the first
4708 // instruction where the cleanup is active.
4709 pushFullExprCleanup<DestroyUnpassedArg>(NormalAndEHCleanup,
4710 Slot.getAddress(), type);
4711 // This unreachable is a temporary marker which will be removed later.
4712 llvm::Instruction *IsActive =
4713 Builder.CreateFlagLoad(llvm::Constant::getNullValue(Int8PtrTy));
4715 }
4716 return;
4717 }
4718
4719 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
4720 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue &&
4721 !type->isArrayParameterType()) {
4722 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
4723 assert(L.isSimple());
4724 args.addUncopiedAggregate(L, type);
4725 return;
4726 }
4727
4728 args.add(EmitAnyExprToTemp(E), type);
4729}
4730
4731QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
4732 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
4733 // implicitly widens null pointer constants that are arguments to varargs
4734 // functions to pointer-sized ints.
4735 if (!getTarget().getTriple().isOSWindows())
4736 return Arg->getType();
4737
4738 if (Arg->getType()->isIntegerType() &&
4739 getContext().getTypeSize(Arg->getType()) <
4740 getContext().getTargetInfo().getPointerWidth(LangAS::Default) &&
4743 return getContext().getIntPtrType();
4744 }
4745
4746 return Arg->getType();
4747}
4748
4749// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4750// optimizer it can aggressively ignore unwind edges.
4751void
4752CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
4753 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
4754 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
4755 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
4757}
4758
4759/// Emits a call to the given no-arguments nounwind runtime function.
4760llvm::CallInst *
4761CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4762 const llvm::Twine &name) {
4763 return EmitNounwindRuntimeCall(callee, ArrayRef<llvm::Value *>(), name);
4764}
4765
4766/// Emits a call to the given nounwind runtime function.
4767llvm::CallInst *
4768CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4769 ArrayRef<Address> args,
4770 const llvm::Twine &name) {
4772 for (auto arg : args)
4773 values.push_back(arg.emitRawPointer(*this));
4774 return EmitNounwindRuntimeCall(callee, values, name);
4775}
4776
4777llvm::CallInst *
4778CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4780 const llvm::Twine &name) {
4781 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
4782 call->setDoesNotThrow();
4783 return call;
4784}
4785
4786/// Emits a simple call (never an invoke) to the given no-arguments
4787/// runtime function.
4788llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
4789 const llvm::Twine &name) {
4790 return EmitRuntimeCall(callee, std::nullopt, name);
4791}
4792
4793// Calls which may throw must have operand bundles indicating which funclet
4794// they are nested within.
4796CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) {
4797 // There is no need for a funclet operand bundle if we aren't inside a
4798 // funclet.
4799 if (!CurrentFuncletPad)
4801
4802 // Skip intrinsics which cannot throw (as long as they don't lower into
4803 // regular function calls in the course of IR transformations).
4804 if (auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts())) {
4805 if (CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow()) {
4806 auto IID = CalleeFn->getIntrinsicID();
4807 if (!llvm::IntrinsicInst::mayLowerToFunctionCall(IID))
4809 }
4810 }
4811
4813 BundleList.emplace_back("funclet", CurrentFuncletPad);
4814 return BundleList;
4815}
4816
4817/// Emits a simple call (never an invoke) to the given runtime function.
4818llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
4820 const llvm::Twine &name) {
4821 llvm::CallInst *call = Builder.CreateCall(
4822 callee, args, getBundlesForFunclet(callee.getCallee()), name);
4823 call->setCallingConv(getRuntimeCC());
4824
4825 if (CGM.shouldEmitConvergenceTokens() && call->isConvergent())
4826 return addControlledConvergenceToken(call);
4827 return call;
4828}
4829
4830/// Emits a call or invoke to the given noreturn runtime function.
4832 llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) {
4834 getBundlesForFunclet(callee.getCallee());
4835
4836 if (getInvokeDest()) {
4837 llvm::InvokeInst *invoke =
4838 Builder.CreateInvoke(callee,
4840 getInvokeDest(),
4841 args,
4842 BundleList);
4843 invoke->setDoesNotReturn();
4844 invoke->setCallingConv(getRuntimeCC());
4845 } else {
4846 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
4847 call->setDoesNotReturn();
4848 call->setCallingConv(getRuntimeCC());
4849 Builder.CreateUnreachable();
4850 }
4851}
4852
4853/// Emits a call or invoke instruction to the given nullary runtime function.
4854llvm::CallBase *
4855CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4856 const Twine &name) {
4857 return EmitRuntimeCallOrInvoke(callee, std::nullopt, name);
4858}
4859
4860/// Emits a call or invoke instruction to the given runtime function.
4861llvm::CallBase *
4862CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4864 const Twine &name) {
4865 llvm::CallBase *call = EmitCallOrInvoke(callee, args, name);
4866 call->setCallingConv(getRuntimeCC());
4867 return call;
4868}
4869
4870/// Emits a call or invoke instruction to the given function, depending
4871/// on the current state of the EH stack.
4872llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee,
4874 const Twine &Name) {
4875 llvm::BasicBlock *InvokeDest = getInvokeDest();
4877 getBundlesForFunclet(Callee.getCallee());
4878
4879 llvm::CallBase *Inst;
4880 if (!InvokeDest)
4881 Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
4882 else {
4883 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
4884 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
4885 Name);
4886 EmitBlock(ContBB);
4887 }
4888
4889 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4890 // optimizer it can aggressively ignore unwind edges.
4891 if (CGM.getLangOpts().ObjCAutoRefCount)
4892 AddObjCARCExceptionMetadata(Inst);
4893
4894 return Inst;
4895}
4896
4897void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
4898 llvm::Value *New) {
4899 DeferredReplacements.push_back(
4900 std::make_pair(llvm::WeakTrackingVH(Old), New));
4901}
4902
4903namespace {
4904
4905/// Specify given \p NewAlign as the alignment of return value attribute. If
4906/// such attribute already exists, re-set it to the maximal one of two options.
4907[[nodiscard]] llvm::AttributeList
4908maybeRaiseRetAlignmentAttribute(llvm::LLVMContext &Ctx,
4909 const llvm::AttributeList &Attrs,
4910 llvm::Align NewAlign) {
4911 llvm::Align CurAlign = Attrs.getRetAlignment().valueOrOne();
4912 if (CurAlign >= NewAlign)
4913 return Attrs;
4914 llvm::Attribute AlignAttr = llvm::Attribute::getWithAlignment(Ctx, NewAlign);
4915 return Attrs.removeRetAttribute(Ctx, llvm::Attribute::AttrKind::Alignment)
4916 .addRetAttribute(Ctx, AlignAttr);
4917}
4918
4919template <typename AlignedAttrTy> class AbstractAssumeAlignedAttrEmitter {
4920protected:
4921 CodeGenFunction &CGF;
4922
4923 /// We do nothing if this is, or becomes, nullptr.
4924 const AlignedAttrTy *AA = nullptr;
4925
4926 llvm::Value *Alignment = nullptr; // May or may not be a constant.
4927 llvm::ConstantInt *OffsetCI = nullptr; // Constant, hopefully zero.
4928
4929 AbstractAssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
4930 : CGF(CGF_) {
4931 if (!FuncDecl)
4932 return;
4933 AA = FuncDecl->getAttr<AlignedAttrTy>();
4934 }
4935
4936public:
4937 /// If we can, materialize the alignment as an attribute on return value.
4938 [[nodiscard]] llvm::AttributeList
4939 TryEmitAsCallSiteAttribute(const llvm::AttributeList &Attrs) {
4940 if (!AA || OffsetCI || CGF.SanOpts.has(SanitizerKind::Alignment))
4941 return Attrs;
4942 const auto *AlignmentCI = dyn_cast<llvm::ConstantInt>(Alignment);
4943 if (!AlignmentCI)
4944 return Attrs;
4945 // We may legitimately have non-power-of-2 alignment here.
4946 // If so, this is UB land, emit it via `@llvm.assume` instead.
4947 if (!AlignmentCI->getValue().isPowerOf2())
4948 return Attrs;
4949 llvm::AttributeList NewAttrs = maybeRaiseRetAlignmentAttribute(
4950 CGF.getLLVMContext(), Attrs,
4951 llvm::Align(
4952 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment)));
4953 AA = nullptr; // We're done. Disallow doing anything else.
4954 return NewAttrs;
4955 }
4956
4957 /// Emit alignment assumption.
4958 /// This is a general fallback that we take if either there is an offset,
4959 /// or the alignment is variable or we are sanitizing for alignment.
4960 void EmitAsAnAssumption(SourceLocation Loc, QualType RetTy, RValue &Ret) {
4961 if (!AA)
4962 return;
4963 CGF.emitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc,
4964 AA->getLocation(), Alignment, OffsetCI);
4965 AA = nullptr; // We're done. Disallow doing anything else.
4966 }
4967};
4968
4969/// Helper data structure to emit `AssumeAlignedAttr`.
4970class AssumeAlignedAttrEmitter final
4971 : public AbstractAssumeAlignedAttrEmitter<AssumeAlignedAttr> {
4972public:
4973 AssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
4974 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
4975 if (!AA)
4976 return;
4977 // It is guaranteed that the alignment/offset are constants.
4978 Alignment = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AA->getAlignment()));
4979 if (Expr *Offset = AA->getOffset()) {
4980 OffsetCI = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(Offset));
4981 if (OffsetCI->isNullValue()) // Canonicalize zero offset to no offset.
4982 OffsetCI = nullptr;
4983 }
4984 }
4985};
4986
4987/// Helper data structure to emit `AllocAlignAttr`.
4988class AllocAlignAttrEmitter final
4989 : public AbstractAssumeAlignedAttrEmitter<AllocAlignAttr> {
4990public:
4991 AllocAlignAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl,
4992 const CallArgList &CallArgs)
4993 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
4994 if (!AA)
4995 return;
4996 // Alignment may or may not be a constant, and that is okay.
4997 Alignment = CallArgs[AA->getParamIndex().getLLVMIndex()]
4998 .getRValue(CGF)
4999 .getScalarVal();
5000 }
5001};
5002
5003} // namespace
5004
5005static unsigned getMaxVectorWidth(const llvm::Type *Ty) {
5006 if (auto *VT = dyn_cast<llvm::VectorType>(Ty))
5007 return VT->getPrimitiveSizeInBits().getKnownMinValue();
5008 if (auto *AT = dyn_cast<llvm::ArrayType>(Ty))
5009 return getMaxVectorWidth(AT->getElementType());
5010
5011 unsigned MaxVectorWidth = 0;
5012 if (auto *ST = dyn_cast<llvm::StructType>(Ty))
5013 for (auto *I : ST->elements())
5014 MaxVectorWidth = std::max(MaxVectorWidth, getMaxVectorWidth(I));
5015 return MaxVectorWidth;
5016}
5017
5019 const CGCallee &Callee,
5020 ReturnValueSlot ReturnValue,
5021 const CallArgList &CallArgs,
5022 llvm::CallBase **callOrInvoke, bool IsMustTail,
5024 bool IsVirtualFunctionPointerThunk) {
5025 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
5026
5027 assert(Callee.isOrdinary() || Callee.isVirtual());
5028
5029 // Handle struct-return functions by passing a pointer to the
5030 // location that we would like to return into.
5031 QualType RetTy = CallInfo.getReturnType();
5032 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
5033
5034 llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
5035
5036 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
5037 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
5038 // We can only guarantee that a function is called from the correct
5039 // context/function based on the appropriate target attributes,
5040 // so only check in the case where we have both always_inline and target
5041 // since otherwise we could be making a conditional call after a check for
5042 // the proper cpu features (and it won't cause code generation issues due to
5043 // function based code generation).
5044 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
5045 (TargetDecl->hasAttr<TargetAttr>() ||
5046 (CurFuncDecl && CurFuncDecl->hasAttr<TargetAttr>())))
5048 }
5049
5050 // Some architectures (such as x86-64) have the ABI changed based on
5051 // attribute-target/features. Give them a chance to diagnose.
5053 CGM, Loc, dyn_cast_or_null<FunctionDecl>(CurCodeDecl),
5054 dyn_cast_or_null<FunctionDecl>(TargetDecl), CallArgs, RetTy);
5055
5056 // 1. Set up the arguments.
5057
5058 // If we're using inalloca, insert the allocation after the stack save.
5059 // FIXME: Do this earlier rather than hacking it in here!
5060 RawAddress ArgMemory = RawAddress::invalid();
5061 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
5062 const llvm::DataLayout &DL = CGM.getDataLayout();
5063 llvm::Instruction *IP = CallArgs.getStackBase();
5064 llvm::AllocaInst *AI;
5065 if (IP) {
5066 IP = IP->getNextNode();
5067 AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(), "argmem",
5068 IP->getIterator());
5069 } else {
5070 AI = CreateTempAlloca(ArgStruct, "argmem");
5071 }
5072 auto Align = CallInfo.getArgStructAlignment();
5073 AI->setAlignment(Align.getAsAlign());
5074 AI->setUsedWithInAlloca(true);
5075 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
5076 ArgMemory = RawAddress(AI, ArgStruct, Align);
5077 }
5078
5079 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
5080 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
5081
5082 // If the call returns a temporary with struct return, create a temporary
5083 // alloca to hold the result, unless one is given to us.
5084 Address SRetPtr = Address::invalid();
5085 RawAddress SRetAlloca = RawAddress::invalid();
5086 llvm::Value *UnusedReturnSizePtr = nullptr;
5087 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
5088 if (IsVirtualFunctionPointerThunk && RetAI.isIndirect()) {
5089 SRetPtr = makeNaturalAddressForPointer(CurFn->arg_begin() +
5090 IRFunctionArgs.getSRetArgNo(),
5091 RetTy, CharUnits::fromQuantity(1));
5092 } else if (!ReturnValue.isNull()) {
5093 SRetPtr = ReturnValue.getAddress();
5094 } else {
5095 SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca);
5096 if (HaveInsertPoint() && ReturnValue.isUnused()) {
5097 llvm::TypeSize size =
5098 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
5099 UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer());
5100 }
5101 }
5102 if (IRFunctionArgs.hasSRetArg()) {
5103 IRCallArgs[IRFunctionArgs.getSRetArgNo()] =
5104 getAsNaturalPointerTo(SRetPtr, RetTy);
5105 } else if (RetAI.isInAlloca()) {
5106 Address Addr =
5107 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
5108 Builder.CreateStore(getAsNaturalPointerTo(SRetPtr, RetTy), Addr);
5109 }
5110 }
5111
5112 RawAddress swiftErrorTemp = RawAddress::invalid();
5113 Address swiftErrorArg = Address::invalid();
5114
5115 // When passing arguments using temporary allocas, we need to add the
5116 // appropriate lifetime markers. This vector keeps track of all the lifetime
5117 // markers that need to be ended right after the call.
5118 SmallVector<CallLifetimeEnd, 2> CallLifetimeEndAfterCall;
5119
5120 // Translate all of the arguments as necessary to match the IR lowering.
5121 assert(CallInfo.arg_size() == CallArgs.size() &&
5122 "Mismatch between function signature & arguments.");
5123 unsigned ArgNo = 0;
5124 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
5125 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
5126 I != E; ++I, ++info_it, ++ArgNo) {
5127 const ABIArgInfo &ArgInfo = info_it->info;
5128
5129 // Insert a padding argument to ensure proper alignment.
5130 if (IRFunctionArgs.hasPaddingArg(ArgNo))
5131 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
5132 llvm::UndefValue::get(ArgInfo.getPaddingType());
5133
5134 unsigned FirstIRArg, NumIRArgs;
5135 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
5136
5137 bool ArgHasMaybeUndefAttr =
5138 IsArgumentMaybeUndef(TargetDecl, CallInfo.getNumRequiredArgs(), ArgNo);
5139
5140 switch (ArgInfo.getKind()) {
5141 case ABIArgInfo::InAlloca: {
5142 assert(NumIRArgs == 0);
5143 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
5144 if (I->isAggregate()) {
5145 RawAddress Addr = I->hasLValue()
5146 ? I->getKnownLValue().getAddress()
5147 : I->getKnownRValue().getAggregateAddress();
5148 llvm::Instruction *Placeholder =
5149 cast<llvm::Instruction>(Addr.getPointer());
5150
5151 if (!ArgInfo.getInAllocaIndirect()) {
5152 // Replace the placeholder with the appropriate argument slot GEP.
5153 CGBuilderTy::InsertPoint IP = Builder.saveIP();
5154 Builder.SetInsertPoint(Placeholder);
5155 Addr = Builder.CreateStructGEP(ArgMemory,
5156 ArgInfo.getInAllocaFieldIndex());
5157 Builder.restoreIP(IP);
5158 } else {
5159 // For indirect things such as overaligned structs, replace the
5160 // placeholder with a regular aggregate temporary alloca. Store the
5161 // address of this alloca into the struct.
5162 Addr = CreateMemTemp(info_it->type, "inalloca.indirect.tmp");
5164 ArgMemory, ArgInfo.getInAllocaFieldIndex());
5165 Builder.CreateStore(Addr.getPointer(), ArgSlot);
5166 }
5167 deferPlaceholderReplacement(Placeholder, Addr.getPointer());
5168 } else if (ArgInfo.getInAllocaIndirect()) {
5169 // Make a temporary alloca and store the address of it into the argument
5170 // struct.
5172 I->Ty, getContext().getTypeAlignInChars(I->Ty),
5173 "indirect-arg-temp");
5174 I->copyInto(*this, Addr);
5175 Address ArgSlot =
5176 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
5177 Builder.CreateStore(Addr.getPointer(), ArgSlot);
5178 } else {
5179 // Store the RValue into the argument struct.
5180 Address Addr =
5181 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
5182 Addr = Addr.withElementType(ConvertTypeForMem(I->Ty));
5183 I->copyInto(*this, Addr);
5184 }
5185 break;
5186 }
5187
5190 assert(NumIRArgs == 1);
5191 if (I->isAggregate()) {
5192 // We want to avoid creating an unnecessary temporary+copy here;
5193 // however, we need one in three cases:
5194 // 1. If the argument is not byval, and we are required to copy the
5195 // source. (This case doesn't occur on any common architecture.)
5196 // 2. If the argument is byval, RV is not sufficiently aligned, and
5197 // we cannot force it to be sufficiently aligned.
5198 // 3. If the argument is byval, but RV is not located in default
5199 // or alloca address space.
5200 Address Addr = I->hasLValue()
5201 ? I->getKnownLValue().getAddress()
5202 : I->getKnownRValue().getAggregateAddress();
5203 CharUnits Align = ArgInfo.getIndirectAlign();
5204 const llvm::DataLayout *TD = &CGM.getDataLayout();
5205
5206 assert((FirstIRArg >= IRFuncTy->getNumParams() ||
5207 IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() ==
5208 TD->getAllocaAddrSpace()) &&
5209 "indirect argument must be in alloca address space");
5210
5211 bool NeedCopy = false;
5212 if (Addr.getAlignment() < Align &&
5213 llvm::getOrEnforceKnownAlignment(Addr.emitRawPointer(*this),
5214 Align.getAsAlign(),
5215 *TD) < Align.getAsAlign()) {
5216 NeedCopy = true;
5217 } else if (I->hasLValue()) {
5218 auto LV = I->getKnownLValue();
5219 auto AS = LV.getAddressSpace();
5220
5221 bool isByValOrRef =
5222 ArgInfo.isIndirectAliased() || ArgInfo.getIndirectByVal();
5223
5224 if (!isByValOrRef ||
5225 (LV.getAlignment() < getContext().getTypeAlignInChars(I->Ty))) {
5226 NeedCopy = true;
5227 }
5228 if (!getLangOpts().OpenCL) {
5229 if ((isByValOrRef &&
5230 (AS != LangAS::Default &&
5231 AS != CGM.getASTAllocaAddressSpace()))) {
5232 NeedCopy = true;
5233 }
5234 }
5235 // For OpenCL even if RV is located in default or alloca address space
5236 // we don't want to perform address space cast for it.
5237 else if ((isByValOrRef &&
5238 Addr.getType()->getAddressSpace() != IRFuncTy->
5239 getParamType(FirstIRArg)->getPointerAddressSpace())) {
5240 NeedCopy = true;
5241 }
5242 }
5243
5244 if (!NeedCopy) {
5245 // Skip the extra memcpy call.
5246 llvm::Value *V = getAsNaturalPointerTo(Addr, I->Ty);
5247 auto *T = llvm::PointerType::get(
5248 CGM.getLLVMContext(), CGM.getDataLayout().getAllocaAddrSpace());
5249
5250 llvm::Value *Val = getTargetHooks().performAddrSpaceCast(
5252 true);
5253 if (ArgHasMaybeUndefAttr)
5254 Val = Builder.CreateFreeze(Val);
5255 IRCallArgs[FirstIRArg] = Val;
5256 break;
5257 }
5258 }
5259
5260 // For non-aggregate args and aggregate args meeting conditions above
5261 // we need to create an aligned temporary, and copy to it.
5263 I->Ty, ArgInfo.getIndirectAlign(), "byval-temp");
5264 llvm::Value *Val = getAsNaturalPointerTo(AI, I->Ty);
5265 if (ArgHasMaybeUndefAttr)
5266 Val = Builder.CreateFreeze(Val);
5267 IRCallArgs[FirstIRArg] = Val;
5268
5269 // Emit lifetime markers for the temporary alloca.
5270 llvm::TypeSize ByvalTempElementSize =
5271 CGM.getDataLayout().getTypeAllocSize(AI.getElementType());
5272 llvm::Value *LifetimeSize =
5273 EmitLifetimeStart(ByvalTempElementSize, AI.getPointer());
5274
5275 // Add cleanup code to emit the end lifetime marker after the call.
5276 if (LifetimeSize) // In case we disabled lifetime markers.
5277 CallLifetimeEndAfterCall.emplace_back(AI, LifetimeSize);
5278
5279 // Generate the copy.
5280 I->copyInto(*this, AI);
5281 break;
5282 }
5283
5284 case ABIArgInfo::Ignore:
5285 assert(NumIRArgs == 0);
5286 break;
5287
5288 case ABIArgInfo::Extend:
5289 case ABIArgInfo::Direct: {
5290 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
5291 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
5292 ArgInfo.getDirectOffset() == 0) {
5293 assert(NumIRArgs == 1);
5294 llvm::Value *V;
5295 if (!I->isAggregate())
5296 V = I->getKnownRValue().getScalarVal();
5297 else
5299 I->hasLValue() ? I->getKnownLValue().getAddress()
5300 : I->getKnownRValue().getAggregateAddress());
5301
5302 // Implement swifterror by copying into a new swifterror argument.
5303 // We'll write back in the normal path out of the call.
5304 if (CallInfo.getExtParameterInfo(ArgNo).getABI()
5306 assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
5307
5308 QualType pointeeTy = I->Ty->getPointeeType();
5309 swiftErrorArg = makeNaturalAddressForPointer(
5310 V, pointeeTy, getContext().getTypeAlignInChars(pointeeTy));
5311
5312 swiftErrorTemp =
5313 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
5314 V = swiftErrorTemp.getPointer();
5315 cast<llvm::AllocaInst>(V)->setSwiftError(true);
5316
5317 llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
5318 Builder.CreateStore(errorValue, swiftErrorTemp);
5319 }
5320
5321 // We might have to widen integers, but we should never truncate.
5322 if (ArgInfo.getCoerceToType() != V->getType() &&
5323 V->getType()->isIntegerTy())
5324 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
5325
5326 // If the argument doesn't match, perform a bitcast to coerce it. This
5327 // can happen due to trivial type mismatches.
5328 if (FirstIRArg < IRFuncTy->getNumParams() &&
5329 V->getType() != IRFuncTy->getParamType(FirstIRArg))
5330 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
5331
5332 if (ArgHasMaybeUndefAttr)
5333 V = Builder.CreateFreeze(V);
5334 IRCallArgs[FirstIRArg] = V;
5335 break;
5336 }
5337
5338 llvm::StructType *STy =
5339 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
5340 if (STy && ArgInfo.isDirect() && !ArgInfo.getCanBeFlattened()) {
5341 llvm::Type *SrcTy = ConvertTypeForMem(I->Ty);
5342 [[maybe_unused]] llvm::TypeSize SrcTypeSize =
5343 CGM.getDataLayout().getTypeAllocSize(SrcTy);
5344 [[maybe_unused]] llvm::TypeSize DstTypeSize =
5345 CGM.getDataLayout().getTypeAllocSize(STy);
5346 if (STy->containsHomogeneousScalableVectorTypes()) {
5347 assert(SrcTypeSize == DstTypeSize &&
5348 "Only allow non-fractional movement of structure with "
5349 "homogeneous scalable vector type");
5350
5351 IRCallArgs[FirstIRArg] = I->getKnownRValue().getScalarVal();
5352 break;
5353 }
5354 }
5355
5356 // FIXME: Avoid the conversion through memory if possible.
5357 Address Src = Address::invalid();
5358 if (!I->isAggregate()) {
5359 Src = CreateMemTemp(I->Ty, "coerce");
5360 I->copyInto(*this, Src);
5361 } else {
5362 Src = I->hasLValue() ? I->getKnownLValue().getAddress()
5363 : I->getKnownRValue().getAggregateAddress();
5364 }
5365
5366 // If the value is offset in memory, apply the offset now.
5367 Src = emitAddressAtOffset(*this, Src, ArgInfo);
5368
5369 // Fast-isel and the optimizer generally like scalar values better than
5370 // FCAs, so we flatten them if this is safe to do for this argument.
5371 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
5372 llvm::Type *SrcTy = Src.getElementType();
5373 llvm::TypeSize SrcTypeSize =
5374 CGM.getDataLayout().getTypeAllocSize(SrcTy);
5375 llvm::TypeSize DstTypeSize = CGM.getDataLayout().getTypeAllocSize(STy);
5376 if (SrcTypeSize.isScalable()) {
5377 assert(STy->containsHomogeneousScalableVectorTypes() &&
5378 "ABI only supports structure with homogeneous scalable vector "
5379 "type");
5380 assert(SrcTypeSize == DstTypeSize &&
5381 "Only allow non-fractional movement of structure with "
5382 "homogeneous scalable vector type");
5383 assert(NumIRArgs == STy->getNumElements());
5384
5385 llvm::Value *StoredStructValue =
5386 Builder.CreateLoad(Src, Src.getName() + ".tuple");
5387 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
5388 llvm::Value *Extract = Builder.CreateExtractValue(
5389 StoredStructValue, i, Src.getName() + ".extract" + Twine(i));
5390 IRCallArgs[FirstIRArg + i] = Extract;
5391 }
5392 } else {
5393 uint64_t SrcSize = SrcTypeSize.getFixedValue();
5394 uint64_t DstSize = DstTypeSize.getFixedValue();
5395
5396 // If the source type is smaller than the destination type of the
5397 // coerce-to logic, copy the source value into a temp alloca the size
5398 // of the destination type to allow loading all of it. The bits past
5399 // the source value are left undef.
5400 if (SrcSize < DstSize) {
5401 Address TempAlloca = CreateTempAlloca(STy, Src.getAlignment(),
5402 Src.getName() + ".coerce");
5403 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
5404 Src = TempAlloca;
5405 } else {
5406 Src = Src.withElementType(STy);
5407 }
5408
5409 assert(NumIRArgs == STy->getNumElements());
5410 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
5411 Address EltPtr = Builder.CreateStructGEP(Src, i);
5412 llvm::Value *LI = Builder.CreateLoad(EltPtr);
5413 if (ArgHasMaybeUndefAttr)
5414 LI = Builder.CreateFreeze(LI);
5415 IRCallArgs[FirstIRArg + i] = LI;
5416 }
5417 }
5418 } else {
5419 // In the simple case, just pass the coerced loaded value.
5420 assert(NumIRArgs == 1);
5421 llvm::Value *Load =
5422 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
5423
5424 if (CallInfo.isCmseNSCall()) {
5425 // For certain parameter types, clear padding bits, as they may reveal
5426 // sensitive information.
5427 // Small struct/union types are passed as integer arrays.
5428 auto *ATy = dyn_cast<llvm::ArrayType>(Load->getType());
5429 if (ATy != nullptr && isa<RecordType>(I->Ty.getCanonicalType()))
5430 Load = EmitCMSEClearRecord(Load, ATy, I->Ty);
5431 }
5432
5433 if (ArgHasMaybeUndefAttr)
5434 Load = Builder.CreateFreeze(Load);
5435 IRCallArgs[FirstIRArg] = Load;
5436 }
5437
5438 break;
5439 }
5440
5442 auto coercionType = ArgInfo.getCoerceAndExpandType();
5443 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
5444
5445 llvm::Value *tempSize = nullptr;
5446 Address addr = Address::invalid();
5447 RawAddress AllocaAddr = RawAddress::invalid();
5448 if (I->isAggregate()) {
5449 addr = I->hasLValue() ? I->getKnownLValue().getAddress()
5450 : I->getKnownRValue().getAggregateAddress();
5451
5452 } else {
5453 RValue RV = I->getKnownRValue();
5454 assert(RV.isScalar()); // complex should always just be direct
5455
5456 llvm::Type *scalarType = RV.getScalarVal()->getType();
5457 auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
5458 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlign(scalarType);
5459
5460 // Materialize to a temporary.
5461 addr = CreateTempAlloca(
5462 RV.getScalarVal()->getType(),
5463 CharUnits::fromQuantity(std::max(layout->getAlignment(), scalarAlign)),
5464 "tmp",
5465 /*ArraySize=*/nullptr, &AllocaAddr);
5466 tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer());
5467
5468 Builder.CreateStore(RV.getScalarVal(), addr);
5469 }
5470
5471 addr = addr.withElementType(coercionType);
5472
5473 unsigned IRArgPos = FirstIRArg;
5474 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
5475 llvm::Type *eltType = coercionType->getElementType(i);
5476 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
5477 Address eltAddr = Builder.CreateStructGEP(addr, i);
5478 llvm::Value *elt = Builder.CreateLoad(eltAddr);
5479 if (ArgHasMaybeUndefAttr)
5480 elt = Builder.CreateFreeze(elt);
5481 IRCallArgs[IRArgPos++] = elt;
5482 }
5483 assert(IRArgPos == FirstIRArg + NumIRArgs);
5484
5485 if (tempSize) {
5486 EmitLifetimeEnd(tempSize, AllocaAddr.getPointer());
5487 }
5488
5489 break;
5490 }
5491
5492 case ABIArgInfo::Expand: {
5493 unsigned IRArgPos = FirstIRArg;
5494 ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos);
5495 assert(IRArgPos == FirstIRArg + NumIRArgs);
5496 break;
5497 }
5498 }
5499 }
5500
5501 const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this);
5502 llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer();
5503
5504 // If we're using inalloca, set up that argument.
5505 if (ArgMemory.isValid()) {
5506 llvm::Value *Arg = ArgMemory.getPointer();
5507 assert(IRFunctionArgs.hasInallocaArg());
5508 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
5509 }
5510
5511 // 2. Prepare the function pointer.
5512
5513 // If the callee is a bitcast of a non-variadic function to have a
5514 // variadic function pointer type, check to see if we can remove the
5515 // bitcast. This comes up with unprototyped functions.
5516 //
5517 // This makes the IR nicer, but more importantly it ensures that we
5518 // can inline the function at -O0 if it is marked always_inline.
5519 auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT,
5520 llvm::Value *Ptr) -> llvm::Function * {
5521 if (!CalleeFT->isVarArg())
5522 return nullptr;
5523
5524 // Get underlying value if it's a bitcast
5525 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) {
5526 if (CE->getOpcode() == llvm::Instruction::BitCast)
5527 Ptr = CE->getOperand(0);
5528 }
5529
5530 llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr);
5531 if (!OrigFn)
5532 return nullptr;
5533
5534 llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
5535
5536 // If the original type is variadic, or if any of the component types
5537 // disagree, we cannot remove the cast.
5538 if (OrigFT->isVarArg() ||
5539 OrigFT->getNumParams() != CalleeFT->getNumParams() ||
5540 OrigFT->getReturnType() != CalleeFT->getReturnType())
5541 return nullptr;
5542
5543 for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
5544 if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
5545 return nullptr;
5546
5547 return OrigFn;
5548 };
5549
5550 if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) {
5551 CalleePtr = OrigFn;
5552 IRFuncTy = OrigFn->getFunctionType();
5553 }
5554
5555 // 3. Perform the actual call.
5556
5557 // Deactivate any cleanups that we're supposed to do immediately before
5558 // the call.
5559 if (!CallArgs.getCleanupsToDeactivate().empty())
5560 deactivateArgCleanupsBeforeCall(*this, CallArgs);
5561
5562 // Assert that the arguments we computed match up. The IR verifier
5563 // will catch this, but this is a common enough source of problems
5564 // during IRGen changes that it's way better for debugging to catch
5565 // it ourselves here.
5566#ifndef NDEBUG
5567 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
5568 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
5569 // Inalloca argument can have different type.
5570 if (IRFunctionArgs.hasInallocaArg() &&
5571 i == IRFunctionArgs.getInallocaArgNo())
5572 continue;
5573 if (i < IRFuncTy->getNumParams())
5574 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
5575 }
5576#endif
5577
5578 // Update the largest vector width if any arguments have vector types.
5579 for (unsigned i = 0; i < IRCallArgs.size(); ++i)
5580 LargestVectorWidth = std::max(LargestVectorWidth,
5581 getMaxVectorWidth(IRCallArgs[i]->getType()));
5582
5583 // Compute the calling convention and attributes.
5584 unsigned CallingConv;
5585 llvm::AttributeList Attrs;
5586 CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
5587 Callee.getAbstractInfo(), Attrs, CallingConv,
5588 /*AttrOnCallSite=*/true,
5589 /*IsThunk=*/false);
5590
5591 if (CallingConv == llvm::CallingConv::X86_VectorCall &&
5592 getTarget().getTriple().isWindowsArm64EC()) {
5593 CGM.Error(Loc, "__vectorcall calling convention is not currently "
5594 "supported");
5595 }
5596
5597 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
5598 if (FD->hasAttr<StrictFPAttr>())
5599 // All calls within a strictfp function are marked strictfp
5600 Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::StrictFP);
5601
5602 // If -ffast-math is enabled and the function is guarded by an
5603 // '__attribute__((optnone)) adjust the memory attribute so the BE emits the
5604 // library call instead of the intrinsic.
5605 if (FD->hasAttr<OptimizeNoneAttr>() && getLangOpts().FastMath)
5606 CGM.AdjustMemoryAttribute(CalleePtr->getName(), Callee.getAbstractInfo(),
5607 Attrs);
5608 }
5609 // Add call-site nomerge attribute if exists.
5611 Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoMerge);
5612
5613 // Add call-site noinline attribute if exists.
5615 Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoInline);
5616
5617 // Add call-site always_inline attribute if exists.
5619 Attrs =
5620 Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::AlwaysInline);
5621
5622 // Remove call-site convergent attribute if requested.
5624 Attrs =
5625 Attrs.removeFnAttribute(getLLVMContext(), llvm::Attribute::Convergent);
5626
5627 // Apply some call-site-specific attributes.
5628 // TODO: work this into building the attribute set.
5629
5630 // Apply always_inline to all calls within flatten functions.
5631 // FIXME: should this really take priority over __try, below?
5632 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
5634 !(TargetDecl && TargetDecl->hasAttr<NoInlineAttr>())) {
5635 Attrs =
5636 Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::AlwaysInline);
5637 }
5638
5639 // Disable inlining inside SEH __try blocks.
5640 if (isSEHTryScope()) {
5641 Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoInline);
5642 }
5643
5644 // Decide whether to use a call or an invoke.
5645 bool CannotThrow;
5647 // SEH cares about asynchronous exceptions, so everything can "throw."
5648 CannotThrow = false;
5649 } else if (isCleanupPadScope() &&
5651 // The MSVC++ personality will implicitly terminate the program if an
5652 // exception is thrown during a cleanup outside of a try/catch.
5653 // We don't need to model anything in IR to get this behavior.
5654 CannotThrow = true;
5655 } else {
5656 // Otherwise, nounwind call sites will never throw.
5657 CannotThrow = Attrs.hasFnAttr(llvm::Attribute::NoUnwind);
5658
5659 if (auto *FPtr = dyn_cast<llvm::Function>(CalleePtr))
5660 if (FPtr->hasFnAttribute(llvm::Attribute::NoUnwind))
5661 CannotThrow = true;
5662 }
5663
5664 // If we made a temporary, be sure to clean up after ourselves. Note that we
5665 // can't depend on being inside of an ExprWithCleanups, so we need to manually
5666 // pop this cleanup later on. Being eager about this is OK, since this
5667 // temporary is 'invisible' outside of the callee.
5668 if (UnusedReturnSizePtr)
5669 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca,
5670 UnusedReturnSizePtr);
5671
5672 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
5673
5675 getBundlesForFunclet(CalleePtr);
5676
5677 if (SanOpts.has(SanitizerKind::KCFI) &&
5678 !isa_and_nonnull<FunctionDecl>(TargetDecl))
5679 EmitKCFIOperandBundle(ConcreteCallee, BundleList);
5680
5681 // Add the pointer-authentication bundle.
5682 EmitPointerAuthOperandBundle(ConcreteCallee.getPointerAuthInfo(), BundleList);
5683
5684 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
5685 if (FD->hasAttr<StrictFPAttr>())
5686 // All calls within a strictfp function are marked strictfp
5687 Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::StrictFP);
5688
5689 AssumeAlignedAttrEmitter AssumeAlignedAttrEmitter(*this, TargetDecl);
5690 Attrs = AssumeAlignedAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
5691
5692 AllocAlignAttrEmitter AllocAlignAttrEmitter(*this, TargetDecl, CallArgs);
5693 Attrs = AllocAlignAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
5694
5695 // Emit the actual call/invoke instruction.
5696 llvm::CallBase *CI;
5697 if (!InvokeDest) {
5698 CI = Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList);
5699 } else {
5700 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
5701 CI = Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs,
5702 BundleList);
5703 EmitBlock(Cont);
5704 }
5705 if (CI->getCalledFunction() && CI->getCalledFunction()->hasName() &&
5706 CI->getCalledFunction()->getName().starts_with("_Z4sqrt")) {
5708 }
5709 if (callOrInvoke)
5710 *callOrInvoke = CI;
5711
5712 // If this is within a function that has the guard(nocf) attribute and is an
5713 // indirect call, add the "guard_nocf" attribute to this call to indicate that
5714 // Control Flow Guard checks should not be added, even if the call is inlined.
5715 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
5716 if (const auto *A = FD->getAttr<CFGuardAttr>()) {
5717 if (A->getGuard() == CFGuardAttr::GuardArg::nocf && !CI->getCalledFunction())
5718 Attrs = Attrs.addFnAttribute(getLLVMContext(), "guard_nocf");
5719 }
5720 }
5721
5722 // Apply the attributes and calling convention.
5723 CI->setAttributes(Attrs);
5724 CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
5725
5726 // Apply various metadata.
5727
5728 if (!CI->getType()->isVoidTy())
5729 CI->setName("call");
5730
5731 if (CGM.shouldEmitConvergenceTokens() && CI->isConvergent())
5733
5734 // Update largest vector width from the return type.
5735 LargestVectorWidth =
5736 std::max(LargestVectorWidth, getMaxVectorWidth(CI->getType()));
5737
5738 // Insert instrumentation or attach profile metadata at indirect call sites.
5739 // For more details, see the comment before the definition of
5740 // IPVK_IndirectCallTarget in InstrProfData.inc.
5741 if (!CI->getCalledFunction())
5742 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
5743 CI, CalleePtr);
5744
5745 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
5746 // optimizer it can aggressively ignore unwind edges.
5747 if (CGM.getLangOpts().ObjCAutoRefCount)
5748 AddObjCARCExceptionMetadata(CI);
5749
5750 // Set tail call kind if necessary.
5751 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
5752 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
5753 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
5754 else if (IsMustTail) {
5755 if (getTarget().getTriple().isPPC()) {
5756 if (getTarget().getTriple().isOSAIX())
5757 CGM.getDiags().Report(Loc, diag::err_aix_musttail_unsupported);
5758 else if (!getTarget().hasFeature("pcrelative-memops")) {
5759 if (getTarget().hasFeature("longcall"))
5760 CGM.getDiags().Report(Loc, diag::err_ppc_impossible_musttail) << 0;
5761 else if (Call->isIndirectCall())
5762 CGM.getDiags().Report(Loc, diag::err_ppc_impossible_musttail) << 1;
5763 else if (isa_and_nonnull<FunctionDecl>(TargetDecl)) {
5764 if (!cast<FunctionDecl>(TargetDecl)->isDefined())
5765 // The undefined callee may be a forward declaration. Without
5766 // knowning all symbols in the module, we won't know the symbol is
5767 // defined or not. Collect all these symbols for later diagnosing.
5769 {cast<FunctionDecl>(TargetDecl), Loc});
5770 else {
5771 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(
5772 GlobalDecl(cast<FunctionDecl>(TargetDecl)));
5773 if (llvm::GlobalValue::isWeakForLinker(Linkage) ||
5774 llvm::GlobalValue::isDiscardableIfUnused(Linkage))
5775 CGM.getDiags().Report(Loc, diag::err_ppc_impossible_musttail)
5776 << 2;
5777 }
5778 }
5779 }
5780 }
5781 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
5782 }
5783 }
5784
5785 // Add metadata for calls to MSAllocator functions
5786 if (getDebugInfo() && TargetDecl &&
5787 TargetDecl->hasAttr<MSAllocatorAttr>())
5789
5790 // Add metadata if calling an __attribute__((error(""))) or warning fn.
5791 if (TargetDecl && TargetDecl->hasAttr<ErrorAttr>()) {
5792 llvm::ConstantInt *Line =
5793 llvm::ConstantInt::get(Int64Ty, Loc.getRawEncoding());
5794 llvm::ConstantAsMetadata *MD = llvm::ConstantAsMetadata::get(Line);
5795 llvm::MDTuple *MDT = llvm::MDNode::get(getLLVMContext(), {MD});
5796 CI->setMetadata("srcloc", MDT);
5797 }
5798
5799 // 4. Finish the call.
5800
5801 // If the call doesn't return, finish the basic block and clear the
5802 // insertion point; this allows the rest of IRGen to discard
5803 // unreachable code.
5804 if (CI->doesNotReturn()) {
5805 if (UnusedReturnSizePtr)
5807
5808 // Strip away the noreturn attribute to better diagnose unreachable UB.
5809 if (SanOpts.has(SanitizerKind::Unreachable)) {
5810 // Also remove from function since CallBase::hasFnAttr additionally checks
5811 // attributes of the called function.
5812 if (auto *F = CI->getCalledFunction())
5813 F->removeFnAttr(llvm::Attribute::NoReturn);
5814 CI->removeFnAttr(llvm::Attribute::NoReturn);
5815
5816 // Avoid incompatibility with ASan which relies on the `noreturn`
5817 // attribute to insert handler calls.
5818 if (SanOpts.hasOneOf(SanitizerKind::Address |
5819 SanitizerKind::KernelAddress)) {
5820 SanitizerScope SanScope(this);
5821 llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder);
5822 Builder.SetInsertPoint(CI);
5823 auto *FnType = llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
5824 llvm::FunctionCallee Fn =
5825 CGM.CreateRuntimeFunction(FnType, "__asan_handle_no_return");
5827 }
5828 }
5829
5831 Builder.ClearInsertionPoint();
5832
5833 // FIXME: For now, emit a dummy basic block because expr emitters in
5834 // generally are not ready to handle emitting expressions at unreachable
5835 // points.
5837
5838 // Return a reasonable RValue.
5839 return GetUndefRValue(RetTy);
5840 }
5841
5842 // If this is a musttail call, return immediately. We do not branch to the
5843 // epilogue in this case.
5844 if (IsMustTail) {
5845 for (auto it = EHStack.find(CurrentCleanupScopeDepth); it != EHStack.end();
5846 ++it) {
5847 EHCleanupScope *Cleanup = dyn_cast<EHCleanupScope>(&*it);
5848 if (!(Cleanup && Cleanup->getCleanup()->isRedundantBeforeReturn()))
5849 CGM.ErrorUnsupported(MustTailCall, "tail call skipping over cleanups");
5850 }
5851 if (CI->getType()->isVoidTy())
5852 Builder.CreateRetVoid();
5853 else
5854 Builder.CreateRet(CI);
5855 Builder.ClearInsertionPoint();
5857 return GetUndefRValue(RetTy);
5858 }
5859
5860 // Perform the swifterror writeback.
5861 if (swiftErrorTemp.isValid()) {
5862 llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
5863 Builder.CreateStore(errorResult, swiftErrorArg);
5864 }
5865
5866 // Emit any call-associated writebacks immediately. Arguably this
5867 // should happen after any return-value munging.
5868 if (CallArgs.hasWritebacks())
5869 emitWritebacks(*this, CallArgs);
5870
5871 // The stack cleanup for inalloca arguments has to run out of the normal
5872 // lexical order, so deactivate it and run it manually here.
5873 CallArgs.freeArgumentMemory(*this);
5874
5875 // Extract the return value.
5876 RValue Ret;
5877
5878 // If the current function is a virtual function pointer thunk, avoid copying
5879 // the return value of the musttail call to a temporary.
5880 if (IsVirtualFunctionPointerThunk) {
5881 Ret = RValue::get(CI);
5882 } else {
5883 Ret = [&] {
5884 switch (RetAI.getKind()) {
5886 auto coercionType = RetAI.getCoerceAndExpandType();
5887
5888 Address addr = SRetPtr.withElementType(coercionType);
5889
5890 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
5891 bool requiresExtract = isa<llvm::StructType>(CI->getType());
5892
5893 unsigned unpaddedIndex = 0;
5894 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
5895 llvm::Type *eltType = coercionType->getElementType(i);
5897 continue;
5898 Address eltAddr = Builder.CreateStructGEP(addr, i);
5899 llvm::Value *elt = CI;
5900 if (requiresExtract)
5901 elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
5902 else
5903 assert(unpaddedIndex == 0);
5904 Builder.CreateStore(elt, eltAddr);
5905 }
5906 [[fallthrough]];
5907 }
5908
5910 case ABIArgInfo::Indirect: {
5911 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
5912 if (UnusedReturnSizePtr)
5914 return ret;
5915 }
5916
5917 case ABIArgInfo::Ignore:
5918 // If we are ignoring an argument that had a result, make sure to
5919 // construct the appropriate return value for our caller.
5920 return GetUndefRValue(RetTy);
5921
5922 case ABIArgInfo::Extend:
5923 case ABIArgInfo::Direct: {
5924 llvm::Type *RetIRTy = ConvertType(RetTy);
5925 if (RetAI.getCoerceToType() == RetIRTy &&
5926 RetAI.getDirectOffset() == 0) {
5927 switch (getEvaluationKind(RetTy)) {
5928 case TEK_Complex: {
5929 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
5930 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
5931 return RValue::getComplex(std::make_pair(Real, Imag));
5932 }
5933 case TEK_Aggregate:
5934 break;
5935 case TEK_Scalar: {
5936 // If the argument doesn't match, perform a bitcast to coerce it.
5937 // This can happen due to trivial type mismatches.
5938 llvm::Value *V = CI;
5939 if (V->getType() != RetIRTy)
5940 V = Builder.CreateBitCast(V, RetIRTy);
5941 return RValue::get(V);
5942 }
5943 }
5944 }
5945
5946 // If coercing a fixed vector from a scalable vector for ABI
5947 // compatibility, and the types match, use the llvm.vector.extract
5948 // intrinsic to perform the conversion.
5949 if (auto *FixedDstTy = dyn_cast<llvm::FixedVectorType>(RetIRTy)) {
5950 llvm::Value *V = CI;
5951 if (auto *ScalableSrcTy =
5952 dyn_cast<llvm::ScalableVectorType>(V->getType())) {
5953 if (FixedDstTy->getElementType() ==
5954 ScalableSrcTy->getElementType()) {
5955 llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty);
5956 V = Builder.CreateExtractVector(FixedDstTy, V, Zero,
5957 "cast.fixed");
5958 return RValue::get(V);
5959 }
5960 }
5961 }
5962
5963 Address DestPtr = ReturnValue.getValue();
5964 bool DestIsVolatile = ReturnValue.isVolatile();
5965 uint64_t DestSize =
5967
5968 if (!DestPtr.isValid()) {
5969 DestPtr = CreateMemTemp(RetTy, "coerce");
5970 DestIsVolatile = false;
5971 DestSize = getContext().getTypeSizeInChars(RetTy).getQuantity();
5972 }
5973
5974 // An empty record can overlap other data (if declared with
5975 // no_unique_address); omit the store for such types - as there is no
5976 // actual data to store.
5977 if (!isEmptyRecord(getContext(), RetTy, true)) {
5978 // If the value is offset in memory, apply the offset now.
5979 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
5981 CI, StorePtr,
5982 llvm::TypeSize::getFixed(DestSize - RetAI.getDirectOffset()),
5983 DestIsVolatile);
5984 }
5985
5986 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
5987 }
5988
5989 case ABIArgInfo::Expand:
5991 llvm_unreachable("Invalid ABI kind for return argument");
5992 }
5993
5994 llvm_unreachable("Unhandled ABIArgInfo::Kind");
5995 }();
5996 }
5997
5998 // Emit the assume_aligned check on the return value.
5999 if (Ret.isScalar() && TargetDecl) {
6000 AssumeAlignedAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
6001 AllocAlignAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
6002 }
6003
6004 // Explicitly call CallLifetimeEnd::Emit just to re-use the code even though
6005 // we can't use the full cleanup mechanism.
6006 for (CallLifetimeEnd &LifetimeEnd : CallLifetimeEndAfterCall)
6007 LifetimeEnd.Emit(*this, /*Flags=*/{});
6008
6009 if (!ReturnValue.isExternallyDestructed() &&
6011 pushDestroy(QualType::DK_nontrivial_c_struct, Ret.getAggregateAddress(),
6012 RetTy);
6013
6014 return Ret;
6015}
6016
6018 if (isVirtual()) {
6019 const CallExpr *CE = getVirtualCallExpr();
6022 CE ? CE->getBeginLoc() : SourceLocation());
6023 }
6024
6025 return *this;
6026}
6027
6028/* VarArg handling */
6029
6031 AggValueSlot Slot) {
6032 VAListAddr = VE->isMicrosoftABI() ? EmitMSVAListRef(VE->getSubExpr())
6033 : EmitVAListRef(VE->getSubExpr());
6034 QualType Ty = VE->getType();
6035 if (VE->isMicrosoftABI())
6036 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty, Slot);
6037 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty, Slot);
6038}
#define V(N, I)
Definition: ASTContext.h:3341
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:4043
static uint64_t buildMultiCharMask(const SmallVectorImpl< uint64_t > &Bits, int Pos, int Size, int CharWidth, bool BigEndian)
Definition: CGCall.cpp:3719
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:3476
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:2888
static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr, const ABIArgInfo &info)
Definition: CGCall.cpp:1403
static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty)
Definition: CGCall.cpp:4048
static void setBitRange(SmallVectorImpl< uint64_t > &Bits, int BitOffset, int BitWidth, int CharWidth)
Definition: CGCall.cpp:3598
static SmallVector< CanQualType, 16 > getArgTypesForCall(ASTContext &ctx, const CallArgList &args)
Definition: CGCall.cpp:385
static bool isProvablyNull(llvm::Value *addr)
Definition: CGCall.cpp:4118
static void AddAttributesFromFunctionProtoType(ASTContext &Ctx, llvm::AttrBuilder &FuncAttrs, const FunctionProtoType *FPT)
Definition: CGCall.cpp:1744
static void eraseUnusedBitCasts(llvm::Instruction *insn)
Definition: CGCall.cpp:3376
static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method)
Definition: CGCall.cpp:4442
static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs, const LangOptions &LangOpts, const NoBuiltinAttr *NBA=nullptr)
Definition: CGCall.cpp:2143
static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args, const ObjCIndirectCopyRestoreExpr *CRE)
Emit an argument that's being passed call-by-writeback.
Definition: CGCall.cpp:4220
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:2022
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:2179
static const Expr * maybeGetUnaryAddrOfOperand(const Expr *E)
Definition: CGCall.cpp:4209
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:1843
static void emitWritebacks(CodeGenFunction &CGF, const CallArgList &args)
Definition: CGCall.cpp:4192
static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF, const CallArgList &CallArgs)
Definition: CGCall.cpp:4198
static bool isProvablyNonNull(Address Addr, CodeGenFunction &CGF)
Definition: CGCall.cpp:4122
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:2868
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:2252
static void getTrivialDefaultFunctionAttributes(StringRef Name, bool HasOptnone, const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, bool AttrOnCallSite, llvm::AttrBuilder &FuncAttrs)
Definition: CGCall.cpp:1863
static llvm::FPClassTest getNoFPClassTestMask(const LangOptions &LangOpts)
Return the nofpclass mask that can be applied to floating-point parameters.
Definition: CGCall.cpp:2274
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:2230
static bool hasInAllocaArgs(CodeGenModule &CGM, CallingConv ExplicitCC, ArrayRef< QualType > ArgTypes)
Definition: CGCall.cpp:4424
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:3702
static llvm::StoreInst * findDominatingStoreToReturnValue(CodeGenFunction &CGF)
Heuristically search for a dominating store to the return-value slot.
Definition: CGCall.cpp:3533
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:3388
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:3515
static void emitWriteback(CodeGenFunction &CGF, const CallArgList::Writeback &writeback)
Emit the actual writing-back of a writeback.
Definition: CGCall.cpp:4127
static bool HasStrictReturn(const CodeGenModule &Module, QualType RetTy, const Decl *TargetDecl)
Definition: CGCall.cpp:1808
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:1857
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:1781
static unsigned getMaxVectorWidth(const llvm::Type *Ty)
Definition: CGCall.cpp:5005
CodeGenFunction::ComplexPairTy ComplexPairTy
const Decl * D
enum clang::sema::@1653::IndirectLocalPathEntry::EntryKind Kind
Expr * E
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:759
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:187
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2825
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:1146
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:2127
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType IntTy
Definition: ASTContext.h:1128
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
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:2394
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1119
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:779
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:2398
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:3566
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:3023
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:2539
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2803
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2064
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:2500
bool isVirtual() const
Definition: DeclCXX.h:2119
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2190
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2225
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:2014
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:635
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
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:6017
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:4346
void freeArgumentMemory(CodeGenFunction &CGF) const
Definition: CGCall.cpp:4353
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
void CreateCoercedStore(llvm::Value *Src, Address Dst, llvm::TypeSize DstSize, bool DstIsVolatile)
Create a store to.
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.
bool InNoConvergentAttributedStmt
True if the current statement has noconvergent attribute.
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 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:1573
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:1590
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:1568
bool ReturnTypeHasInReg(const CGFunctionInfo &FI)
Return true iff the given type has inreg set.
Definition: CGCall.cpp:1563
void AdjustMemoryAttribute(StringRef Name, CGCalleeInfo CalleeInfo, llvm::AttributeList &Attrs)
Adjust Memory attribute to ensure that the BE gets the right attribute.
Definition: CGCall.cpp:2283
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:2311
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:1558
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:2136
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:1796
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:1607
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:1734
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:382
Address performAddrSpaceCast(CodeGen::CodeGenFunction &CGF, Address Addr, LangAS SrcAddr, LangAS DestAddr, llvm::Type *DestTy, bool IsNonNull=false) const
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
static void initBranchProtectionFnAttributes(const TargetInfo::BranchProtectionInfo &BPI, llvm::AttrBuilder &FuncAttrs)
Definition: TargetInfo.cpp:239
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:3134
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3604
bool constructsVirtualBase() const
Returns true if the constructed base class is a virtual base class subobject of this declaration's cl...
Definition: DeclCXX.h:3702
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
T * getAttr() const
Definition: DeclBase.h:580
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:566
DeclContext * getDeclContext()
Definition: DeclBase.h:455
bool hasAttr() const
Definition: DeclBase.h:584
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:4583
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:4668
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5002
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5282
unsigned getNumParams() const
Definition: Type.h:5255
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition: Type.h:5461
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5379
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.h:5374
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition: Type.h:5444
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:5440
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:4419
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4534
CallingConv getCC() const
Definition: Type.h:4481
ExtInfo withProducesResult(bool producesResult) const
Definition: Type.h:4500
bool getCmseNSCall() const
Definition: Type.h:4469
bool getNoCfCheck() const
Definition: Type.h:4471
unsigned getRegParm() const
Definition: Type.h:4474
bool getNoCallerSavedRegs() const
Definition: Type.h:4470
bool getHasRegParm() const
Definition: Type.h:4472
bool getNoReturn() const
Definition: Type.h:4467
bool getProducesResult() const
Definition: Type.h:4468
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: Type.h:4334
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition: Type.h:4347
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition: Type.h:4374
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4308
ExtInfo getExtInfo() const
Definition: Type.h:4642
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition: Type.h:4600
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition: Type.h:4596
QualType getReturnType() const
Definition: Type.h:4630
@ SME_PStateSMEnabledMask
Definition: Type.h:4574
@ SME_PStateSMCompatibleMask
Definition: Type.h:4575
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:2510
ConstructorUsingShadowDecl * getShadowDecl() const
Definition: DeclCXX.h:2522
@ 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:476
std::vector< std::string > NoBuiltinFuncs
A list of all -fno-builtin-* function names (e.g., memset).
Definition: LangOptions.h:543
FPExceptionModeKind getDefaultExceptionMode() const
Definition: LangOptions.h:785
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:674
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition: Type.h:4183
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:2328
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:3187
QualType getPointeeType() const
Definition: Type.h:3197
A (possibly-)qualified type.
Definition: Type.h:941
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:7828
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2751
@ 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:7876
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7790
QualType getCanonicalType() const
Definition: Type.h:7802
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7823
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:4145
bool hasFlexibleArrayMember() const
Definition: Decl.h:4178
field_iterator field_end() const
Definition: Decl.h:4354
field_range fields() const
Definition: Decl.h:4351
bool isParamDestroyedInCallee() const
Definition: Decl.h:4287
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4336
field_iterator field_begin() const
Definition: Decl.cpp:5068
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5965
RecordDecl * getDecl() const
Definition: Type.h:5975
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3428
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:3767
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:8017
bool isVoidType() const
Definition: Type.h:8319
bool isIncompleteArrayType() const
Definition: Type.h:8083
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:8003
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8359
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8607
bool isReferenceType() const
Definition: Type.h:8021
bool isScalarType() const
Definition: Type.h:8418
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:8241
QualType getCanonicalTypeInternal() const
Definition: Type.h:2978
bool isMemberPointerType() const
Definition: Type.h:8057
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2439
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:8011
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8540
bool isNullPtrType() const
Definition: Type.h:8352
bool isObjCRetainableType() const
Definition: Type.cpp:4950
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:4701
bool isMicrosoftABI() const
Returns whether this is really a Win64 ABI va_arg expression.
Definition: Expr.h:4722
const Expr * getSubExpr() const
Definition: Expr.h:4717
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:4021
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:2053
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:3831
bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
Definition: Interp.h:275
bool This(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2268
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2242
bool Load(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1665
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:151
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:278
@ CC_X86Pascal
Definition: Specifiers.h:284
@ CC_Swift
Definition: Specifiers.h:293
@ CC_IntelOclBicc
Definition: Specifiers.h:290
@ CC_OpenCLKernel
Definition: Specifiers.h:292
@ CC_PreserveMost
Definition: Specifiers.h:295
@ CC_Win64
Definition: Specifiers.h:285
@ CC_X86ThisCall
Definition: Specifiers.h:282
@ CC_AArch64VectorCall
Definition: Specifiers.h:297
@ CC_AAPCS
Definition: Specifiers.h:288
@ CC_PreserveNone
Definition: Specifiers.h:301
@ CC_C
Definition: Specifiers.h:279
@ CC_AMDGPUKernelCall
Definition: Specifiers.h:299
@ CC_M68kRTD
Definition: Specifiers.h:300
@ CC_SwiftAsync
Definition: Specifiers.h:294
@ CC_X86RegCall
Definition: Specifiers.h:287
@ CC_RISCVVectorCall
Definition: Specifiers.h:302
@ CC_X86VectorCall
Definition: Specifiers.h:283
@ CC_SpirFunction
Definition: Specifiers.h:291
@ CC_AArch64SVEPCS
Definition: Specifiers.h:298
@ CC_X86StdCall
Definition: Specifiers.h:280
@ CC_X86_64SysV
Definition: Specifiers.h:286
@ CC_PreserveAll
Definition: Specifiers.h:296
@ CC_X86FastCall
Definition: Specifiers.h:281
@ CC_AAPCS_VFP
Definition: Specifiers.h:289
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:4646
bool hasLValue() const
Definition: CGCall.h:247
RValue getRValue(CodeGenFunction &CGF) const
Definition: CGCall.cpp:4636
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:1321