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