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