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