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