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