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