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