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