Bug Summary

File:clang/lib/Sema/SemaChecking.cpp
Warning:line 11261, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaChecking.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-19-001817-16337-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/clang/lib/Sema/SemaChecking.cpp
1//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
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// This file implements extra semantic analysis beyond what is enforced
10// by the C type system.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Attr.h"
17#include "clang/AST/AttrIterator.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/EvaluatedExprVisitor.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/ExprOpenMP.h"
29#include "clang/AST/FormatString.h"
30#include "clang/AST/NSAPI.h"
31#include "clang/AST/NonTrivialTypeVisitor.h"
32#include "clang/AST/OperationKinds.h"
33#include "clang/AST/RecordLayout.h"
34#include "clang/AST/Stmt.h"
35#include "clang/AST/TemplateBase.h"
36#include "clang/AST/Type.h"
37#include "clang/AST/TypeLoc.h"
38#include "clang/AST/UnresolvedSet.h"
39#include "clang/Basic/AddressSpaces.h"
40#include "clang/Basic/CharInfo.h"
41#include "clang/Basic/Diagnostic.h"
42#include "clang/Basic/IdentifierTable.h"
43#include "clang/Basic/LLVM.h"
44#include "clang/Basic/LangOptions.h"
45#include "clang/Basic/OpenCLOptions.h"
46#include "clang/Basic/OperatorKinds.h"
47#include "clang/Basic/PartialDiagnostic.h"
48#include "clang/Basic/SourceLocation.h"
49#include "clang/Basic/SourceManager.h"
50#include "clang/Basic/Specifiers.h"
51#include "clang/Basic/SyncScope.h"
52#include "clang/Basic/TargetBuiltins.h"
53#include "clang/Basic/TargetCXXABI.h"
54#include "clang/Basic/TargetInfo.h"
55#include "clang/Basic/TypeTraits.h"
56#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57#include "clang/Sema/Initialization.h"
58#include "clang/Sema/Lookup.h"
59#include "clang/Sema/Ownership.h"
60#include "clang/Sema/Scope.h"
61#include "clang/Sema/ScopeInfo.h"
62#include "clang/Sema/Sema.h"
63#include "clang/Sema/SemaInternal.h"
64#include "llvm/ADT/APFloat.h"
65#include "llvm/ADT/APInt.h"
66#include "llvm/ADT/APSInt.h"
67#include "llvm/ADT/ArrayRef.h"
68#include "llvm/ADT/DenseMap.h"
69#include "llvm/ADT/FoldingSet.h"
70#include "llvm/ADT/None.h"
71#include "llvm/ADT/Optional.h"
72#include "llvm/ADT/STLExtras.h"
73#include "llvm/ADT/SmallBitVector.h"
74#include "llvm/ADT/SmallPtrSet.h"
75#include "llvm/ADT/SmallString.h"
76#include "llvm/ADT/SmallVector.h"
77#include "llvm/ADT/StringRef.h"
78#include "llvm/ADT/StringSet.h"
79#include "llvm/ADT/StringSwitch.h"
80#include "llvm/ADT/Triple.h"
81#include "llvm/Support/AtomicOrdering.h"
82#include "llvm/Support/Casting.h"
83#include "llvm/Support/Compiler.h"
84#include "llvm/Support/ConvertUTF.h"
85#include "llvm/Support/ErrorHandling.h"
86#include "llvm/Support/Format.h"
87#include "llvm/Support/Locale.h"
88#include "llvm/Support/MathExtras.h"
89#include "llvm/Support/SaveAndRestore.h"
90#include "llvm/Support/raw_ostream.h"
91#include <algorithm>
92#include <bitset>
93#include <cassert>
94#include <cctype>
95#include <cstddef>
96#include <cstdint>
97#include <functional>
98#include <limits>
99#include <string>
100#include <tuple>
101#include <utility>
102
103using namespace clang;
104using namespace sema;
105
106SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
107 unsigned ByteNo) const {
108 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
109 Context.getTargetInfo());
110}
111
112/// Checks that a call expression's argument count is the desired number.
113/// This is useful when doing custom type-checking. Returns true on error.
114static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
115 unsigned argCount = call->getNumArgs();
116 if (argCount == desiredArgCount) return false;
117
118 if (argCount < desiredArgCount)
119 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
120 << 0 /*function call*/ << desiredArgCount << argCount
121 << call->getSourceRange();
122
123 // Highlight all the excess arguments.
124 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
125 call->getArg(argCount - 1)->getEndLoc());
126
127 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
128 << 0 /*function call*/ << desiredArgCount << argCount
129 << call->getArg(1)->getSourceRange();
130}
131
132/// Check that the first argument to __builtin_annotation is an integer
133/// and the second argument is a non-wide string literal.
134static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
135 if (checkArgCount(S, TheCall, 2))
136 return true;
137
138 // First argument should be an integer.
139 Expr *ValArg = TheCall->getArg(0);
140 QualType Ty = ValArg->getType();
141 if (!Ty->isIntegerType()) {
142 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
143 << ValArg->getSourceRange();
144 return true;
145 }
146
147 // Second argument should be a constant string.
148 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
149 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
150 if (!Literal || !Literal->isAscii()) {
151 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
152 << StrArg->getSourceRange();
153 return true;
154 }
155
156 TheCall->setType(Ty);
157 return false;
158}
159
160static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
161 // We need at least one argument.
162 if (TheCall->getNumArgs() < 1) {
163 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
164 << 0 << 1 << TheCall->getNumArgs()
165 << TheCall->getCallee()->getSourceRange();
166 return true;
167 }
168
169 // All arguments should be wide string literals.
170 for (Expr *Arg : TheCall->arguments()) {
171 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
172 if (!Literal || !Literal->isWide()) {
173 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
174 << Arg->getSourceRange();
175 return true;
176 }
177 }
178
179 return false;
180}
181
182/// Check that the argument to __builtin_addressof is a glvalue, and set the
183/// result type to the corresponding pointer type.
184static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
185 if (checkArgCount(S, TheCall, 1))
186 return true;
187
188 ExprResult Arg(TheCall->getArg(0));
189 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
190 if (ResultType.isNull())
191 return true;
192
193 TheCall->setArg(0, Arg.get());
194 TheCall->setType(ResultType);
195 return false;
196}
197
198/// Check that the argument to __builtin_function_start is a function.
199static bool SemaBuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
200 if (checkArgCount(S, TheCall, 1))
201 return true;
202
203 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
204 if (Arg.isInvalid())
205 return true;
206
207 TheCall->setArg(0, Arg.get());
208 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
209 Arg.get()->getAsBuiltinConstantDeclRef(S.getASTContext()));
210
211 if (!FD) {
212 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
213 << TheCall->getSourceRange();
214 return true;
215 }
216
217 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
218 TheCall->getBeginLoc());
219}
220
221/// Check the number of arguments and set the result type to
222/// the argument type.
223static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
224 if (checkArgCount(S, TheCall, 1))
225 return true;
226
227 TheCall->setType(TheCall->getArg(0)->getType());
228 return false;
229}
230
231/// Check that the value argument for __builtin_is_aligned(value, alignment) and
232/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
233/// type (but not a function pointer) and that the alignment is a power-of-two.
234static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
235 if (checkArgCount(S, TheCall, 2))
236 return true;
237
238 clang::Expr *Source = TheCall->getArg(0);
239 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
240
241 auto IsValidIntegerType = [](QualType Ty) {
242 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
243 };
244 QualType SrcTy = Source->getType();
245 // We should also be able to use it with arrays (but not functions!).
246 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
247 SrcTy = S.Context.getDecayedType(SrcTy);
248 }
249 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
250 SrcTy->isFunctionPointerType()) {
251 // FIXME: this is not quite the right error message since we don't allow
252 // floating point types, or member pointers.
253 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
254 << SrcTy;
255 return true;
256 }
257
258 clang::Expr *AlignOp = TheCall->getArg(1);
259 if (!IsValidIntegerType(AlignOp->getType())) {
260 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
261 << AlignOp->getType();
262 return true;
263 }
264 Expr::EvalResult AlignResult;
265 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
266 // We can't check validity of alignment if it is value dependent.
267 if (!AlignOp->isValueDependent() &&
268 AlignOp->EvaluateAsInt(AlignResult, S.Context,
269 Expr::SE_AllowSideEffects)) {
270 llvm::APSInt AlignValue = AlignResult.Val.getInt();
271 llvm::APSInt MaxValue(
272 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
273 if (AlignValue < 1) {
274 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
275 return true;
276 }
277 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
278 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
279 << toString(MaxValue, 10);
280 return true;
281 }
282 if (!AlignValue.isPowerOf2()) {
283 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
284 return true;
285 }
286 if (AlignValue == 1) {
287 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
288 << IsBooleanAlignBuiltin;
289 }
290 }
291
292 ExprResult SrcArg = S.PerformCopyInitialization(
293 InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
294 SourceLocation(), Source);
295 if (SrcArg.isInvalid())
296 return true;
297 TheCall->setArg(0, SrcArg.get());
298 ExprResult AlignArg =
299 S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
300 S.Context, AlignOp->getType(), false),
301 SourceLocation(), AlignOp);
302 if (AlignArg.isInvalid())
303 return true;
304 TheCall->setArg(1, AlignArg.get());
305 // For align_up/align_down, the return type is the same as the (potentially
306 // decayed) argument type including qualifiers. For is_aligned(), the result
307 // is always bool.
308 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
309 return false;
310}
311
312static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
313 unsigned BuiltinID) {
314 if (checkArgCount(S, TheCall, 3))
315 return true;
316
317 // First two arguments should be integers.
318 for (unsigned I = 0; I < 2; ++I) {
319 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
320 if (Arg.isInvalid()) return true;
321 TheCall->setArg(I, Arg.get());
322
323 QualType Ty = Arg.get()->getType();
324 if (!Ty->isIntegerType()) {
325 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
326 << Ty << Arg.get()->getSourceRange();
327 return true;
328 }
329 }
330
331 // Third argument should be a pointer to a non-const integer.
332 // IRGen correctly handles volatile, restrict, and address spaces, and
333 // the other qualifiers aren't possible.
334 {
335 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
336 if (Arg.isInvalid()) return true;
337 TheCall->setArg(2, Arg.get());
338
339 QualType Ty = Arg.get()->getType();
340 const auto *PtrTy = Ty->getAs<PointerType>();
341 if (!PtrTy ||
342 !PtrTy->getPointeeType()->isIntegerType() ||
343 PtrTy->getPointeeType().isConstQualified()) {
344 S.Diag(Arg.get()->getBeginLoc(),
345 diag::err_overflow_builtin_must_be_ptr_int)
346 << Ty << Arg.get()->getSourceRange();
347 return true;
348 }
349 }
350
351 // Disallow signed bit-precise integer args larger than 128 bits to mul
352 // function until we improve backend support.
353 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
354 for (unsigned I = 0; I < 3; ++I) {
355 const auto Arg = TheCall->getArg(I);
356 // Third argument will be a pointer.
357 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
358 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
359 S.getASTContext().getIntWidth(Ty) > 128)
360 return S.Diag(Arg->getBeginLoc(),
361 diag::err_overflow_builtin_bit_int_max_size)
362 << 128;
363 }
364 }
365
366 return false;
367}
368
369static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
370 if (checkArgCount(S, BuiltinCall, 2))
371 return true;
372
373 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
374 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
375 Expr *Call = BuiltinCall->getArg(0);
376 Expr *Chain = BuiltinCall->getArg(1);
377
378 if (Call->getStmtClass() != Stmt::CallExprClass) {
379 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
380 << Call->getSourceRange();
381 return true;
382 }
383
384 auto CE = cast<CallExpr>(Call);
385 if (CE->getCallee()->getType()->isBlockPointerType()) {
386 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
387 << Call->getSourceRange();
388 return true;
389 }
390
391 const Decl *TargetDecl = CE->getCalleeDecl();
392 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
393 if (FD->getBuiltinID()) {
394 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
395 << Call->getSourceRange();
396 return true;
397 }
398
399 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
400 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
401 << Call->getSourceRange();
402 return true;
403 }
404
405 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
406 if (ChainResult.isInvalid())
407 return true;
408 if (!ChainResult.get()->getType()->isPointerType()) {
409 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
410 << Chain->getSourceRange();
411 return true;
412 }
413
414 QualType ReturnTy = CE->getCallReturnType(S.Context);
415 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
416 QualType BuiltinTy = S.Context.getFunctionType(
417 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
418 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
419
420 Builtin =
421 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
422
423 BuiltinCall->setType(CE->getType());
424 BuiltinCall->setValueKind(CE->getValueKind());
425 BuiltinCall->setObjectKind(CE->getObjectKind());
426 BuiltinCall->setCallee(Builtin);
427 BuiltinCall->setArg(1, ChainResult.get());
428
429 return false;
430}
431
432namespace {
433
434class ScanfDiagnosticFormatHandler
435 : public analyze_format_string::FormatStringHandler {
436 // Accepts the argument index (relative to the first destination index) of the
437 // argument whose size we want.
438 using ComputeSizeFunction =
439 llvm::function_ref<Optional<llvm::APSInt>(unsigned)>;
440
441 // Accepts the argument index (relative to the first destination index), the
442 // destination size, and the source size).
443 using DiagnoseFunction =
444 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
445
446 ComputeSizeFunction ComputeSizeArgument;
447 DiagnoseFunction Diagnose;
448
449public:
450 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
451 DiagnoseFunction Diagnose)
452 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
453
454 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
455 const char *StartSpecifier,
456 unsigned specifierLen) override {
457 if (!FS.consumesDataArgument())
458 return true;
459
460 unsigned NulByte = 0;
461 switch ((FS.getConversionSpecifier().getKind())) {
462 default:
463 return true;
464 case analyze_format_string::ConversionSpecifier::sArg:
465 case analyze_format_string::ConversionSpecifier::ScanListArg:
466 NulByte = 1;
467 break;
468 case analyze_format_string::ConversionSpecifier::cArg:
469 break;
470 }
471
472 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
473 if (FW.getHowSpecified() !=
474 analyze_format_string::OptionalAmount::HowSpecified::Constant)
475 return true;
476
477 unsigned SourceSize = FW.getConstantAmount() + NulByte;
478
479 Optional<llvm::APSInt> DestSizeAPS = ComputeSizeArgument(FS.getArgIndex());
480 if (!DestSizeAPS)
481 return true;
482
483 unsigned DestSize = DestSizeAPS->getZExtValue();
484
485 if (DestSize < SourceSize)
486 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
487
488 return true;
489 }
490};
491
492class EstimateSizeFormatHandler
493 : public analyze_format_string::FormatStringHandler {
494 size_t Size;
495
496public:
497 EstimateSizeFormatHandler(StringRef Format)
498 : Size(std::min(Format.find(0), Format.size()) +
499 1 /* null byte always written by sprintf */) {}
500
501 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
502 const char *, unsigned SpecifierLen) override {
503
504 const size_t FieldWidth = computeFieldWidth(FS);
505 const size_t Precision = computePrecision(FS);
506
507 // The actual format.
508 switch (FS.getConversionSpecifier().getKind()) {
509 // Just a char.
510 case analyze_format_string::ConversionSpecifier::cArg:
511 case analyze_format_string::ConversionSpecifier::CArg:
512 Size += std::max(FieldWidth, (size_t)1);
513 break;
514 // Just an integer.
515 case analyze_format_string::ConversionSpecifier::dArg:
516 case analyze_format_string::ConversionSpecifier::DArg:
517 case analyze_format_string::ConversionSpecifier::iArg:
518 case analyze_format_string::ConversionSpecifier::oArg:
519 case analyze_format_string::ConversionSpecifier::OArg:
520 case analyze_format_string::ConversionSpecifier::uArg:
521 case analyze_format_string::ConversionSpecifier::UArg:
522 case analyze_format_string::ConversionSpecifier::xArg:
523 case analyze_format_string::ConversionSpecifier::XArg:
524 Size += std::max(FieldWidth, Precision);
525 break;
526
527 // %g style conversion switches between %f or %e style dynamically.
528 // %f always takes less space, so default to it.
529 case analyze_format_string::ConversionSpecifier::gArg:
530 case analyze_format_string::ConversionSpecifier::GArg:
531
532 // Floating point number in the form '[+]ddd.ddd'.
533 case analyze_format_string::ConversionSpecifier::fArg:
534 case analyze_format_string::ConversionSpecifier::FArg:
535 Size += std::max(FieldWidth, 1 /* integer part */ +
536 (Precision ? 1 + Precision
537 : 0) /* period + decimal */);
538 break;
539
540 // Floating point number in the form '[-]d.ddde[+-]dd'.
541 case analyze_format_string::ConversionSpecifier::eArg:
542 case analyze_format_string::ConversionSpecifier::EArg:
543 Size +=
544 std::max(FieldWidth,
545 1 /* integer part */ +
546 (Precision ? 1 + Precision : 0) /* period + decimal */ +
547 1 /* e or E letter */ + 2 /* exponent */);
548 break;
549
550 // Floating point number in the form '[-]0xh.hhhhp±dd'.
551 case analyze_format_string::ConversionSpecifier::aArg:
552 case analyze_format_string::ConversionSpecifier::AArg:
553 Size +=
554 std::max(FieldWidth,
555 2 /* 0x */ + 1 /* integer part */ +
556 (Precision ? 1 + Precision : 0) /* period + decimal */ +
557 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
558 break;
559
560 // Just a string.
561 case analyze_format_string::ConversionSpecifier::sArg:
562 case analyze_format_string::ConversionSpecifier::SArg:
563 Size += FieldWidth;
564 break;
565
566 // Just a pointer in the form '0xddd'.
567 case analyze_format_string::ConversionSpecifier::pArg:
568 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
569 break;
570
571 // A plain percent.
572 case analyze_format_string::ConversionSpecifier::PercentArg:
573 Size += 1;
574 break;
575
576 default:
577 break;
578 }
579
580 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
581
582 if (FS.hasAlternativeForm()) {
583 switch (FS.getConversionSpecifier().getKind()) {
584 default:
585 break;
586 // Force a leading '0'.
587 case analyze_format_string::ConversionSpecifier::oArg:
588 Size += 1;
589 break;
590 // Force a leading '0x'.
591 case analyze_format_string::ConversionSpecifier::xArg:
592 case analyze_format_string::ConversionSpecifier::XArg:
593 Size += 2;
594 break;
595 // Force a period '.' before decimal, even if precision is 0.
596 case analyze_format_string::ConversionSpecifier::aArg:
597 case analyze_format_string::ConversionSpecifier::AArg:
598 case analyze_format_string::ConversionSpecifier::eArg:
599 case analyze_format_string::ConversionSpecifier::EArg:
600 case analyze_format_string::ConversionSpecifier::fArg:
601 case analyze_format_string::ConversionSpecifier::FArg:
602 case analyze_format_string::ConversionSpecifier::gArg:
603 case analyze_format_string::ConversionSpecifier::GArg:
604 Size += (Precision ? 0 : 1);
605 break;
606 }
607 }
608 assert(SpecifierLen <= Size && "no underflow")(static_cast <bool> (SpecifierLen <= Size &&
"no underflow") ? void (0) : __assert_fail ("SpecifierLen <= Size && \"no underflow\""
, "clang/lib/Sema/SemaChecking.cpp", 608, __extension__ __PRETTY_FUNCTION__
))
;
609 Size -= SpecifierLen;
610 return true;
611 }
612
613 size_t getSizeLowerBound() const { return Size; }
614
615private:
616 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
617 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
618 size_t FieldWidth = 0;
619 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
620 FieldWidth = FW.getConstantAmount();
621 return FieldWidth;
622 }
623
624 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
625 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
626 size_t Precision = 0;
627
628 // See man 3 printf for default precision value based on the specifier.
629 switch (FW.getHowSpecified()) {
630 case analyze_format_string::OptionalAmount::NotSpecified:
631 switch (FS.getConversionSpecifier().getKind()) {
632 default:
633 break;
634 case analyze_format_string::ConversionSpecifier::dArg: // %d
635 case analyze_format_string::ConversionSpecifier::DArg: // %D
636 case analyze_format_string::ConversionSpecifier::iArg: // %i
637 Precision = 1;
638 break;
639 case analyze_format_string::ConversionSpecifier::oArg: // %d
640 case analyze_format_string::ConversionSpecifier::OArg: // %D
641 case analyze_format_string::ConversionSpecifier::uArg: // %d
642 case analyze_format_string::ConversionSpecifier::UArg: // %D
643 case analyze_format_string::ConversionSpecifier::xArg: // %d
644 case analyze_format_string::ConversionSpecifier::XArg: // %D
645 Precision = 1;
646 break;
647 case analyze_format_string::ConversionSpecifier::fArg: // %f
648 case analyze_format_string::ConversionSpecifier::FArg: // %F
649 case analyze_format_string::ConversionSpecifier::eArg: // %e
650 case analyze_format_string::ConversionSpecifier::EArg: // %E
651 case analyze_format_string::ConversionSpecifier::gArg: // %g
652 case analyze_format_string::ConversionSpecifier::GArg: // %G
653 Precision = 6;
654 break;
655 case analyze_format_string::ConversionSpecifier::pArg: // %d
656 Precision = 1;
657 break;
658 }
659 break;
660 case analyze_format_string::OptionalAmount::Constant:
661 Precision = FW.getConstantAmount();
662 break;
663 default:
664 break;
665 }
666 return Precision;
667 }
668};
669
670} // namespace
671
672void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
673 CallExpr *TheCall) {
674 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
675 isConstantEvaluated())
676 return;
677
678 bool UseDABAttr = false;
679 const FunctionDecl *UseDecl = FD;
680
681 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
682 if (DABAttr) {
683 UseDecl = DABAttr->getFunction();
684 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!")(static_cast <bool> (UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!"
) ? void (0) : __assert_fail ("UseDecl && \"Missing FunctionDecl in DiagnoseAsBuiltin attribute!\""
, "clang/lib/Sema/SemaChecking.cpp", 684, __extension__ __PRETTY_FUNCTION__
))
;
685 UseDABAttr = true;
686 }
687
688 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
689
690 if (!BuiltinID)
691 return;
692
693 const TargetInfo &TI = getASTContext().getTargetInfo();
694 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
695
696 auto TranslateIndex = [&](unsigned Index) -> Optional<unsigned> {
697 // If we refer to a diagnose_as_builtin attribute, we need to change the
698 // argument index to refer to the arguments of the called function. Unless
699 // the index is out of bounds, which presumably means it's a variadic
700 // function.
701 if (!UseDABAttr)
702 return Index;
703 unsigned DABIndices = DABAttr->argIndices_size();
704 unsigned NewIndex = Index < DABIndices
705 ? DABAttr->argIndices_begin()[Index]
706 : Index - DABIndices + FD->getNumParams();
707 if (NewIndex >= TheCall->getNumArgs())
708 return llvm::None;
709 return NewIndex;
710 };
711
712 auto ComputeExplicitObjectSizeArgument =
713 [&](unsigned Index) -> Optional<llvm::APSInt> {
714 Optional<unsigned> IndexOptional = TranslateIndex(Index);
715 if (!IndexOptional)
716 return llvm::None;
717 unsigned NewIndex = IndexOptional.getValue();
718 Expr::EvalResult Result;
719 Expr *SizeArg = TheCall->getArg(NewIndex);
720 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
721 return llvm::None;
722 llvm::APSInt Integer = Result.Val.getInt();
723 Integer.setIsUnsigned(true);
724 return Integer;
725 };
726
727 auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
728 // If the parameter has a pass_object_size attribute, then we should use its
729 // (potentially) more strict checking mode. Otherwise, conservatively assume
730 // type 0.
731 int BOSType = 0;
732 // This check can fail for variadic functions.
733 if (Index < FD->getNumParams()) {
734 if (const auto *POS =
735 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
736 BOSType = POS->getType();
737 }
738
739 Optional<unsigned> IndexOptional = TranslateIndex(Index);
740 if (!IndexOptional)
741 return llvm::None;
742 unsigned NewIndex = IndexOptional.getValue();
743
744 const Expr *ObjArg = TheCall->getArg(NewIndex);
745 uint64_t Result;
746 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
747 return llvm::None;
748
749 // Get the object size in the target's size_t width.
750 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
751 };
752
753 auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
754 Optional<unsigned> IndexOptional = TranslateIndex(Index);
755 if (!IndexOptional)
756 return llvm::None;
757 unsigned NewIndex = IndexOptional.getValue();
758
759 const Expr *ObjArg = TheCall->getArg(NewIndex);
760 uint64_t Result;
761 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
762 return llvm::None;
763 // Add 1 for null byte.
764 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
765 };
766
767 Optional<llvm::APSInt> SourceSize;
768 Optional<llvm::APSInt> DestinationSize;
769 unsigned DiagID = 0;
770 bool IsChkVariant = false;
771
772 auto GetFunctionName = [&]() {
773 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
774 // Skim off the details of whichever builtin was called to produce a better
775 // diagnostic, as it's unlikely that the user wrote the __builtin
776 // explicitly.
777 if (IsChkVariant) {
778 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
779 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
780 } else if (FunctionName.startswith("__builtin_")) {
781 FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
782 }
783 return FunctionName;
784 };
785
786 switch (BuiltinID) {
787 default:
788 return;
789 case Builtin::BI__builtin_strcpy:
790 case Builtin::BIstrcpy: {
791 DiagID = diag::warn_fortify_strlen_overflow;
792 SourceSize = ComputeStrLenArgument(1);
793 DestinationSize = ComputeSizeArgument(0);
794 break;
795 }
796
797 case Builtin::BI__builtin___strcpy_chk: {
798 DiagID = diag::warn_fortify_strlen_overflow;
799 SourceSize = ComputeStrLenArgument(1);
800 DestinationSize = ComputeExplicitObjectSizeArgument(2);
801 IsChkVariant = true;
802 break;
803 }
804
805 case Builtin::BIscanf:
806 case Builtin::BIfscanf:
807 case Builtin::BIsscanf: {
808 unsigned FormatIndex = 1;
809 unsigned DataIndex = 2;
810 if (BuiltinID == Builtin::BIscanf) {
811 FormatIndex = 0;
812 DataIndex = 1;
813 }
814
815 const auto *FormatExpr =
816 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
817
818 const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
819 if (!Format)
820 return;
821
822 if (!Format->isAscii() && !Format->isUTF8())
823 return;
824
825 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
826 unsigned SourceSize) {
827 DiagID = diag::warn_fortify_scanf_overflow;
828 unsigned Index = ArgIndex + DataIndex;
829 StringRef FunctionName = GetFunctionName();
830 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
831 PDiag(DiagID) << FunctionName << (Index + 1)
832 << DestSize << SourceSize);
833 };
834
835 StringRef FormatStrRef = Format->getString();
836 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
837 return ComputeSizeArgument(Index + DataIndex);
838 };
839 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
840 const char *FormatBytes = FormatStrRef.data();
841 const ConstantArrayType *T =
842 Context.getAsConstantArrayType(Format->getType());
843 assert(T && "String literal not of constant array type!")(static_cast <bool> (T && "String literal not of constant array type!"
) ? void (0) : __assert_fail ("T && \"String literal not of constant array type!\""
, "clang/lib/Sema/SemaChecking.cpp", 843, __extension__ __PRETTY_FUNCTION__
))
;
844 size_t TypeSize = T->getSize().getZExtValue();
845
846 // In case there's a null byte somewhere.
847 size_t StrLen =
848 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
849
850 analyze_format_string::ParseScanfString(H, FormatBytes,
851 FormatBytes + StrLen, getLangOpts(),
852 Context.getTargetInfo());
853
854 // Unlike the other cases, in this one we have already issued the diagnostic
855 // here, so no need to continue (because unlike the other cases, here the
856 // diagnostic refers to the argument number).
857 return;
858 }
859
860 case Builtin::BIsprintf:
861 case Builtin::BI__builtin___sprintf_chk: {
862 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
863 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
864
865 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
866
867 if (!Format->isAscii() && !Format->isUTF8())
868 return;
869
870 StringRef FormatStrRef = Format->getString();
871 EstimateSizeFormatHandler H(FormatStrRef);
872 const char *FormatBytes = FormatStrRef.data();
873 const ConstantArrayType *T =
874 Context.getAsConstantArrayType(Format->getType());
875 assert(T && "String literal not of constant array type!")(static_cast <bool> (T && "String literal not of constant array type!"
) ? void (0) : __assert_fail ("T && \"String literal not of constant array type!\""
, "clang/lib/Sema/SemaChecking.cpp", 875, __extension__ __PRETTY_FUNCTION__
))
;
876 size_t TypeSize = T->getSize().getZExtValue();
877
878 // In case there's a null byte somewhere.
879 size_t StrLen =
880 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
881 if (!analyze_format_string::ParsePrintfString(
882 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
883 Context.getTargetInfo(), false)) {
884 DiagID = diag::warn_fortify_source_format_overflow;
885 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
886 .extOrTrunc(SizeTypeWidth);
887 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
888 DestinationSize = ComputeExplicitObjectSizeArgument(2);
889 IsChkVariant = true;
890 } else {
891 DestinationSize = ComputeSizeArgument(0);
892 }
893 break;
894 }
895 }
896 return;
897 }
898 case Builtin::BI__builtin___memcpy_chk:
899 case Builtin::BI__builtin___memmove_chk:
900 case Builtin::BI__builtin___memset_chk:
901// case Builtin::BI__builtin___strlcat_chk:
902// case Builtin::BI__builtin___strlcpy_chk:
903 case Builtin::BI__builtin___strncat_chk:
904 case Builtin::BI__builtin___strncpy_chk:
905 case Builtin::BI__builtin___stpncpy_chk:
906 case Builtin::BI__builtin___memccpy_chk:
907 case Builtin::BI__builtin___mempcpy_chk: {
908 DiagID = diag::warn_builtin_chk_overflow;
909 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
910 DestinationSize =
911 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
912 IsChkVariant = true;
913 break;
914 }
915
916 case Builtin::BI__builtin___snprintf_chk:
917 case Builtin::BI__builtin___vsnprintf_chk: {
918 DiagID = diag::warn_builtin_chk_overflow;
919 SourceSize = ComputeExplicitObjectSizeArgument(1);
920 DestinationSize = ComputeExplicitObjectSizeArgument(3);
921 IsChkVariant = true;
922 break;
923 }
924
925 case Builtin::BIstrncat:
926 case Builtin::BI__builtin_strncat:
927 case Builtin::BIstrncpy:
928 case Builtin::BI__builtin_strncpy:
929 case Builtin::BIstpncpy:
930 case Builtin::BI__builtin_stpncpy: {
931 // Whether these functions overflow depends on the runtime strlen of the
932 // string, not just the buffer size, so emitting the "always overflow"
933 // diagnostic isn't quite right. We should still diagnose passing a buffer
934 // size larger than the destination buffer though; this is a runtime abort
935 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
936 DiagID = diag::warn_fortify_source_size_mismatch;
937 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
938 DestinationSize = ComputeSizeArgument(0);
939 break;
940 }
941
942 case Builtin::BImemcpy:
943 case Builtin::BI__builtin_memcpy:
944 case Builtin::BImemmove:
945 case Builtin::BI__builtin_memmove:
946 case Builtin::BImemset:
947 case Builtin::BI__builtin_memset:
948 case Builtin::BImempcpy:
949 case Builtin::BI__builtin_mempcpy: {
950 DiagID = diag::warn_fortify_source_overflow;
951 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
952 DestinationSize = ComputeSizeArgument(0);
953 break;
954 }
955 case Builtin::BIsnprintf:
956 case Builtin::BI__builtin_snprintf:
957 case Builtin::BIvsnprintf:
958 case Builtin::BI__builtin_vsnprintf: {
959 DiagID = diag::warn_fortify_source_size_mismatch;
960 SourceSize = ComputeExplicitObjectSizeArgument(1);
961 DestinationSize = ComputeSizeArgument(0);
962 break;
963 }
964 }
965
966 if (!SourceSize || !DestinationSize ||
967 llvm::APSInt::compareValues(SourceSize.getValue(),
968 DestinationSize.getValue()) <= 0)
969 return;
970
971 StringRef FunctionName = GetFunctionName();
972
973 SmallString<16> DestinationStr;
974 SmallString<16> SourceStr;
975 DestinationSize->toString(DestinationStr, /*Radix=*/10);
976 SourceSize->toString(SourceStr, /*Radix=*/10);
977 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
978 PDiag(DiagID)
979 << FunctionName << DestinationStr << SourceStr);
980}
981
982static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
983 Scope::ScopeFlags NeededScopeFlags,
984 unsigned DiagID) {
985 // Scopes aren't available during instantiation. Fortunately, builtin
986 // functions cannot be template args so they cannot be formed through template
987 // instantiation. Therefore checking once during the parse is sufficient.
988 if (SemaRef.inTemplateInstantiation())
989 return false;
990
991 Scope *S = SemaRef.getCurScope();
992 while (S && !S->isSEHExceptScope())
993 S = S->getParent();
994 if (!S || !(S->getFlags() & NeededScopeFlags)) {
995 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
996 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
997 << DRE->getDecl()->getIdentifier();
998 return true;
999 }
1000
1001 return false;
1002}
1003
1004static inline bool isBlockPointer(Expr *Arg) {
1005 return Arg->getType()->isBlockPointerType();
1006}
1007
1008/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
1009/// void*, which is a requirement of device side enqueue.
1010static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
1011 const BlockPointerType *BPT =
1012 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1013 ArrayRef<QualType> Params =
1014 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
1015 unsigned ArgCounter = 0;
1016 bool IllegalParams = false;
1017 // Iterate through the block parameters until either one is found that is not
1018 // a local void*, or the block is valid.
1019 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
1020 I != E; ++I, ++ArgCounter) {
1021 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
1022 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
1023 LangAS::opencl_local) {
1024 // Get the location of the error. If a block literal has been passed
1025 // (BlockExpr) then we can point straight to the offending argument,
1026 // else we just point to the variable reference.
1027 SourceLocation ErrorLoc;
1028 if (isa<BlockExpr>(BlockArg)) {
1029 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
1030 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
1031 } else if (isa<DeclRefExpr>(BlockArg)) {
1032 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
1033 }
1034 S.Diag(ErrorLoc,
1035 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
1036 IllegalParams = true;
1037 }
1038 }
1039
1040 return IllegalParams;
1041}
1042
1043static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
1044 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
1045 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
1046 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
1047 return true;
1048 }
1049 return false;
1050}
1051
1052static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
1053 if (checkArgCount(S, TheCall, 2))
1054 return true;
1055
1056 if (checkOpenCLSubgroupExt(S, TheCall))
1057 return true;
1058
1059 // First argument is an ndrange_t type.
1060 Expr *NDRangeArg = TheCall->getArg(0);
1061 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1062 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1063 << TheCall->getDirectCallee() << "'ndrange_t'";
1064 return true;
1065 }
1066
1067 Expr *BlockArg = TheCall->getArg(1);
1068 if (!isBlockPointer(BlockArg)) {
1069 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1070 << TheCall->getDirectCallee() << "block";
1071 return true;
1072 }
1073 return checkOpenCLBlockArgs(S, BlockArg);
1074}
1075
1076/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
1077/// get_kernel_work_group_size
1078/// and get_kernel_preferred_work_group_size_multiple builtin functions.
1079static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
1080 if (checkArgCount(S, TheCall, 1))
1081 return true;
1082
1083 Expr *BlockArg = TheCall->getArg(0);
1084 if (!isBlockPointer(BlockArg)) {
1085 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1086 << TheCall->getDirectCallee() << "block";
1087 return true;
1088 }
1089 return checkOpenCLBlockArgs(S, BlockArg);
1090}
1091
1092/// Diagnose integer type and any valid implicit conversion to it.
1093static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
1094 const QualType &IntType);
1095
1096static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
1097 unsigned Start, unsigned End) {
1098 bool IllegalParams = false;
1099 for (unsigned I = Start; I <= End; ++I)
1100 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
1101 S.Context.getSizeType());
1102 return IllegalParams;
1103}
1104
1105/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
1106/// 'local void*' parameter of passed block.
1107static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
1108 Expr *BlockArg,
1109 unsigned NumNonVarArgs) {
1110 const BlockPointerType *BPT =
1111 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1112 unsigned NumBlockParams =
1113 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
1114 unsigned TotalNumArgs = TheCall->getNumArgs();
1115
1116 // For each argument passed to the block, a corresponding uint needs to
1117 // be passed to describe the size of the local memory.
1118 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
1119 S.Diag(TheCall->getBeginLoc(),
1120 diag::err_opencl_enqueue_kernel_local_size_args);
1121 return true;
1122 }
1123
1124 // Check that the sizes of the local memory are specified by integers.
1125 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
1126 TotalNumArgs - 1);
1127}
1128
1129/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
1130/// overload formats specified in Table 6.13.17.1.
1131/// int enqueue_kernel(queue_t queue,
1132/// kernel_enqueue_flags_t flags,
1133/// const ndrange_t ndrange,
1134/// void (^block)(void))
1135/// int enqueue_kernel(queue_t queue,
1136/// kernel_enqueue_flags_t flags,
1137/// const ndrange_t ndrange,
1138/// uint num_events_in_wait_list,
1139/// clk_event_t *event_wait_list,
1140/// clk_event_t *event_ret,
1141/// void (^block)(void))
1142/// int enqueue_kernel(queue_t queue,
1143/// kernel_enqueue_flags_t flags,
1144/// const ndrange_t ndrange,
1145/// void (^block)(local void*, ...),
1146/// uint size0, ...)
1147/// int enqueue_kernel(queue_t queue,
1148/// kernel_enqueue_flags_t flags,
1149/// const ndrange_t ndrange,
1150/// uint num_events_in_wait_list,
1151/// clk_event_t *event_wait_list,
1152/// clk_event_t *event_ret,
1153/// void (^block)(local void*, ...),
1154/// uint size0, ...)
1155static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
1156 unsigned NumArgs = TheCall->getNumArgs();
1157
1158 if (NumArgs < 4) {
1159 S.Diag(TheCall->getBeginLoc(),
1160 diag::err_typecheck_call_too_few_args_at_least)
1161 << 0 << 4 << NumArgs;
1162 return true;
1163 }
1164
1165 Expr *Arg0 = TheCall->getArg(0);
1166 Expr *Arg1 = TheCall->getArg(1);
1167 Expr *Arg2 = TheCall->getArg(2);
1168 Expr *Arg3 = TheCall->getArg(3);
1169
1170 // First argument always needs to be a queue_t type.
1171 if (!Arg0->getType()->isQueueT()) {
1172 S.Diag(TheCall->getArg(0)->getBeginLoc(),
1173 diag::err_opencl_builtin_expected_type)
1174 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
1175 return true;
1176 }
1177
1178 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
1179 if (!Arg1->getType()->isIntegerType()) {
1180 S.Diag(TheCall->getArg(1)->getBeginLoc(),
1181 diag::err_opencl_builtin_expected_type)
1182 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
1183 return true;
1184 }
1185
1186 // Third argument is always an ndrange_t type.
1187 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1188 S.Diag(TheCall->getArg(2)->getBeginLoc(),
1189 diag::err_opencl_builtin_expected_type)
1190 << TheCall->getDirectCallee() << "'ndrange_t'";
1191 return true;
1192 }
1193
1194 // With four arguments, there is only one form that the function could be
1195 // called in: no events and no variable arguments.
1196 if (NumArgs == 4) {
1197 // check that the last argument is the right block type.
1198 if (!isBlockPointer(Arg3)) {
1199 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1200 << TheCall->getDirectCallee() << "block";
1201 return true;
1202 }
1203 // we have a block type, check the prototype
1204 const BlockPointerType *BPT =
1205 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1206 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1207 S.Diag(Arg3->getBeginLoc(),
1208 diag::err_opencl_enqueue_kernel_blocks_no_args);
1209 return true;
1210 }
1211 return false;
1212 }
1213 // we can have block + varargs.
1214 if (isBlockPointer(Arg3))
1215 return (checkOpenCLBlockArgs(S, Arg3) ||
1216 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1217 // last two cases with either exactly 7 args or 7 args and varargs.
1218 if (NumArgs >= 7) {
1219 // check common block argument.
1220 Expr *Arg6 = TheCall->getArg(6);
1221 if (!isBlockPointer(Arg6)) {
1222 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1223 << TheCall->getDirectCallee() << "block";
1224 return true;
1225 }
1226 if (checkOpenCLBlockArgs(S, Arg6))
1227 return true;
1228
1229 // Forth argument has to be any integer type.
1230 if (!Arg3->getType()->isIntegerType()) {
1231 S.Diag(TheCall->getArg(3)->getBeginLoc(),
1232 diag::err_opencl_builtin_expected_type)
1233 << TheCall->getDirectCallee() << "integer";
1234 return true;
1235 }
1236 // check remaining common arguments.
1237 Expr *Arg4 = TheCall->getArg(4);
1238 Expr *Arg5 = TheCall->getArg(5);
1239
1240 // Fifth argument is always passed as a pointer to clk_event_t.
1241 if (!Arg4->isNullPointerConstant(S.Context,
1242 Expr::NPC_ValueDependentIsNotNull) &&
1243 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1244 S.Diag(TheCall->getArg(4)->getBeginLoc(),
1245 diag::err_opencl_builtin_expected_type)
1246 << TheCall->getDirectCallee()
1247 << S.Context.getPointerType(S.Context.OCLClkEventTy);
1248 return true;
1249 }
1250
1251 // Sixth argument is always passed as a pointer to clk_event_t.
1252 if (!Arg5->isNullPointerConstant(S.Context,
1253 Expr::NPC_ValueDependentIsNotNull) &&
1254 !(Arg5->getType()->isPointerType() &&
1255 Arg5->getType()->getPointeeType()->isClkEventT())) {
1256 S.Diag(TheCall->getArg(5)->getBeginLoc(),
1257 diag::err_opencl_builtin_expected_type)
1258 << TheCall->getDirectCallee()
1259 << S.Context.getPointerType(S.Context.OCLClkEventTy);
1260 return true;
1261 }
1262
1263 if (NumArgs == 7)
1264 return false;
1265
1266 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1267 }
1268
1269 // None of the specific case has been detected, give generic error
1270 S.Diag(TheCall->getBeginLoc(),
1271 diag::err_opencl_enqueue_kernel_incorrect_args);
1272 return true;
1273}
1274
1275/// Returns OpenCL access qual.
1276static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1277 return D->getAttr<OpenCLAccessAttr>();
1278}
1279
1280/// Returns true if pipe element type is different from the pointer.
1281static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1282 const Expr *Arg0 = Call->getArg(0);
1283 // First argument type should always be pipe.
1284 if (!Arg0->getType()->isPipeType()) {
1285 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1286 << Call->getDirectCallee() << Arg0->getSourceRange();
1287 return true;
1288 }
1289 OpenCLAccessAttr *AccessQual =
1290 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1291 // Validates the access qualifier is compatible with the call.
1292 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1293 // read_only and write_only, and assumed to be read_only if no qualifier is
1294 // specified.
1295 switch (Call->getDirectCallee()->getBuiltinID()) {
1296 case Builtin::BIread_pipe:
1297 case Builtin::BIreserve_read_pipe:
1298 case Builtin::BIcommit_read_pipe:
1299 case Builtin::BIwork_group_reserve_read_pipe:
1300 case Builtin::BIsub_group_reserve_read_pipe:
1301 case Builtin::BIwork_group_commit_read_pipe:
1302 case Builtin::BIsub_group_commit_read_pipe:
1303 if (!(!AccessQual || AccessQual->isReadOnly())) {
1304 S.Diag(Arg0->getBeginLoc(),
1305 diag::err_opencl_builtin_pipe_invalid_access_modifier)
1306 << "read_only" << Arg0->getSourceRange();
1307 return true;
1308 }
1309 break;
1310 case Builtin::BIwrite_pipe:
1311 case Builtin::BIreserve_write_pipe:
1312 case Builtin::BIcommit_write_pipe:
1313 case Builtin::BIwork_group_reserve_write_pipe:
1314 case Builtin::BIsub_group_reserve_write_pipe:
1315 case Builtin::BIwork_group_commit_write_pipe:
1316 case Builtin::BIsub_group_commit_write_pipe:
1317 if (!(AccessQual && AccessQual->isWriteOnly())) {
1318 S.Diag(Arg0->getBeginLoc(),
1319 diag::err_opencl_builtin_pipe_invalid_access_modifier)
1320 << "write_only" << Arg0->getSourceRange();
1321 return true;
1322 }
1323 break;
1324 default:
1325 break;
1326 }
1327 return false;
1328}
1329
1330/// Returns true if pipe element type is different from the pointer.
1331static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1332 const Expr *Arg0 = Call->getArg(0);
1333 const Expr *ArgIdx = Call->getArg(Idx);
1334 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1335 const QualType EltTy = PipeTy->getElementType();
1336 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1337 // The Idx argument should be a pointer and the type of the pointer and
1338 // the type of pipe element should also be the same.
1339 if (!ArgTy ||
1340 !S.Context.hasSameType(
1341 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1342 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1343 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1344 << ArgIdx->getType() << ArgIdx->getSourceRange();
1345 return true;
1346 }
1347 return false;
1348}
1349
1350// Performs semantic analysis for the read/write_pipe call.
1351// \param S Reference to the semantic analyzer.
1352// \param Call A pointer to the builtin call.
1353// \return True if a semantic error has been found, false otherwise.
1354static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1355 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1356 // functions have two forms.
1357 switch (Call->getNumArgs()) {
1358 case 2:
1359 if (checkOpenCLPipeArg(S, Call))
1360 return true;
1361 // The call with 2 arguments should be
1362 // read/write_pipe(pipe T, T*).
1363 // Check packet type T.
1364 if (checkOpenCLPipePacketType(S, Call, 1))
1365 return true;
1366 break;
1367
1368 case 4: {
1369 if (checkOpenCLPipeArg(S, Call))
1370 return true;
1371 // The call with 4 arguments should be
1372 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1373 // Check reserve_id_t.
1374 if (!Call->getArg(1)->getType()->isReserveIDT()) {
1375 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1376 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1377 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1378 return true;
1379 }
1380
1381 // Check the index.
1382 const Expr *Arg2 = Call->getArg(2);
1383 if (!Arg2->getType()->isIntegerType() &&
1384 !Arg2->getType()->isUnsignedIntegerType()) {
1385 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1386 << Call->getDirectCallee() << S.Context.UnsignedIntTy
1387 << Arg2->getType() << Arg2->getSourceRange();
1388 return true;
1389 }
1390
1391 // Check packet type T.
1392 if (checkOpenCLPipePacketType(S, Call, 3))
1393 return true;
1394 } break;
1395 default:
1396 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1397 << Call->getDirectCallee() << Call->getSourceRange();
1398 return true;
1399 }
1400
1401 return false;
1402}
1403
1404// Performs a semantic analysis on the {work_group_/sub_group_
1405// /_}reserve_{read/write}_pipe
1406// \param S Reference to the semantic analyzer.
1407// \param Call The call to the builtin function to be analyzed.
1408// \return True if a semantic error was found, false otherwise.
1409static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1410 if (checkArgCount(S, Call, 2))
1411 return true;
1412
1413 if (checkOpenCLPipeArg(S, Call))
1414 return true;
1415
1416 // Check the reserve size.
1417 if (!Call->getArg(1)->getType()->isIntegerType() &&
1418 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1419 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1420 << Call->getDirectCallee() << S.Context.UnsignedIntTy
1421 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1422 return true;
1423 }
1424
1425 // Since return type of reserve_read/write_pipe built-in function is
1426 // reserve_id_t, which is not defined in the builtin def file , we used int
1427 // as return type and need to override the return type of these functions.
1428 Call->setType(S.Context.OCLReserveIDTy);
1429
1430 return false;
1431}
1432
1433// Performs a semantic analysis on {work_group_/sub_group_
1434// /_}commit_{read/write}_pipe
1435// \param S Reference to the semantic analyzer.
1436// \param Call The call to the builtin function to be analyzed.
1437// \return True if a semantic error was found, false otherwise.
1438static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1439 if (checkArgCount(S, Call, 2))
1440 return true;
1441
1442 if (checkOpenCLPipeArg(S, Call))
1443 return true;
1444
1445 // Check reserve_id_t.
1446 if (!Call->getArg(1)->getType()->isReserveIDT()) {
1447 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1448 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1449 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1450 return true;
1451 }
1452
1453 return false;
1454}
1455
1456// Performs a semantic analysis on the call to built-in Pipe
1457// Query Functions.
1458// \param S Reference to the semantic analyzer.
1459// \param Call The call to the builtin function to be analyzed.
1460// \return True if a semantic error was found, false otherwise.
1461static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1462 if (checkArgCount(S, Call, 1))
1463 return true;
1464
1465 if (!Call->getArg(0)->getType()->isPipeType()) {
1466 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1467 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1468 return true;
1469 }
1470
1471 return false;
1472}
1473
1474// OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1475// Performs semantic analysis for the to_global/local/private call.
1476// \param S Reference to the semantic analyzer.
1477// \param BuiltinID ID of the builtin function.
1478// \param Call A pointer to the builtin call.
1479// \return True if a semantic error has been found, false otherwise.
1480static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1481 CallExpr *Call) {
1482 if (checkArgCount(S, Call, 1))
1483 return true;
1484
1485 auto RT = Call->getArg(0)->getType();
1486 if (!RT->isPointerType() || RT->getPointeeType()
1487 .getAddressSpace() == LangAS::opencl_constant) {
1488 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1489 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1490 return true;
1491 }
1492
1493 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1494 S.Diag(Call->getArg(0)->getBeginLoc(),
1495 diag::warn_opencl_generic_address_space_arg)
1496 << Call->getDirectCallee()->getNameInfo().getAsString()
1497 << Call->getArg(0)->getSourceRange();
1498 }
1499
1500 RT = RT->getPointeeType();
1501 auto Qual = RT.getQualifiers();
1502 switch (BuiltinID) {
1503 case Builtin::BIto_global:
1504 Qual.setAddressSpace(LangAS::opencl_global);
1505 break;
1506 case Builtin::BIto_local:
1507 Qual.setAddressSpace(LangAS::opencl_local);
1508 break;
1509 case Builtin::BIto_private:
1510 Qual.setAddressSpace(LangAS::opencl_private);
1511 break;
1512 default:
1513 llvm_unreachable("Invalid builtin function")::llvm::llvm_unreachable_internal("Invalid builtin function",
"clang/lib/Sema/SemaChecking.cpp", 1513)
;
1514 }
1515 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1516 RT.getUnqualifiedType(), Qual)));
1517
1518 return false;
1519}
1520
1521static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1522 if (checkArgCount(S, TheCall, 1))
1523 return ExprError();
1524
1525 // Compute __builtin_launder's parameter type from the argument.
1526 // The parameter type is:
1527 // * The type of the argument if it's not an array or function type,
1528 // Otherwise,
1529 // * The decayed argument type.
1530 QualType ParamTy = [&]() {
1531 QualType ArgTy = TheCall->getArg(0)->getType();
1532 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1533 return S.Context.getPointerType(Ty->getElementType());
1534 if (ArgTy->isFunctionType()) {
1535 return S.Context.getPointerType(ArgTy);
1536 }
1537 return ArgTy;
1538 }();
1539
1540 TheCall->setType(ParamTy);
1541
1542 auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1543 if (!ParamTy->isPointerType())
1544 return 0;
1545 if (ParamTy->isFunctionPointerType())
1546 return 1;
1547 if (ParamTy->isVoidPointerType())
1548 return 2;
1549 return llvm::Optional<unsigned>{};
1550 }();
1551 if (DiagSelect.hasValue()) {
1552 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1553 << DiagSelect.getValue() << TheCall->getSourceRange();
1554 return ExprError();
1555 }
1556
1557 // We either have an incomplete class type, or we have a class template
1558 // whose instantiation has not been forced. Example:
1559 //
1560 // template <class T> struct Foo { T value; };
1561 // Foo<int> *p = nullptr;
1562 // auto *d = __builtin_launder(p);
1563 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1564 diag::err_incomplete_type))
1565 return ExprError();
1566
1567 assert(ParamTy->getPointeeType()->isObjectType() &&(static_cast <bool> (ParamTy->getPointeeType()->isObjectType
() && "Unhandled non-object pointer case") ? void (0)
: __assert_fail ("ParamTy->getPointeeType()->isObjectType() && \"Unhandled non-object pointer case\""
, "clang/lib/Sema/SemaChecking.cpp", 1568, __extension__ __PRETTY_FUNCTION__
))
1568 "Unhandled non-object pointer case")(static_cast <bool> (ParamTy->getPointeeType()->isObjectType
() && "Unhandled non-object pointer case") ? void (0)
: __assert_fail ("ParamTy->getPointeeType()->isObjectType() && \"Unhandled non-object pointer case\""
, "clang/lib/Sema/SemaChecking.cpp", 1568, __extension__ __PRETTY_FUNCTION__
))
;
1569
1570 InitializedEntity Entity =
1571 InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1572 ExprResult Arg =
1573 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1574 if (Arg.isInvalid())
1575 return ExprError();
1576 TheCall->setArg(0, Arg.get());
1577
1578 return TheCall;
1579}
1580
1581// Emit an error and return true if the current object format type is in the
1582// list of unsupported types.
1583static bool CheckBuiltinTargetNotInUnsupported(
1584 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1585 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
1586 llvm::Triple::ObjectFormatType CurObjFormat =
1587 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
1588 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
1589 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1590 << TheCall->getSourceRange();
1591 return true;
1592 }
1593 return false;
1594}
1595
1596// Emit an error and return true if the current architecture is not in the list
1597// of supported architectures.
1598static bool
1599CheckBuiltinTargetInSupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1600 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1601 llvm::Triple::ArchType CurArch =
1602 S.getASTContext().getTargetInfo().getTriple().getArch();
1603 if (llvm::is_contained(SupportedArchs, CurArch))
1604 return false;
1605 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1606 << TheCall->getSourceRange();
1607 return true;
1608}
1609
1610static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1611 SourceLocation CallSiteLoc);
1612
1613bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1614 CallExpr *TheCall) {
1615 switch (TI.getTriple().getArch()) {
1616 default:
1617 // Some builtins don't require additional checking, so just consider these
1618 // acceptable.
1619 return false;
1620 case llvm::Triple::arm:
1621 case llvm::Triple::armeb:
1622 case llvm::Triple::thumb:
1623 case llvm::Triple::thumbeb:
1624 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1625 case llvm::Triple::aarch64:
1626 case llvm::Triple::aarch64_32:
1627 case llvm::Triple::aarch64_be:
1628 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1629 case llvm::Triple::bpfeb:
1630 case llvm::Triple::bpfel:
1631 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1632 case llvm::Triple::hexagon:
1633 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1634 case llvm::Triple::mips:
1635 case llvm::Triple::mipsel:
1636 case llvm::Triple::mips64:
1637 case llvm::Triple::mips64el:
1638 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1639 case llvm::Triple::systemz:
1640 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1641 case llvm::Triple::x86:
1642 case llvm::Triple::x86_64:
1643 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1644 case llvm::Triple::ppc:
1645 case llvm::Triple::ppcle:
1646 case llvm::Triple::ppc64:
1647 case llvm::Triple::ppc64le:
1648 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1649 case llvm::Triple::amdgcn:
1650 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1651 case llvm::Triple::riscv32:
1652 case llvm::Triple::riscv64:
1653 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1654 }
1655}
1656
1657ExprResult
1658Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1659 CallExpr *TheCall) {
1660 ExprResult TheCallResult(TheCall);
1661
1662 // Find out if any arguments are required to be integer constant expressions.
1663 unsigned ICEArguments = 0;
1664 ASTContext::GetBuiltinTypeError Error;
1665 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1666 if (Error != ASTContext::GE_None)
1667 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
1668
1669 // If any arguments are required to be ICE's, check and diagnose.
1670 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1671 // Skip arguments not required to be ICE's.
1672 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1673
1674 llvm::APSInt Result;
1675 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1676 return true;
1677 ICEArguments &= ~(1 << ArgNo);
1678 }
1679
1680 switch (BuiltinID) {
1681 case Builtin::BI__builtin___CFStringMakeConstantString:
1682 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
1683 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
1684 if (CheckBuiltinTargetNotInUnsupported(
1685 *this, BuiltinID, TheCall,
1686 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
1687 return ExprError();
1688 assert(TheCall->getNumArgs() == 1 &&(static_cast <bool> (TheCall->getNumArgs() == 1 &&
"Wrong # arguments to builtin CFStringMakeConstantString") ?
void (0) : __assert_fail ("TheCall->getNumArgs() == 1 && \"Wrong # arguments to builtin CFStringMakeConstantString\""
, "clang/lib/Sema/SemaChecking.cpp", 1689, __extension__ __PRETTY_FUNCTION__
))
1689 "Wrong # arguments to builtin CFStringMakeConstantString")(static_cast <bool> (TheCall->getNumArgs() == 1 &&
"Wrong # arguments to builtin CFStringMakeConstantString") ?
void (0) : __assert_fail ("TheCall->getNumArgs() == 1 && \"Wrong # arguments to builtin CFStringMakeConstantString\""
, "clang/lib/Sema/SemaChecking.cpp", 1689, __extension__ __PRETTY_FUNCTION__
))
;
1690 if (CheckObjCString(TheCall->getArg(0)))
1691 return ExprError();
1692 break;
1693 case Builtin::BI__builtin_ms_va_start:
1694 case Builtin::BI__builtin_stdarg_start:
1695 case Builtin::BI__builtin_va_start:
1696 if (SemaBuiltinVAStart(BuiltinID, TheCall))
1697 return ExprError();
1698 break;
1699 case Builtin::BI__va_start: {
1700 switch (Context.getTargetInfo().getTriple().getArch()) {
1701 case llvm::Triple::aarch64:
1702 case llvm::Triple::arm:
1703 case llvm::Triple::thumb:
1704 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1705 return ExprError();
1706 break;
1707 default:
1708 if (SemaBuiltinVAStart(BuiltinID, TheCall))
1709 return ExprError();
1710 break;
1711 }
1712 break;
1713 }
1714
1715 // The acquire, release, and no fence variants are ARM and AArch64 only.
1716 case Builtin::BI_interlockedbittestandset_acq:
1717 case Builtin::BI_interlockedbittestandset_rel:
1718 case Builtin::BI_interlockedbittestandset_nf:
1719 case Builtin::BI_interlockedbittestandreset_acq:
1720 case Builtin::BI_interlockedbittestandreset_rel:
1721 case Builtin::BI_interlockedbittestandreset_nf:
1722 if (CheckBuiltinTargetInSupported(
1723 *this, BuiltinID, TheCall,
1724 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1725 return ExprError();
1726 break;
1727
1728 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1729 case Builtin::BI_bittest64:
1730 case Builtin::BI_bittestandcomplement64:
1731 case Builtin::BI_bittestandreset64:
1732 case Builtin::BI_bittestandset64:
1733 case Builtin::BI_interlockedbittestandreset64:
1734 case Builtin::BI_interlockedbittestandset64:
1735 if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall,
1736 {llvm::Triple::x86_64, llvm::Triple::arm,
1737 llvm::Triple::thumb,
1738 llvm::Triple::aarch64}))
1739 return ExprError();
1740 break;
1741
1742 case Builtin::BI__builtin_isgreater:
1743 case Builtin::BI__builtin_isgreaterequal:
1744 case Builtin::BI__builtin_isless:
1745 case Builtin::BI__builtin_islessequal:
1746 case Builtin::BI__builtin_islessgreater:
1747 case Builtin::BI__builtin_isunordered:
1748 if (SemaBuiltinUnorderedCompare(TheCall))
1749 return ExprError();
1750 break;
1751 case Builtin::BI__builtin_fpclassify:
1752 if (SemaBuiltinFPClassification(TheCall, 6))
1753 return ExprError();
1754 break;
1755 case Builtin::BI__builtin_isfinite:
1756 case Builtin::BI__builtin_isinf:
1757 case Builtin::BI__builtin_isinf_sign:
1758 case Builtin::BI__builtin_isnan:
1759 case Builtin::BI__builtin_isnormal:
1760 case Builtin::BI__builtin_signbit:
1761 case Builtin::BI__builtin_signbitf:
1762 case Builtin::BI__builtin_signbitl:
1763 if (SemaBuiltinFPClassification(TheCall, 1))
1764 return ExprError();
1765 break;
1766 case Builtin::BI__builtin_shufflevector:
1767 return SemaBuiltinShuffleVector(TheCall);
1768 // TheCall will be freed by the smart pointer here, but that's fine, since
1769 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1770 case Builtin::BI__builtin_prefetch:
1771 if (SemaBuiltinPrefetch(TheCall))
1772 return ExprError();
1773 break;
1774 case Builtin::BI__builtin_alloca_with_align:
1775 case Builtin::BI__builtin_alloca_with_align_uninitialized:
1776 if (SemaBuiltinAllocaWithAlign(TheCall))
1777 return ExprError();
1778 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1779 case Builtin::BI__builtin_alloca:
1780 case Builtin::BI__builtin_alloca_uninitialized:
1781 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1782 << TheCall->getDirectCallee();
1783 break;
1784 case Builtin::BI__arithmetic_fence:
1785 if (SemaBuiltinArithmeticFence(TheCall))
1786 return ExprError();
1787 break;
1788 case Builtin::BI__assume:
1789 case Builtin::BI__builtin_assume:
1790 if (SemaBuiltinAssume(TheCall))
1791 return ExprError();
1792 break;
1793 case Builtin::BI__builtin_assume_aligned:
1794 if (SemaBuiltinAssumeAligned(TheCall))
1795 return ExprError();
1796 break;
1797 case Builtin::BI__builtin_dynamic_object_size:
1798 case Builtin::BI__builtin_object_size:
1799 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1800 return ExprError();
1801 break;
1802 case Builtin::BI__builtin_longjmp:
1803 if (SemaBuiltinLongjmp(TheCall))
1804 return ExprError();
1805 break;
1806 case Builtin::BI__builtin_setjmp:
1807 if (SemaBuiltinSetjmp(TheCall))
1808 return ExprError();
1809 break;
1810 case Builtin::BI__builtin_classify_type:
1811 if (checkArgCount(*this, TheCall, 1)) return true;
1812 TheCall->setType(Context.IntTy);
1813 break;
1814 case Builtin::BI__builtin_complex:
1815 if (SemaBuiltinComplex(TheCall))
1816 return ExprError();
1817 break;
1818 case Builtin::BI__builtin_constant_p: {
1819 if (checkArgCount(*this, TheCall, 1)) return true;
1820 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1821 if (Arg.isInvalid()) return true;
1822 TheCall->setArg(0, Arg.get());
1823 TheCall->setType(Context.IntTy);
1824 break;
1825 }
1826 case Builtin::BI__builtin_launder:
1827 return SemaBuiltinLaunder(*this, TheCall);
1828 case Builtin::BI__sync_fetch_and_add:
1829 case Builtin::BI__sync_fetch_and_add_1:
1830 case Builtin::BI__sync_fetch_and_add_2:
1831 case Builtin::BI__sync_fetch_and_add_4:
1832 case Builtin::BI__sync_fetch_and_add_8:
1833 case Builtin::BI__sync_fetch_and_add_16:
1834 case Builtin::BI__sync_fetch_and_sub:
1835 case Builtin::BI__sync_fetch_and_sub_1:
1836 case Builtin::BI__sync_fetch_and_sub_2:
1837 case Builtin::BI__sync_fetch_and_sub_4:
1838 case Builtin::BI__sync_fetch_and_sub_8:
1839 case Builtin::BI__sync_fetch_and_sub_16:
1840 case Builtin::BI__sync_fetch_and_or:
1841 case Builtin::BI__sync_fetch_and_or_1:
1842 case Builtin::BI__sync_fetch_and_or_2:
1843 case Builtin::BI__sync_fetch_and_or_4:
1844 case Builtin::BI__sync_fetch_and_or_8:
1845 case Builtin::BI__sync_fetch_and_or_16:
1846 case Builtin::BI__sync_fetch_and_and:
1847 case Builtin::BI__sync_fetch_and_and_1:
1848 case Builtin::BI__sync_fetch_and_and_2:
1849 case Builtin::BI__sync_fetch_and_and_4:
1850 case Builtin::BI__sync_fetch_and_and_8:
1851 case Builtin::BI__sync_fetch_and_and_16:
1852 case Builtin::BI__sync_fetch_and_xor:
1853 case Builtin::BI__sync_fetch_and_xor_1:
1854 case Builtin::BI__sync_fetch_and_xor_2:
1855 case Builtin::BI__sync_fetch_and_xor_4:
1856 case Builtin::BI__sync_fetch_and_xor_8:
1857 case Builtin::BI__sync_fetch_and_xor_16:
1858 case Builtin::BI__sync_fetch_and_nand:
1859 case Builtin::BI__sync_fetch_and_nand_1:
1860 case Builtin::BI__sync_fetch_and_nand_2:
1861 case Builtin::BI__sync_fetch_and_nand_4:
1862 case Builtin::BI__sync_fetch_and_nand_8:
1863 case Builtin::BI__sync_fetch_and_nand_16:
1864 case Builtin::BI__sync_add_and_fetch:
1865 case Builtin::BI__sync_add_and_fetch_1:
1866 case Builtin::BI__sync_add_and_fetch_2:
1867 case Builtin::BI__sync_add_and_fetch_4:
1868 case Builtin::BI__sync_add_and_fetch_8:
1869 case Builtin::BI__sync_add_and_fetch_16:
1870 case Builtin::BI__sync_sub_and_fetch:
1871 case Builtin::BI__sync_sub_and_fetch_1:
1872 case Builtin::BI__sync_sub_and_fetch_2:
1873 case Builtin::BI__sync_sub_and_fetch_4:
1874 case Builtin::BI__sync_sub_and_fetch_8:
1875 case Builtin::BI__sync_sub_and_fetch_16:
1876 case Builtin::BI__sync_and_and_fetch:
1877 case Builtin::BI__sync_and_and_fetch_1:
1878 case Builtin::BI__sync_and_and_fetch_2:
1879 case Builtin::BI__sync_and_and_fetch_4:
1880 case Builtin::BI__sync_and_and_fetch_8:
1881 case Builtin::BI__sync_and_and_fetch_16:
1882 case Builtin::BI__sync_or_and_fetch:
1883 case Builtin::BI__sync_or_and_fetch_1:
1884 case Builtin::BI__sync_or_and_fetch_2:
1885 case Builtin::BI__sync_or_and_fetch_4:
1886 case Builtin::BI__sync_or_and_fetch_8:
1887 case Builtin::BI__sync_or_and_fetch_16:
1888 case Builtin::BI__sync_xor_and_fetch:
1889 case Builtin::BI__sync_xor_and_fetch_1:
1890 case Builtin::BI__sync_xor_and_fetch_2:
1891 case Builtin::BI__sync_xor_and_fetch_4:
1892 case Builtin::BI__sync_xor_and_fetch_8:
1893 case Builtin::BI__sync_xor_and_fetch_16:
1894 case Builtin::BI__sync_nand_and_fetch:
1895 case Builtin::BI__sync_nand_and_fetch_1:
1896 case Builtin::BI__sync_nand_and_fetch_2:
1897 case Builtin::BI__sync_nand_and_fetch_4:
1898 case Builtin::BI__sync_nand_and_fetch_8:
1899 case Builtin::BI__sync_nand_and_fetch_16:
1900 case Builtin::BI__sync_val_compare_and_swap:
1901 case Builtin::BI__sync_val_compare_and_swap_1:
1902 case Builtin::BI__sync_val_compare_and_swap_2:
1903 case Builtin::BI__sync_val_compare_and_swap_4:
1904 case Builtin::BI__sync_val_compare_and_swap_8:
1905 case Builtin::BI__sync_val_compare_and_swap_16:
1906 case Builtin::BI__sync_bool_compare_and_swap:
1907 case Builtin::BI__sync_bool_compare_and_swap_1:
1908 case Builtin::BI__sync_bool_compare_and_swap_2:
1909 case Builtin::BI__sync_bool_compare_and_swap_4:
1910 case Builtin::BI__sync_bool_compare_and_swap_8:
1911 case Builtin::BI__sync_bool_compare_and_swap_16:
1912 case Builtin::BI__sync_lock_test_and_set:
1913 case Builtin::BI__sync_lock_test_and_set_1:
1914 case Builtin::BI__sync_lock_test_and_set_2:
1915 case Builtin::BI__sync_lock_test_and_set_4:
1916 case Builtin::BI__sync_lock_test_and_set_8:
1917 case Builtin::BI__sync_lock_test_and_set_16:
1918 case Builtin::BI__sync_lock_release:
1919 case Builtin::BI__sync_lock_release_1:
1920 case Builtin::BI__sync_lock_release_2:
1921 case Builtin::BI__sync_lock_release_4:
1922 case Builtin::BI__sync_lock_release_8:
1923 case Builtin::BI__sync_lock_release_16:
1924 case Builtin::BI__sync_swap:
1925 case Builtin::BI__sync_swap_1:
1926 case Builtin::BI__sync_swap_2:
1927 case Builtin::BI__sync_swap_4:
1928 case Builtin::BI__sync_swap_8:
1929 case Builtin::BI__sync_swap_16:
1930 return SemaBuiltinAtomicOverloaded(TheCallResult);
1931 case Builtin::BI__sync_synchronize:
1932 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1933 << TheCall->getCallee()->getSourceRange();
1934 break;
1935 case Builtin::BI__builtin_nontemporal_load:
1936 case Builtin::BI__builtin_nontemporal_store:
1937 return SemaBuiltinNontemporalOverloaded(TheCallResult);
1938 case Builtin::BI__builtin_memcpy_inline: {
1939 clang::Expr *SizeOp = TheCall->getArg(2);
1940 // We warn about copying to or from `nullptr` pointers when `size` is
1941 // greater than 0. When `size` is value dependent we cannot evaluate its
1942 // value so we bail out.
1943 if (SizeOp->isValueDependent())
1944 break;
1945 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
1946 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1947 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1948 }
1949 break;
1950 }
1951#define BUILTIN(ID, TYPE, ATTRS)
1952#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1953 case Builtin::BI##ID: \
1954 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1955#include "clang/Basic/Builtins.def"
1956 case Builtin::BI__annotation:
1957 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1958 return ExprError();
1959 break;
1960 case Builtin::BI__builtin_annotation:
1961 if (SemaBuiltinAnnotation(*this, TheCall))
1962 return ExprError();
1963 break;
1964 case Builtin::BI__builtin_addressof:
1965 if (SemaBuiltinAddressof(*this, TheCall))
1966 return ExprError();
1967 break;
1968 case Builtin::BI__builtin_function_start:
1969 if (SemaBuiltinFunctionStart(*this, TheCall))
1970 return ExprError();
1971 break;
1972 case Builtin::BI__builtin_is_aligned:
1973 case Builtin::BI__builtin_align_up:
1974 case Builtin::BI__builtin_align_down:
1975 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1976 return ExprError();
1977 break;
1978 case Builtin::BI__builtin_add_overflow:
1979 case Builtin::BI__builtin_sub_overflow:
1980 case Builtin::BI__builtin_mul_overflow:
1981 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1982 return ExprError();
1983 break;
1984 case Builtin::BI__builtin_operator_new:
1985 case Builtin::BI__builtin_operator_delete: {
1986 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1987 ExprResult Res =
1988 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1989 if (Res.isInvalid())
1990 CorrectDelayedTyposInExpr(TheCallResult.get());
1991 return Res;
1992 }
1993 case Builtin::BI__builtin_dump_struct: {
1994 // We first want to ensure we are called with 2 arguments
1995 if (checkArgCount(*this, TheCall, 2))
1996 return ExprError();
1997 // Ensure that the first argument is of type 'struct XX *'
1998 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1999 const QualType PtrArgType = PtrArg->getType();
2000 if (!PtrArgType->isPointerType() ||
2001 !PtrArgType->getPointeeType()->isRecordType()) {
2002 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2003 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
2004 << "structure pointer";
2005 return ExprError();
2006 }
2007
2008 // Ensure that the second argument is of type 'FunctionType'
2009 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
2010 const QualType FnPtrArgType = FnPtrArg->getType();
2011 if (!FnPtrArgType->isPointerType()) {
2012 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2013 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
2014 << FnPtrArgType << "'int (*)(const char *, ...)'";
2015 return ExprError();
2016 }
2017
2018 const auto *FuncType =
2019 FnPtrArgType->getPointeeType()->getAs<FunctionType>();
2020
2021 if (!FuncType) {
2022 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2023 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
2024 << FnPtrArgType << "'int (*)(const char *, ...)'";
2025 return ExprError();
2026 }
2027
2028 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
2029 if (!FT->getNumParams()) {
2030 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2031 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
2032 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
2033 return ExprError();
2034 }
2035 QualType PT = FT->getParamType(0);
2036 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
2037 !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
2038 !PT->getPointeeType().isConstQualified()) {
2039 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
2040 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
2041 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
2042 return ExprError();
2043 }
2044 }
2045
2046 TheCall->setType(Context.IntTy);
2047 break;
2048 }
2049 case Builtin::BI__builtin_expect_with_probability: {
2050 // We first want to ensure we are called with 3 arguments
2051 if (checkArgCount(*this, TheCall, 3))
2052 return ExprError();
2053 // then check probability is constant float in range [0.0, 1.0]
2054 const Expr *ProbArg = TheCall->getArg(2);
2055 SmallVector<PartialDiagnosticAt, 8> Notes;
2056 Expr::EvalResult Eval;
2057 Eval.Diag = &Notes;
2058 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2059 !Eval.Val.isFloat()) {
2060 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2061 << ProbArg->getSourceRange();
2062 for (const PartialDiagnosticAt &PDiag : Notes)
2063 Diag(PDiag.first, PDiag.second);
2064 return ExprError();
2065 }
2066 llvm::APFloat Probability = Eval.Val.getFloat();
2067 bool LoseInfo = false;
2068 Probability.convert(llvm::APFloat::IEEEdouble(),
2069 llvm::RoundingMode::Dynamic, &LoseInfo);
2070 if (!(Probability >= llvm::APFloat(0.0) &&
2071 Probability <= llvm::APFloat(1.0))) {
2072 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2073 << ProbArg->getSourceRange();
2074 return ExprError();
2075 }
2076 break;
2077 }
2078 case Builtin::BI__builtin_preserve_access_index:
2079 if (SemaBuiltinPreserveAI(*this, TheCall))
2080 return ExprError();
2081 break;
2082 case Builtin::BI__builtin_call_with_static_chain:
2083 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
2084 return ExprError();
2085 break;
2086 case Builtin::BI__exception_code:
2087 case Builtin::BI_exception_code:
2088 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
2089 diag::err_seh___except_block))
2090 return ExprError();
2091 break;
2092 case Builtin::BI__exception_info:
2093 case Builtin::BI_exception_info:
2094 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2095 diag::err_seh___except_filter))
2096 return ExprError();
2097 break;
2098 case Builtin::BI__GetExceptionInfo:
2099 if (checkArgCount(*this, TheCall, 1))
2100 return ExprError();
2101
2102 if (CheckCXXThrowOperand(
2103 TheCall->getBeginLoc(),
2104 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
2105 TheCall))
2106 return ExprError();
2107
2108 TheCall->setType(Context.VoidPtrTy);
2109 break;
2110 // OpenCL v2.0, s6.13.16 - Pipe functions
2111 case Builtin::BIread_pipe:
2112 case Builtin::BIwrite_pipe:
2113 // Since those two functions are declared with var args, we need a semantic
2114 // check for the argument.
2115 if (SemaBuiltinRWPipe(*this, TheCall))
2116 return ExprError();
2117 break;
2118 case Builtin::BIreserve_read_pipe:
2119 case Builtin::BIreserve_write_pipe:
2120 case Builtin::BIwork_group_reserve_read_pipe:
2121 case Builtin::BIwork_group_reserve_write_pipe:
2122 if (SemaBuiltinReserveRWPipe(*this, TheCall))
2123 return ExprError();
2124 break;
2125 case Builtin::BIsub_group_reserve_read_pipe:
2126 case Builtin::BIsub_group_reserve_write_pipe:
2127 if (checkOpenCLSubgroupExt(*this, TheCall) ||
2128 SemaBuiltinReserveRWPipe(*this, TheCall))
2129 return ExprError();
2130 break;
2131 case Builtin::BIcommit_read_pipe:
2132 case Builtin::BIcommit_write_pipe:
2133 case Builtin::BIwork_group_commit_read_pipe:
2134 case Builtin::BIwork_group_commit_write_pipe:
2135 if (SemaBuiltinCommitRWPipe(*this, TheCall))
2136 return ExprError();
2137 break;
2138 case Builtin::BIsub_group_commit_read_pipe:
2139 case Builtin::BIsub_group_commit_write_pipe:
2140 if (checkOpenCLSubgroupExt(*this, TheCall) ||
2141 SemaBuiltinCommitRWPipe(*this, TheCall))
2142 return ExprError();
2143 break;
2144 case Builtin::BIget_pipe_num_packets:
2145 case Builtin::BIget_pipe_max_packets:
2146 if (SemaBuiltinPipePackets(*this, TheCall))
2147 return ExprError();
2148 break;
2149 case Builtin::BIto_global:
2150 case Builtin::BIto_local:
2151 case Builtin::BIto_private:
2152 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
2153 return ExprError();
2154 break;
2155 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2156 case Builtin::BIenqueue_kernel:
2157 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
2158 return ExprError();
2159 break;
2160 case Builtin::BIget_kernel_work_group_size:
2161 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2162 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
2163 return ExprError();
2164 break;
2165 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2166 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2167 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
2168 return ExprError();
2169 break;
2170 case Builtin::BI__builtin_os_log_format:
2171 Cleanup.setExprNeedsCleanups(true);
2172 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2173 case Builtin::BI__builtin_os_log_format_buffer_size:
2174 if (SemaBuiltinOSLogFormat(TheCall))
2175 return ExprError();
2176 break;
2177 case Builtin::BI__builtin_frame_address:
2178 case Builtin::BI__builtin_return_address: {
2179 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
2180 return ExprError();
2181
2182 // -Wframe-address warning if non-zero passed to builtin
2183 // return/frame address.
2184 Expr::EvalResult Result;
2185 if (!TheCall->getArg(0)->isValueDependent() &&
2186 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
2187 Result.Val.getInt() != 0)
2188 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
2189 << ((BuiltinID == Builtin::BI__builtin_return_address)
2190 ? "__builtin_return_address"
2191 : "__builtin_frame_address")
2192 << TheCall->getSourceRange();
2193 break;
2194 }
2195
2196 // __builtin_elementwise_abs restricts the element type to signed integers or
2197 // floating point types only.
2198 case Builtin::BI__builtin_elementwise_abs: {
2199 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2200 return ExprError();
2201
2202 QualType ArgTy = TheCall->getArg(0)->getType();
2203 QualType EltTy = ArgTy;
2204
2205 if (auto *VecTy = EltTy->getAs<VectorType>())
2206 EltTy = VecTy->getElementType();
2207 if (EltTy->isUnsignedIntegerType()) {
2208 Diag(TheCall->getArg(0)->getBeginLoc(),
2209 diag::err_builtin_invalid_arg_type)
2210 << 1 << /* signed integer or float ty*/ 3 << ArgTy;
2211 return ExprError();
2212 }
2213 break;
2214 }
2215
2216 // These builtins restrict the element type to floating point
2217 // types only.
2218 case Builtin::BI__builtin_elementwise_ceil:
2219 case Builtin::BI__builtin_elementwise_floor:
2220 case Builtin::BI__builtin_elementwise_roundeven:
2221 case Builtin::BI__builtin_elementwise_trunc: {
2222 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2223 return ExprError();
2224
2225 QualType ArgTy = TheCall->getArg(0)->getType();
2226 QualType EltTy = ArgTy;
2227
2228 if (auto *VecTy = EltTy->getAs<VectorType>())
2229 EltTy = VecTy->getElementType();
2230 if (!EltTy->isFloatingType()) {
2231 Diag(TheCall->getArg(0)->getBeginLoc(),
2232 diag::err_builtin_invalid_arg_type)
2233 << 1 << /* float ty*/ 5 << ArgTy;
2234
2235 return ExprError();
2236 }
2237 break;
2238 }
2239
2240 case Builtin::BI__builtin_elementwise_min:
2241 case Builtin::BI__builtin_elementwise_max:
2242 if (SemaBuiltinElementwiseMath(TheCall))
2243 return ExprError();
2244 break;
2245 case Builtin::BI__builtin_reduce_max:
2246 case Builtin::BI__builtin_reduce_min: {
2247 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2248 return ExprError();
2249
2250 const Expr *Arg = TheCall->getArg(0);
2251 const auto *TyA = Arg->getType()->getAs<VectorType>();
2252 if (!TyA) {
2253 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2254 << 1 << /* vector ty*/ 4 << Arg->getType();
2255 return ExprError();
2256 }
2257
2258 TheCall->setType(TyA->getElementType());
2259 break;
2260 }
2261
2262 // These builtins support vectors of integers only.
2263 case Builtin::BI__builtin_reduce_xor:
2264 case Builtin::BI__builtin_reduce_or:
2265 case Builtin::BI__builtin_reduce_and: {
2266 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2267 return ExprError();
2268
2269 const Expr *Arg = TheCall->getArg(0);
2270 const auto *TyA = Arg->getType()->getAs<VectorType>();
2271 if (!TyA || !TyA->getElementType()->isIntegerType()) {
2272 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2273 << 1 << /* vector of integers */ 6 << Arg->getType();
2274 return ExprError();
2275 }
2276 TheCall->setType(TyA->getElementType());
2277 break;
2278 }
2279
2280 case Builtin::BI__builtin_matrix_transpose:
2281 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
2282
2283 case Builtin::BI__builtin_matrix_column_major_load:
2284 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
2285
2286 case Builtin::BI__builtin_matrix_column_major_store:
2287 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
2288
2289 case Builtin::BI__builtin_get_device_side_mangled_name: {
2290 auto Check = [](CallExpr *TheCall) {
2291 if (TheCall->getNumArgs() != 1)
2292 return false;
2293 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2294 if (!DRE)
2295 return false;
2296 auto *D = DRE->getDecl();
2297 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2298 return false;
2299 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2300 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2301 };
2302 if (!Check(TheCall)) {
2303 Diag(TheCall->getBeginLoc(),
2304 diag::err_hip_invalid_args_builtin_mangled_name);
2305 return ExprError();
2306 }
2307 }
2308 }
2309
2310 // Since the target specific builtins for each arch overlap, only check those
2311 // of the arch we are compiling for.
2312 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2313 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2314 assert(Context.getAuxTargetInfo() &&(static_cast <bool> (Context.getAuxTargetInfo() &&
"Aux Target Builtin, but not an aux target?") ? void (0) : __assert_fail
("Context.getAuxTargetInfo() && \"Aux Target Builtin, but not an aux target?\""
, "clang/lib/Sema/SemaChecking.cpp", 2315, __extension__ __PRETTY_FUNCTION__
))
2315 "Aux Target Builtin, but not an aux target?")(static_cast <bool> (Context.getAuxTargetInfo() &&
"Aux Target Builtin, but not an aux target?") ? void (0) : __assert_fail
("Context.getAuxTargetInfo() && \"Aux Target Builtin, but not an aux target?\""
, "clang/lib/Sema/SemaChecking.cpp", 2315, __extension__ __PRETTY_FUNCTION__
))
;
2316
2317 if (CheckTSBuiltinFunctionCall(
2318 *Context.getAuxTargetInfo(),
2319 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2320 return ExprError();
2321 } else {
2322 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2323 TheCall))
2324 return ExprError();
2325 }
2326 }
2327
2328 return TheCallResult;
2329}
2330
2331// Get the valid immediate range for the specified NEON type code.
2332static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2333 NeonTypeFlags Type(t);
2334 int IsQuad = ForceQuad ? true : Type.isQuad();
2335 switch (Type.getEltType()) {
2336 case NeonTypeFlags::Int8:
2337 case NeonTypeFlags::Poly8:
2338 return shift ? 7 : (8 << IsQuad) - 1;
2339 case NeonTypeFlags::Int16:
2340 case NeonTypeFlags::Poly16:
2341 return shift ? 15 : (4 << IsQuad) - 1;
2342 case NeonTypeFlags::Int32:
2343 return shift ? 31 : (2 << IsQuad) - 1;
2344 case NeonTypeFlags::Int64:
2345 case NeonTypeFlags::Poly64:
2346 return shift ? 63 : (1 << IsQuad) - 1;
2347 case NeonTypeFlags::Poly128:
2348 return shift ? 127 : (1 << IsQuad) - 1;
2349 case NeonTypeFlags::Float16:
2350 assert(!shift && "cannot shift float types!")(static_cast <bool> (!shift && "cannot shift float types!"
) ? void (0) : __assert_fail ("!shift && \"cannot shift float types!\""
, "clang/lib/Sema/SemaChecking.cpp", 2350, __extension__ __PRETTY_FUNCTION__
))
;
2351 return (4 << IsQuad) - 1;
2352 case NeonTypeFlags::Float32:
2353 assert(!shift && "cannot shift float types!")(static_cast <bool> (!shift && "cannot shift float types!"
) ? void (0) : __assert_fail ("!shift && \"cannot shift float types!\""
, "clang/lib/Sema/SemaChecking.cpp", 2353, __extension__ __PRETTY_FUNCTION__
))
;
2354 return (2 << IsQuad) - 1;
2355 case NeonTypeFlags::Float64:
2356 assert(!shift && "cannot shift float types!")(static_cast <bool> (!shift && "cannot shift float types!"
) ? void (0) : __assert_fail ("!shift && \"cannot shift float types!\""
, "clang/lib/Sema/SemaChecking.cpp", 2356, __extension__ __PRETTY_FUNCTION__
))
;
2357 return (1 << IsQuad) - 1;
2358 case NeonTypeFlags::BFloat16:
2359 assert(!shift && "cannot shift float types!")(static_cast <bool> (!shift && "cannot shift float types!"
) ? void (0) : __assert_fail ("!shift && \"cannot shift float types!\""
, "clang/lib/Sema/SemaChecking.cpp", 2359, __extension__ __PRETTY_FUNCTION__
))
;
2360 return (4 << IsQuad) - 1;
2361 }
2362 llvm_unreachable("Invalid NeonTypeFlag!")::llvm::llvm_unreachable_internal("Invalid NeonTypeFlag!", "clang/lib/Sema/SemaChecking.cpp"
, 2362)
;
2363}
2364
2365/// getNeonEltType - Return the QualType corresponding to the elements of
2366/// the vector type specified by the NeonTypeFlags. This is used to check
2367/// the pointer arguments for Neon load/store intrinsics.
2368static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2369 bool IsPolyUnsigned, bool IsInt64Long) {
2370 switch (Flags.getEltType()) {
2371 case NeonTypeFlags::Int8:
2372 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2373 case NeonTypeFlags::Int16:
2374 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2375 case NeonTypeFlags::Int32:
2376 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2377 case NeonTypeFlags::Int64:
2378 if (IsInt64Long)
2379 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2380 else
2381 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2382 : Context.LongLongTy;
2383 case NeonTypeFlags::Poly8:
2384 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2385 case NeonTypeFlags::Poly16:
2386 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2387 case NeonTypeFlags::Poly64:
2388 if (IsInt64Long)
2389 return Context.UnsignedLongTy;
2390 else
2391 return Context.UnsignedLongLongTy;
2392 case NeonTypeFlags::Poly128:
2393 break;
2394 case NeonTypeFlags::Float16:
2395 return Context.HalfTy;
2396 case NeonTypeFlags::Float32:
2397 return Context.FloatTy;
2398 case NeonTypeFlags::Float64:
2399 return Context.DoubleTy;
2400 case NeonTypeFlags::BFloat16:
2401 return Context.BFloat16Ty;
2402 }
2403 llvm_unreachable("Invalid NeonTypeFlag!")::llvm::llvm_unreachable_internal("Invalid NeonTypeFlag!", "clang/lib/Sema/SemaChecking.cpp"
, 2403)
;
2404}
2405
2406bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2407 // Range check SVE intrinsics that take immediate values.
2408 SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2409
2410 switch (BuiltinID) {
2411 default:
2412 return false;
2413#define GET_SVE_IMMEDIATE_CHECK
2414#include "clang/Basic/arm_sve_sema_rangechecks.inc"
2415#undef GET_SVE_IMMEDIATE_CHECK
2416 }
2417
2418 // Perform all the immediate checks for this builtin call.
2419 bool HasError = false;
2420 for (auto &I : ImmChecks) {
2421 int ArgNum, CheckTy, ElementSizeInBits;
2422 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2423
2424 typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2425
2426 // Function that checks whether the operand (ArgNum) is an immediate
2427 // that is one of the predefined values.
2428 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2429 int ErrDiag) -> bool {
2430 // We can't check the value of a dependent argument.
2431 Expr *Arg = TheCall->getArg(ArgNum);
2432 if (Arg->isTypeDependent() || Arg->isValueDependent())
2433 return false;
2434
2435 // Check constant-ness first.
2436 llvm::APSInt Imm;
2437 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2438 return true;
2439
2440 if (!CheckImm(Imm.getSExtValue()))
2441 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2442 return false;
2443 };
2444
2445 switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2446 case SVETypeFlags::ImmCheck0_31:
2447 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2448 HasError = true;
2449 break;
2450 case SVETypeFlags::ImmCheck0_13:
2451 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2452 HasError = true;
2453 break;
2454 case SVETypeFlags::ImmCheck1_16:
2455 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2456 HasError = true;
2457 break;
2458 case SVETypeFlags::ImmCheck0_7:
2459 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2460 HasError = true;
2461 break;
2462 case SVETypeFlags::ImmCheckExtract:
2463 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2464 (2048 / ElementSizeInBits) - 1))
2465 HasError = true;
2466 break;
2467 case SVETypeFlags::ImmCheckShiftRight:
2468 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2469 HasError = true;
2470 break;
2471 case SVETypeFlags::ImmCheckShiftRightNarrow:
2472 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2473 ElementSizeInBits / 2))
2474 HasError = true;
2475 break;
2476 case SVETypeFlags::ImmCheckShiftLeft:
2477 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2478 ElementSizeInBits - 1))
2479 HasError = true;
2480 break;
2481 case SVETypeFlags::ImmCheckLaneIndex:
2482 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2483 (128 / (1 * ElementSizeInBits)) - 1))
2484 HasError = true;
2485 break;
2486 case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2487 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2488 (128 / (2 * ElementSizeInBits)) - 1))
2489 HasError = true;
2490 break;
2491 case SVETypeFlags::ImmCheckLaneIndexDot:
2492 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2493 (128 / (4 * ElementSizeInBits)) - 1))
2494 HasError = true;
2495 break;
2496 case SVETypeFlags::ImmCheckComplexRot90_270:
2497 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2498 diag::err_rotation_argument_to_cadd))
2499 HasError = true;
2500 break;
2501 case SVETypeFlags::ImmCheckComplexRotAll90:
2502 if (CheckImmediateInSet(
2503 [](int64_t V) {
2504 return V == 0 || V == 90 || V == 180 || V == 270;
2505 },
2506 diag::err_rotation_argument_to_cmla))
2507 HasError = true;
2508 break;
2509 case SVETypeFlags::ImmCheck0_1:
2510 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2511 HasError = true;
2512 break;
2513 case SVETypeFlags::ImmCheck0_2:
2514 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2515 HasError = true;
2516 break;
2517 case SVETypeFlags::ImmCheck0_3:
2518 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2519 HasError = true;
2520 break;
2521 }
2522 }
2523
2524 return HasError;
2525}
2526
2527bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2528 unsigned BuiltinID, CallExpr *TheCall) {
2529 llvm::APSInt Result;
2530 uint64_t mask = 0;
2531 unsigned TV = 0;
2532 int PtrArgNum = -1;
2533 bool HasConstPtr = false;
2534 switch (BuiltinID) {
2535#define GET_NEON_OVERLOAD_CHECK
2536#include "clang/Basic/arm_neon.inc"
2537#include "clang/Basic/arm_fp16.inc"
2538#undef GET_NEON_OVERLOAD_CHECK
2539 }
2540
2541 // For NEON intrinsics which are overloaded on vector element type, validate
2542 // the immediate which specifies which variant to emit.
2543 unsigned ImmArg = TheCall->getNumArgs()-1;
2544 if (mask) {
2545 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2546 return true;
2547
2548 TV = Result.getLimitedValue(64);
2549 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2550 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2551 << TheCall->getArg(ImmArg)->getSourceRange();
2552 }
2553
2554 if (PtrArgNum >= 0) {
2555 // Check that pointer arguments have the specified type.
2556 Expr *Arg = TheCall->getArg(PtrArgNum);
2557 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2558 Arg = ICE->getSubExpr();
2559 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2560 QualType RHSTy = RHS.get()->getType();
2561
2562 llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2563 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2564 Arch == llvm::Triple::aarch64_32 ||
2565 Arch == llvm::Triple::aarch64_be;
2566 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2567 QualType EltTy =
2568 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2569 if (HasConstPtr)
2570 EltTy = EltTy.withConst();
2571 QualType LHSTy = Context.getPointerType(EltTy);
2572 AssignConvertType ConvTy;
2573 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2574 if (RHS.isInvalid())
2575 return true;
2576 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2577 RHS.get(), AA_Assigning))
2578 return true;
2579 }
2580
2581 // For NEON intrinsics which take an immediate value as part of the
2582 // instruction, range check them here.
2583 unsigned i = 0, l = 0, u = 0;
2584 switch (BuiltinID) {
2585 default:
2586 return false;
2587 #define GET_NEON_IMMEDIATE_CHECK
2588 #include "clang/Basic/arm_neon.inc"
2589 #include "clang/Basic/arm_fp16.inc"
2590 #undef GET_NEON_IMMEDIATE_CHECK
2591 }
2592
2593 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2594}
2595
2596bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2597 switch (BuiltinID) {
2598 default:
2599 return false;
2600 #include "clang/Basic/arm_mve_builtin_sema.inc"
2601 }
2602}
2603
2604bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2605 CallExpr *TheCall) {
2606 bool Err = false;
2607 switch (BuiltinID) {
2608 default:
2609 return false;
2610#include "clang/Basic/arm_cde_builtin_sema.inc"
2611 }
2612
2613 if (Err)
2614 return true;
2615
2616 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2617}
2618
2619bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2620 const Expr *CoprocArg, bool WantCDE) {
2621 if (isConstantEvaluated())
2622 return false;
2623
2624 // We can't check the value of a dependent argument.
2625 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2626 return false;
2627
2628 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2629 int64_t CoprocNo = CoprocNoAP.getExtValue();
2630 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative")(static_cast <bool> (CoprocNo >= 0 && "Coprocessor immediate must be non-negative"
) ? void (0) : __assert_fail ("CoprocNo >= 0 && \"Coprocessor immediate must be non-negative\""
, "clang/lib/Sema/SemaChecking.cpp", 2630, __extension__ __PRETTY_FUNCTION__
))
;
2631
2632 uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2633 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2634
2635 if (IsCDECoproc != WantCDE)
2636 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2637 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2638
2639 return false;
2640}
2641
2642bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2643 unsigned MaxWidth) {
2644 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||(static_cast <bool> ((BuiltinID == ARM::BI__builtin_arm_ldrex
|| BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM
::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex
|| BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID ==
AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex
|| BuiltinID == AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? void (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "clang/lib/Sema/SemaChecking.cpp", 2652, __extension__ __PRETTY_FUNCTION__
))
2645 BuiltinID == ARM::BI__builtin_arm_ldaex ||(static_cast <bool> ((BuiltinID == ARM::BI__builtin_arm_ldrex
|| BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM
::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex
|| BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID ==
AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex
|| BuiltinID == AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? void (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "clang/lib/Sema/SemaChecking.cpp", 2652, __extension__ __PRETTY_FUNCTION__
))
2646 BuiltinID == ARM::BI__builtin_arm_strex ||(static_cast <bool> ((BuiltinID == ARM::BI__builtin_arm_ldrex
|| BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM
::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex
|| BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID ==
AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex
|| BuiltinID == AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? void (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "clang/lib/Sema/SemaChecking.cpp", 2652, __extension__ __PRETTY_FUNCTION__
))
2647 BuiltinID == ARM::BI__builtin_arm_stlex ||(static_cast <bool> ((BuiltinID == ARM::BI__builtin_arm_ldrex
|| BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM
::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex
|| BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID ==
AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex
|| BuiltinID == AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? void (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "clang/lib/Sema/SemaChecking.cpp", 2652, __extension__ __PRETTY_FUNCTION__
))
2648 BuiltinID == AArch64::BI__builtin_arm_ldrex ||(static_cast <bool> ((BuiltinID == ARM::BI__builtin_arm_ldrex
|| BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM
::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex
|| BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID ==
AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex
|| BuiltinID == AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? void (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "clang/lib/Sema/SemaChecking.cpp", 2652, __extension__ __PRETTY_FUNCTION__
))
2649 BuiltinID == AArch64::BI__builtin_arm_ldaex ||(static_cast <bool> ((BuiltinID == ARM::BI__builtin_arm_ldrex
|| BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM
::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex
|| BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID ==
AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex
|| BuiltinID == AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? void (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "clang/lib/Sema/SemaChecking.cpp", 2652, __extension__ __PRETTY_FUNCTION__
))
2650 BuiltinID == AArch64::BI__builtin_arm_strex ||(static_cast <bool> ((BuiltinID == ARM::BI__builtin_arm_ldrex
|| BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM
::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex
|| BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID ==
AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex
|| BuiltinID == AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? void (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "clang/lib/Sema/SemaChecking.cpp", 2652, __extension__ __PRETTY_FUNCTION__
))
2651 BuiltinID == AArch64::BI__builtin_arm_stlex) &&(static_cast <bool> ((BuiltinID == ARM::BI__builtin_arm_ldrex
|| BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM
::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex
|| BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID ==
AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex
|| BuiltinID == AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? void (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "clang/lib/Sema/SemaChecking.cpp", 2652, __extension__ __PRETTY_FUNCTION__
))
2652 "unexpected ARM builtin")(static_cast <bool> ((BuiltinID == ARM::BI__builtin_arm_ldrex
|| BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM
::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex
|| BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID ==
AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex
|| BuiltinID == AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? void (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "clang/lib/Sema/SemaChecking.cpp", 2652, __extension__ __PRETTY_FUNCTION__
))
;
2653 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2654 BuiltinID == ARM::BI__builtin_arm_ldaex ||
2655 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2656 BuiltinID == AArch64::BI__builtin_arm_ldaex;
2657
2658 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2659
2660 // Ensure that we have the proper number of arguments.
2661 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2662 return true;
2663
2664 // Inspect the pointer argument of the atomic builtin. This should always be
2665 // a pointer type, whose element is an integral scalar or pointer type.
2666 // Because it is a pointer type, we don't have to worry about any implicit
2667 // casts here.
2668 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2669 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2670 if (PointerArgRes.isInvalid())
2671 return true;
2672 PointerArg = PointerArgRes.get();
2673
2674 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2675 if (!pointerType) {
2676 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2677 << PointerArg->getType() << PointerArg->getSourceRange();
2678 return true;
2679 }
2680
2681 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2682 // task is to insert the appropriate casts into the AST. First work out just
2683 // what the appropriate type is.
2684 QualType ValType = pointerType->getPointeeType();
2685 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2686 if (IsLdrex)
2687 AddrType.addConst();
2688
2689 // Issue a warning if the cast is dodgy.
2690 CastKind CastNeeded = CK_NoOp;
2691 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2692 CastNeeded = CK_BitCast;
2693 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2694 << PointerArg->getType() << Context.getPointerType(AddrType)
2695 << AA_Passing << PointerArg->getSourceRange();
2696 }
2697
2698 // Finally, do the cast and replace the argument with the corrected version.
2699 AddrType = Context.getPointerType(AddrType);
2700 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2701 if (PointerArgRes.isInvalid())
2702 return true;
2703 PointerArg = PointerArgRes.get();
2704
2705 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2706
2707 // In general, we allow ints, floats and pointers to be loaded and stored.
2708 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2709 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2710 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2711 << PointerArg->getType() << PointerArg->getSourceRange();
2712 return true;
2713 }
2714
2715 // But ARM doesn't have instructions to deal with 128-bit versions.
2716 if (Context.getTypeSize(ValType) > MaxWidth) {
2717 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate")(static_cast <bool> (MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"
) ? void (0) : __assert_fail ("MaxWidth == 64 && \"Diagnostic unexpectedly inaccurate\""
, "clang/lib/Sema/SemaChecking.cpp", 2717, __extension__ __PRETTY_FUNCTION__
))
;
2718 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2719 << PointerArg->getType() << PointerArg->getSourceRange();
2720 return true;
2721 }
2722
2723 switch (ValType.getObjCLifetime()) {
2724 case Qualifiers::OCL_None:
2725 case Qualifiers::OCL_ExplicitNone:
2726 // okay
2727 break;
2728
2729 case Qualifiers::OCL_Weak:
2730 case Qualifiers::OCL_Strong:
2731 case Qualifiers::OCL_Autoreleasing:
2732 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2733 << ValType << PointerArg->getSourceRange();
2734 return true;
2735 }
2736
2737 if (IsLdrex) {
2738 TheCall->setType(ValType);
2739 return false;
2740 }
2741
2742 // Initialize the argument to be stored.
2743 ExprResult ValArg = TheCall->getArg(0);
2744 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2745 Context, ValType, /*consume*/ false);
2746 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2747 if (ValArg.isInvalid())
2748 return true;
2749 TheCall->setArg(0, ValArg.get());
2750
2751 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2752 // but the custom checker bypasses all default analysis.
2753 TheCall->setType(Context.IntTy);
2754 return false;
2755}
2756
2757bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2758 CallExpr *TheCall) {
2759 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2760 BuiltinID == ARM::BI__builtin_arm_ldaex ||
2761 BuiltinID == ARM::BI__builtin_arm_strex ||
2762 BuiltinID == ARM::BI__builtin_arm_stlex) {
2763 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2764 }
2765
2766 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2767 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2768 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2769 }
2770
2771 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2772 BuiltinID == ARM::BI__builtin_arm_wsr64)
2773 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2774
2775 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2776 BuiltinID == ARM::BI__builtin_arm_rsrp ||
2777 BuiltinID == ARM::BI__builtin_arm_wsr ||
2778 BuiltinID == ARM::BI__builtin_arm_wsrp)
2779 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2780
2781 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2782 return true;
2783 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2784 return true;
2785 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2786 return true;
2787
2788 // For intrinsics which take an immediate value as part of the instruction,
2789 // range check them here.
2790 // FIXME: VFP Intrinsics should error if VFP not present.
2791 switch (BuiltinID) {
2792 default: return false;
2793 case ARM::BI__builtin_arm_ssat:
2794 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2795 case ARM::BI__builtin_arm_usat:
2796 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2797 case ARM::BI__builtin_arm_ssat16:
2798 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2799 case ARM::BI__builtin_arm_usat16:
2800 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2801 case ARM::BI__builtin_arm_vcvtr_f:
2802 case ARM::BI__builtin_arm_vcvtr_d:
2803 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2804 case ARM::BI__builtin_arm_dmb:
2805 case ARM::BI__builtin_arm_dsb:
2806 case ARM::BI__builtin_arm_isb:
2807 case ARM::BI__builtin_arm_dbg:
2808 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2809 case ARM::BI__builtin_arm_cdp:
2810 case ARM::BI__builtin_arm_cdp2:
2811 case ARM::BI__builtin_arm_mcr:
2812 case ARM::BI__builtin_arm_mcr2:
2813 case ARM::BI__builtin_arm_mrc:
2814 case ARM::BI__builtin_arm_mrc2:
2815 case ARM::BI__builtin_arm_mcrr:
2816 case ARM::BI__builtin_arm_mcrr2:
2817 case ARM::BI__builtin_arm_mrrc:
2818 case ARM::BI__builtin_arm_mrrc2:
2819 case ARM::BI__builtin_arm_ldc:
2820 case ARM::BI__builtin_arm_ldcl:
2821 case ARM::BI__builtin_arm_ldc2:
2822 case ARM::BI__builtin_arm_ldc2l:
2823 case ARM::BI__builtin_arm_stc:
2824 case ARM::BI__builtin_arm_stcl:
2825 case ARM::BI__builtin_arm_stc2:
2826 case ARM::BI__builtin_arm_stc2l:
2827 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2828 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2829 /*WantCDE*/ false);
2830 }
2831}
2832
2833bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2834 unsigned BuiltinID,
2835 CallExpr *TheCall) {
2836 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2837 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2838 BuiltinID == AArch64::BI__builtin_arm_strex ||
2839 BuiltinID == AArch64::BI__builtin_arm_stlex) {
2840 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2841 }
2842
2843 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2844 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2845 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2846 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2847 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2848 }
2849
2850 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2851 BuiltinID == AArch64::BI__builtin_arm_wsr64)
2852 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2853
2854 // Memory Tagging Extensions (MTE) Intrinsics
2855 if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2856 BuiltinID == AArch64::BI__builtin_arm_addg ||
2857 BuiltinID == AArch64::BI__builtin_arm_gmi ||
2858 BuiltinID == AArch64::BI__builtin_arm_ldg ||
2859 BuiltinID == AArch64::BI__builtin_arm_stg ||
2860 BuiltinID == AArch64::BI__builtin_arm_subp) {
2861 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2862 }
2863
2864 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2865 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2866 BuiltinID == AArch64::BI__builtin_arm_wsr ||
2867 BuiltinID == AArch64::BI__builtin_arm_wsrp)
2868 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2869
2870 // Only check the valid encoding range. Any constant in this range would be
2871 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2872 // an exception for incorrect registers. This matches MSVC behavior.
2873 if (BuiltinID == AArch64::BI_ReadStatusReg ||
2874 BuiltinID == AArch64::BI_WriteStatusReg)
2875 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2876
2877 if (BuiltinID == AArch64::BI__getReg)
2878 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2879
2880 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2881 return true;
2882
2883 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2884 return true;
2885
2886 // For intrinsics which take an immediate value as part of the instruction,
2887 // range check them here.
2888 unsigned i = 0, l = 0, u = 0;
2889 switch (BuiltinID) {
2890 default: return false;
2891 case AArch64::BI__builtin_arm_dmb:
2892 case AArch64::BI__builtin_arm_dsb:
2893 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2894 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2895 }
2896
2897 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2898}
2899
2900static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2901 if (Arg->getType()->getAsPlaceholderType())
2902 return false;
2903
2904 // The first argument needs to be a record field access.
2905 // If it is an array element access, we delay decision
2906 // to BPF backend to check whether the access is a
2907 // field access or not.
2908 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2909 isa<MemberExpr>(Arg->IgnoreParens()) ||
2910 isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
2911}
2912
2913static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2914 QualType VectorTy, QualType EltTy) {
2915 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2916 if (!Context.hasSameType(VectorEltTy, EltTy)) {
2917 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2918 << Call->getSourceRange() << VectorEltTy << EltTy;
2919 return false;
2920 }
2921 return true;
2922}
2923
2924static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2925 QualType ArgType = Arg->getType();
2926 if (ArgType->getAsPlaceholderType())
2927 return false;
2928
2929 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2930 // format:
2931 // 1. __builtin_preserve_type_info(*(<type> *)0, flag);
2932 // 2. <type> var;
2933 // __builtin_preserve_type_info(var, flag);
2934 if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
2935 !isa<UnaryOperator>(Arg->IgnoreParens()))
2936 return false;
2937
2938 // Typedef type.
2939 if (ArgType->getAs<TypedefType>())
2940 return true;
2941
2942 // Record type or Enum type.
2943 const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2944 if (const auto *RT = Ty->getAs<RecordType>()) {
2945 if (!RT->getDecl()->getDeclName().isEmpty())
2946 return true;
2947 } else if (const auto *ET = Ty->getAs<EnumType>()) {
2948 if (!ET->getDecl()->getDeclName().isEmpty())
2949 return true;
2950 }
2951
2952 return false;
2953}
2954
2955static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2956 QualType ArgType = Arg->getType();
2957 if (ArgType->getAsPlaceholderType())
2958 return false;
2959
2960 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2961 // format:
2962 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2963 // flag);
2964 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2965 if (!UO)
2966 return false;
2967
2968 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2969 if (!CE)
2970 return false;
2971 if (CE->getCastKind() != CK_IntegralToPointer &&
2972 CE->getCastKind() != CK_NullToPointer)
2973 return false;
2974
2975 // The integer must be from an EnumConstantDecl.
2976 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2977 if (!DR)
2978 return false;
2979
2980 const EnumConstantDecl *Enumerator =
2981 dyn_cast<EnumConstantDecl>(DR->getDecl());
2982 if (!Enumerator)
2983 return false;
2984
2985 // The type must be EnumType.
2986 const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2987 const auto *ET = Ty->getAs<EnumType>();
2988 if (!ET)
2989 return false;
2990
2991 // The enum value must be supported.
2992 return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
2993}
2994
2995bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2996 CallExpr *TheCall) {
2997 assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||(static_cast <bool> ((BuiltinID == BPF::BI__builtin_preserve_field_info
|| BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID ==
BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value
) && "unexpected BPF builtin") ? void (0) : __assert_fail
("(BuiltinID == BPF::BI__builtin_preserve_field_info || BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID == BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value) && \"unexpected BPF builtin\""
, "clang/lib/Sema/SemaChecking.cpp", 3001, __extension__ __PRETTY_FUNCTION__
))
2998 BuiltinID == BPF::BI__builtin_btf_type_id ||(static_cast <bool> ((BuiltinID == BPF::BI__builtin_preserve_field_info
|| BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID ==
BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value
) && "unexpected BPF builtin") ? void (0) : __assert_fail
("(BuiltinID == BPF::BI__builtin_preserve_field_info || BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID == BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value) && \"unexpected BPF builtin\""
, "clang/lib/Sema/SemaChecking.cpp", 3001, __extension__ __PRETTY_FUNCTION__
))
2999 BuiltinID == BPF::BI__builtin_preserve_type_info ||(static_cast <bool> ((BuiltinID == BPF::BI__builtin_preserve_field_info
|| BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID ==
BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value
) && "unexpected BPF builtin") ? void (0) : __assert_fail
("(BuiltinID == BPF::BI__builtin_preserve_field_info || BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID == BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value) && \"unexpected BPF builtin\""
, "clang/lib/Sema/SemaChecking.cpp", 3001, __extension__ __PRETTY_FUNCTION__
))
3000 BuiltinID == BPF::BI__builtin_preserve_enum_value) &&(static_cast <bool> ((BuiltinID == BPF::BI__builtin_preserve_field_info
|| BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID ==
BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value
) && "unexpected BPF builtin") ? void (0) : __assert_fail
("(BuiltinID == BPF::BI__builtin_preserve_field_info || BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID == BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value) && \"unexpected BPF builtin\""
, "clang/lib/Sema/SemaChecking.cpp", 3001, __extension__ __PRETTY_FUNCTION__
))
3001 "unexpected BPF builtin")(static_cast <bool> ((BuiltinID == BPF::BI__builtin_preserve_field_info
|| BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID ==
BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value
) && "unexpected BPF builtin") ? void (0) : __assert_fail
("(BuiltinID == BPF::BI__builtin_preserve_field_info || BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID == BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value) && \"unexpected BPF builtin\""
, "clang/lib/Sema/SemaChecking.cpp", 3001, __extension__ __PRETTY_FUNCTION__
))
;
3002
3003 if (checkArgCount(*this, TheCall, 2))
3004 return true;
3005
3006 // The second argument needs to be a constant int
3007 Expr *Arg = TheCall->getArg(1);
3008 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
3009 diag::kind kind;
3010 if (!Value) {
3011 if (BuiltinID == BPF::BI__builtin_preserve_field_info)
3012 kind = diag::err_preserve_field_info_not_const;
3013 else if (BuiltinID == BPF::BI__builtin_btf_type_id)
3014 kind = diag::err_btf_type_id_not_const;
3015 else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
3016 kind = diag::err_preserve_type_info_not_const;
3017 else
3018 kind = diag::err_preserve_enum_value_not_const;
3019 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
3020 return true;
3021 }
3022
3023 // The first argument
3024 Arg = TheCall->getArg(0);
3025 bool InvalidArg = false;
3026 bool ReturnUnsignedInt = true;
3027 if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
3028 if (!isValidBPFPreserveFieldInfoArg(Arg)) {
3029 InvalidArg = true;
3030 kind = diag::err_preserve_field_info_not_field;
3031 }
3032 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
3033 if (!isValidBPFPreserveTypeInfoArg(Arg)) {
3034 InvalidArg = true;
3035 kind = diag::err_preserve_type_info_invalid;
3036 }
3037 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
3038 if (!isValidBPFPreserveEnumValueArg(Arg)) {
3039 InvalidArg = true;
3040 kind = diag::err_preserve_enum_value_invalid;
3041 }
3042 ReturnUnsignedInt = false;
3043 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
3044 ReturnUnsignedInt = false;
3045 }
3046
3047 if (InvalidArg) {
3048 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
3049 return true;
3050 }
3051
3052 if (ReturnUnsignedInt)
3053 TheCall->setType(Context.UnsignedIntTy);
3054 else
3055 TheCall->setType(Context.UnsignedLongTy);
3056 return false;
3057}
3058
3059bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3060 struct ArgInfo {
3061 uint8_t OpNum;
3062 bool IsSigned;
3063 uint8_t BitWidth;
3064 uint8_t Align;
3065 };
3066 struct BuiltinInfo {
3067 unsigned BuiltinID;
3068 ArgInfo Infos[2];
3069 };
3070
3071 static BuiltinInfo Infos[] = {
3072 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
3073 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
3074 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
3075 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} },
3076 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
3077 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
3078 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
3079 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
3080 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
3081 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
3082 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
3083
3084 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
3085 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
3086 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
3087 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
3088 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
3089 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
3090 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
3091 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
3092 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
3093 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
3094 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
3095
3096 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
3097 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
3098 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
3099 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
3100 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
3101 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
3102 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
3103 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
3104 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
3105 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
3106 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
3107 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
3108 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
3109 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
3110 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
3111 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
3112 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
3113 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
3114 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
3115 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
3116 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
3117 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
3118 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
3119 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
3120 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
3121 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
3122 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
3123 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
3124 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
3125 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
3126 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
3127 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
3128 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
3129 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
3130 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
3131 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
3132 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
3133 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
3134 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
3135 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
3136 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
3137 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
3138 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
3139 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
3140 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
3141 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
3142 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
3143 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
3144 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
3145 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
3146 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
3147 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
3148 {{ 1, false, 6, 0 }} },
3149 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
3150 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
3151 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
3152 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
3153 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
3154 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
3155 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
3156 {{ 1, false, 5, 0 }} },
3157 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
3158 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
3159 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
3160 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
3161 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
3162 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
3163 { 2, false, 5, 0 }} },
3164 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
3165 { 2, false, 6, 0 }} },
3166 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
3167 { 3, false, 5, 0 }} },
3168 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
3169 { 3, false, 6, 0 }} },
3170 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
3171 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
3172 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
3173 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
3174 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
3175 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
3176 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
3177 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
3178 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
3179 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
3180 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
3181 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
3182 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
3183 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
3184 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
3185 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
3186 {{ 2, false, 4, 0 },
3187 { 3, false, 5, 0 }} },
3188 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
3189 {{ 2, false, 4, 0 },
3190 { 3, false, 5, 0 }} },
3191 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
3192 {{ 2, false, 4, 0 },
3193 { 3, false, 5, 0 }} },
3194 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
3195 {{ 2, false, 4, 0 },
3196 { 3, false, 5, 0 }} },
3197 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
3198 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
3199 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
3200 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
3201 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
3202 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
3203 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
3204 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
3205 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
3206 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
3207 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
3208 { 2, false, 5, 0 }} },
3209 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
3210 { 2, false, 6, 0 }} },
3211 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
3212 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
3213 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
3214 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
3215 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
3216 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
3217 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
3218 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
3219 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
3220 {{ 1, false, 4, 0 }} },
3221 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
3222 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
3223 {{ 1, false, 4, 0 }} },
3224 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
3225 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
3226 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
3227 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
3228 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
3229 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
3230 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
3231 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
3232 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
3233 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
3234 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
3235 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
3236 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
3237 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
3238 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
3239 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
3240 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
3241 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
3242 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
3243 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
3244 {{ 3, false, 1, 0 }} },
3245 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
3246 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
3247 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
3248 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
3249 {{ 3, false, 1, 0 }} },
3250 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
3251 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
3252 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
3253 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
3254 {{ 3, false, 1, 0 }} },
3255 };
3256
3257 // Use a dynamically initialized static to sort the table exactly once on
3258 // first run.
3259 static const bool SortOnce =
3260 (llvm::sort(Infos,
3261 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3262 return LHS.BuiltinID < RHS.BuiltinID;
3263 }),
3264 true);
3265 (void)SortOnce;
3266
3267 const BuiltinInfo *F = llvm::partition_point(
3268 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
3269 if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
3270 return false;
3271
3272 bool Error = false;
3273
3274 for (const ArgInfo &A : F->Infos) {
3275 // Ignore empty ArgInfo elements.
3276 if (A.BitWidth == 0)
3277 continue;
3278
3279 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3280 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
3281 if (!A.Align) {
3282 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3283 } else {
3284 unsigned M = 1 << A.Align;
3285 Min *= M;
3286 Max *= M;
3287 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3288 Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3289 }
3290 }
3291 return Error;
3292}
3293
3294bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3295 CallExpr *TheCall) {
3296 return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3297}
3298
3299bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3300 unsigned BuiltinID, CallExpr *TheCall) {
3301 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3302 CheckMipsBuiltinArgument(BuiltinID, TheCall);
3303}
3304
3305bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3306 CallExpr *TheCall) {
3307
3308 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3309 BuiltinID <= Mips::BI__builtin_mips_lwx) {
3310 if (!TI.hasFeature("dsp"))
3311 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3312 }
3313
3314 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3315 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3316 if (!TI.hasFeature("dspr2"))
3317 return Diag(TheCall->getBeginLoc(),
3318 diag::err_mips_builtin_requires_dspr2);
3319 }
3320
3321 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3322 BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3323 if (!TI.hasFeature("msa"))
3324 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3325 }
3326
3327 return false;
3328}
3329
3330// CheckMipsBuiltinArgument - Checks the constant value passed to the
3331// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3332// ordering for DSP is unspecified. MSA is ordered by the data format used
3333// by the underlying instruction i.e., df/m, df/n and then by size.
3334//
3335// FIXME: The size tests here should instead be tablegen'd along with the
3336// definitions from include/clang/Basic/BuiltinsMips.def.
3337// FIXME: GCC is strict on signedness for some of these intrinsics, we should
3338// be too.
3339bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3340 unsigned i = 0, l = 0, u = 0, m = 0;
3341 switch (BuiltinID) {
3342 default: return false;
3343 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3344 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3345 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3346 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3347 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3348 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3349 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3350 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3351 // df/m field.
3352 // These intrinsics take an unsigned 3 bit immediate.
3353 case Mips::BI__builtin_msa_bclri_b:
3354 case Mips::BI__builtin_msa_bnegi_b:
3355 case Mips::BI__builtin_msa_bseti_b:
3356 case Mips::BI__builtin_msa_sat_s_b:
3357 case Mips::BI__builtin_msa_sat_u_b:
3358 case Mips::BI__builtin_msa_slli_b:
3359 case Mips::BI__builtin_msa_srai_b:
3360 case Mips::BI__builtin_msa_srari_b:
3361 case Mips::BI__builtin_msa_srli_b:
3362 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3363 case Mips::BI__builtin_msa_binsli_b:
3364 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3365 // These intrinsics take an unsigned 4 bit immediate.
3366 case Mips::BI__builtin_msa_bclri_h:
3367 case Mips::BI__builtin_msa_bnegi_h:
3368 case Mips::BI__builtin_msa_bseti_h:
3369 case Mips::BI__builtin_msa_sat_s_h:
3370 case Mips::BI__builtin_msa_sat_u_h:
3371 case Mips::BI__builtin_msa_slli_h:
3372 case Mips::BI__builtin_msa_srai_h:
3373 case Mips::BI__builtin_msa_srari_h:
3374 case Mips::BI__builtin_msa_srli_h:
3375 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3376 case Mips::BI__builtin_msa_binsli_h:
3377 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3378 // These intrinsics take an unsigned 5 bit immediate.
3379 // The first block of intrinsics actually have an unsigned 5 bit field,
3380 // not a df/n field.
3381 case Mips::BI__builtin_msa_cfcmsa:
3382 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3383 case Mips::BI__builtin_msa_clei_u_b:
3384 case Mips::BI__builtin_msa_clei_u_h:
3385 case Mips::BI__builtin_msa_clei_u_w:
3386 case Mips::BI__builtin_msa_clei_u_d:
3387 case Mips::BI__builtin_msa_clti_u_b:
3388 case Mips::BI__builtin_msa_clti_u_h:
3389 case Mips::BI__builtin_msa_clti_u_w:
3390 case Mips::BI__builtin_msa_clti_u_d:
3391 case Mips::BI__builtin_msa_maxi_u_b:
3392 case Mips::BI__builtin_msa_maxi_u_h:
3393 case Mips::BI__builtin_msa_maxi_u_w:
3394 case Mips::BI__builtin_msa_maxi_u_d:
3395 case Mips::BI__builtin_msa_mini_u_b:
3396 case Mips::BI__builtin_msa_mini_u_h:
3397 case Mips::BI__builtin_msa_mini_u_w:
3398 case Mips::BI__builtin_msa_mini_u_d:
3399 case Mips::BI__builtin_msa_addvi_b:
3400 case Mips::BI__builtin_msa_addvi_h:
3401 case Mips::BI__builtin_msa_addvi_w:
3402 case Mips::BI__builtin_msa_addvi_d:
3403 case Mips::BI__builtin_msa_bclri_w:
3404 case Mips::BI__builtin_msa_bnegi_w:
3405 case Mips::BI__builtin_msa_bseti_w:
3406 case Mips::BI__builtin_msa_sat_s_w:
3407 case Mips::BI__builtin_msa_sat_u_w:
3408 case Mips::BI__builtin_msa_slli_w:
3409 case Mips::BI__builtin_msa_srai_w:
3410 case Mips::BI__builtin_msa_srari_w:
3411 case Mips::BI__builtin_msa_srli_w:
3412 case Mips::BI__builtin_msa_srlri_w:
3413 case Mips::BI__builtin_msa_subvi_b:
3414 case Mips::BI__builtin_msa_subvi_h:
3415 case Mips::BI__builtin_msa_subvi_w:
3416 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3417 case Mips::BI__builtin_msa_binsli_w:
3418 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3419 // These intrinsics take an unsigned 6 bit immediate.
3420 case Mips::BI__builtin_msa_bclri_d:
3421 case Mips::BI__builtin_msa_bnegi_d:
3422 case Mips::BI__builtin_msa_bseti_d:
3423 case Mips::BI__builtin_msa_sat_s_d:
3424 case Mips::BI__builtin_msa_sat_u_d:
3425 case Mips::BI__builtin_msa_slli_d:
3426 case Mips::BI__builtin_msa_srai_d:
3427 case Mips::BI__builtin_msa_srari_d:
3428 case Mips::BI__builtin_msa_srli_d:
3429 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3430 case Mips::BI__builtin_msa_binsli_d:
3431 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3432 // These intrinsics take a signed 5 bit immediate.
3433 case Mips::BI__builtin_msa_ceqi_b:
3434 case Mips::BI__builtin_msa_ceqi_h:
3435 case Mips::BI__builtin_msa_ceqi_w:
3436 case Mips::BI__builtin_msa_ceqi_d:
3437 case Mips::BI__builtin_msa_clti_s_b:
3438 case Mips::BI__builtin_msa_clti_s_h:
3439 case Mips::BI__builtin_msa_clti_s_w:
3440 case Mips::BI__builtin_msa_clti_s_d:
3441 case Mips::BI__builtin_msa_clei_s_b:
3442 case Mips::BI__builtin_msa_clei_s_h:
3443 case Mips::BI__builtin_msa_clei_s_w:
3444 case Mips::BI__builtin_msa_clei_s_d:
3445 case Mips::BI__builtin_msa_maxi_s_b:
3446 case Mips::BI__builtin_msa_maxi_s_h:
3447 case Mips::BI__builtin_msa_maxi_s_w:
3448 case Mips::BI__builtin_msa_maxi_s_d:
3449 case Mips::BI__builtin_msa_mini_s_b:
3450 case Mips::BI__builtin_msa_mini_s_h:
3451 case Mips::BI__builtin_msa_mini_s_w:
3452 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3453 // These intrinsics take an unsigned 8 bit immediate.
3454 case Mips::BI__builtin_msa_andi_b:
3455 case Mips::BI__builtin_msa_nori_b:
3456 case Mips::BI__builtin_msa_ori_b:
3457 case Mips::BI__builtin_msa_shf_b:
3458 case Mips::BI__builtin_msa_shf_h:
3459 case Mips::BI__builtin_msa_shf_w:
3460 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3461 case Mips::BI__builtin_msa_bseli_b:
3462 case Mips::BI__builtin_msa_bmnzi_b:
3463 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3464 // df/n format
3465 // These intrinsics take an unsigned 4 bit immediate.
3466 case Mips::BI__builtin_msa_copy_s_b:
3467 case Mips::BI__builtin_msa_copy_u_b:
3468 case Mips::BI__builtin_msa_insve_b:
3469 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3470 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3471 // These intrinsics take an unsigned 3 bit immediate.
3472 case Mips::BI__builtin_msa_copy_s_h:
3473 case Mips::BI__builtin_msa_copy_u_h:
3474 case Mips::BI__builtin_msa_insve_h:
3475 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3476 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3477 // These intrinsics take an unsigned 2 bit immediate.
3478 case Mips::BI__builtin_msa_copy_s_w:
3479 case Mips::BI__builtin_msa_copy_u_w:
3480 case Mips::BI__builtin_msa_insve_w:
3481 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3482 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3483 // These intrinsics take an unsigned 1 bit immediate.
3484 case Mips::BI__builtin_msa_copy_s_d:
3485 case Mips::BI__builtin_msa_copy_u_d:
3486 case Mips::BI__builtin_msa_insve_d:
3487 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3488 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3489 // Memory offsets and immediate loads.
3490 // These intrinsics take a signed 10 bit immediate.
3491 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3492 case Mips::BI__builtin_msa_ldi_h:
3493 case Mips::BI__builtin_msa_ldi_w:
3494 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3495 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3496 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3497 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3498 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3499 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3500 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3501 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3502 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3503 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3504 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3505 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3506 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3507 }
3508
3509 if (!m)
3510 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3511
3512 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3513 SemaBuiltinConstantArgMultiple(TheCall, i, m);
3514}
3515
3516/// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3517/// advancing the pointer over the consumed characters. The decoded type is
3518/// returned. If the decoded type represents a constant integer with a
3519/// constraint on its value then Mask is set to that value. The type descriptors
3520/// used in Str are specific to PPC MMA builtins and are documented in the file
3521/// defining the PPC builtins.
3522static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3523 unsigned &Mask) {
3524 bool RequireICE = false;
3525 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3526 switch (*Str++) {
3527 case 'V':
3528 return Context.getVectorType(Context.UnsignedCharTy, 16,
3529 VectorType::VectorKind::AltiVecVector);
3530 case 'i': {
3531 char *End;
3532 unsigned size = strtoul(Str, &End, 10);
3533 assert(End != Str && "Missing constant parameter constraint")(static_cast <bool> (End != Str && "Missing constant parameter constraint"
) ? void (0) : __assert_fail ("End != Str && \"Missing constant parameter constraint\""
, "clang/lib/Sema/SemaChecking.cpp", 3533, __extension__ __PRETTY_FUNCTION__
))
;
3534 Str = End;
3535 Mask = size;
3536 return Context.IntTy;
3537 }
3538 case 'W': {
3539 char *End;
3540 unsigned size = strtoul(Str, &End, 10);
3541 assert(End != Str && "Missing PowerPC MMA type size")(static_cast <bool> (End != Str && "Missing PowerPC MMA type size"
) ? void (0) : __assert_fail ("End != Str && \"Missing PowerPC MMA type size\""
, "clang/lib/Sema/SemaChecking.cpp", 3541, __extension__ __PRETTY_FUNCTION__
))
;
3542 Str = End;
3543 QualType Type;
3544 switch (size) {
3545 #define PPC_VECTOR_TYPE(typeName, Id, size) \
3546 case size: Type = Context.Id##Ty; break;
3547 #include "clang/Basic/PPCTypes.def"
3548 default: llvm_unreachable("Invalid PowerPC MMA vector type")::llvm::llvm_unreachable_internal("Invalid PowerPC MMA vector type"
, "clang/lib/Sema/SemaChecking.cpp", 3548)
;
3549 }
3550 bool CheckVectorArgs = false;
3551 while (!CheckVectorArgs) {
3552 switch (*Str++) {
3553 case '*':
3554 Type = Context.getPointerType(Type);
3555 break;
3556 case 'C':
3557 Type = Type.withConst();
3558 break;
3559 default:
3560 CheckVectorArgs = true;
3561 --Str;
3562 break;
3563 }
3564 }
3565 return Type;
3566 }
3567 default:
3568 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3569 }
3570}
3571
3572static bool isPPC_64Builtin(unsigned BuiltinID) {
3573 // These builtins only work on PPC 64bit targets.
3574 switch (BuiltinID) {
3575 case PPC::BI__builtin_divde:
3576 case PPC::BI__builtin_divdeu:
3577 case PPC::BI__builtin_bpermd:
3578 case PPC::BI__builtin_ppc_ldarx:
3579 case PPC::BI__builtin_ppc_stdcx:
3580 case PPC::BI__builtin_ppc_tdw:
3581 case PPC::BI__builtin_ppc_trapd:
3582 case PPC::BI__builtin_ppc_cmpeqb:
3583 case PPC::BI__builtin_ppc_setb:
3584 case PPC::BI__builtin_ppc_mulhd:
3585 case PPC::BI__builtin_ppc_mulhdu:
3586 case PPC::BI__builtin_ppc_maddhd:
3587 case PPC::BI__builtin_ppc_maddhdu:
3588 case PPC::BI__builtin_ppc_maddld:
3589 case PPC::BI__builtin_ppc_load8r:
3590 case PPC::BI__builtin_ppc_store8r:
3591 case PPC::BI__builtin_ppc_insert_exp:
3592 case PPC::BI__builtin_ppc_extract_sig:
3593 case PPC::BI__builtin_ppc_addex:
3594 case PPC::BI__builtin_darn:
3595 case PPC::BI__builtin_darn_raw:
3596 case PPC::BI__builtin_ppc_compare_and_swaplp:
3597 case PPC::BI__builtin_ppc_fetch_and_addlp:
3598 case PPC::BI__builtin_ppc_fetch_and_andlp:
3599 case PPC::BI__builtin_ppc_fetch_and_orlp:
3600 case PPC::BI__builtin_ppc_fetch_and_swaplp:
3601 return true;
3602 }
3603 return false;
3604}
3605
3606static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3607 StringRef FeatureToCheck, unsigned DiagID,
3608 StringRef DiagArg = "") {
3609 if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3610 return false;
3611
3612 if (DiagArg.empty())
3613 S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3614 else
3615 S.Diag(TheCall->getBeginLoc(), DiagID)
3616 << DiagArg << TheCall->getSourceRange();
3617
3618 return true;
3619}
3620
3621/// Returns true if the argument consists of one contiguous run of 1s with any
3622/// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3623/// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3624/// since all 1s are not contiguous.
3625bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3626 llvm::APSInt Result;
3627 // We can't check the value of a dependent argument.
3628 Expr *Arg = TheCall->getArg(ArgNum);
3629 if (Arg->isTypeDependent() || Arg->isValueDependent())
3630 return false;
3631
3632 // Check constant-ness first.
3633 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3634 return true;
3635
3636 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3637 if (Result.isShiftedMask() || (~Result).isShiftedMask())
3638 return false;
3639
3640 return Diag(TheCall->getBeginLoc(),
3641 diag::err_argument_not_contiguous_bit_field)
3642 << ArgNum << Arg->getSourceRange();
3643}
3644
3645bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3646 CallExpr *TheCall) {
3647 unsigned i = 0, l = 0, u = 0;
3648 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3649 llvm::APSInt Result;
3650
3651 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3652 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3653 << TheCall->getSourceRange();
3654
3655 switch (BuiltinID) {
3656 default: return false;
3657 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3658 case PPC::BI__builtin_altivec_crypto_vshasigmad:
3659 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3660 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3661 case PPC::BI__builtin_altivec_dss:
3662 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3663 case PPC::BI__builtin_tbegin:
3664 case PPC::BI__builtin_tend:
3665 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) ||
3666 SemaFeatureCheck(*this, TheCall, "htm",
3667 diag::err_ppc_builtin_requires_htm);
3668 case PPC::BI__builtin_tsr:
3669 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3670 SemaFeatureCheck(*this, TheCall, "htm",
3671 diag::err_ppc_builtin_requires_htm);
3672 case PPC::BI__builtin_tabortwc:
3673 case PPC::BI__builtin_tabortdc:
3674 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3675 SemaFeatureCheck(*this, TheCall, "htm",
3676 diag::err_ppc_builtin_requires_htm);
3677 case PPC::BI__builtin_tabortwci:
3678 case PPC::BI__builtin_tabortdci:
3679 return SemaFeatureCheck(*this, TheCall, "htm",
3680 diag::err_ppc_builtin_requires_htm) ||
3681 (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3682 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31));
3683 case PPC::BI__builtin_tabort:
3684 case PPC::BI__builtin_tcheck:
3685 case PPC::BI__builtin_treclaim:
3686 case PPC::BI__builtin_trechkpt:
3687 case PPC::BI__builtin_tendall:
3688 case PPC::BI__builtin_tresume:
3689 case PPC::BI__builtin_tsuspend:
3690 case PPC::BI__builtin_get_texasr:
3691 case PPC::BI__builtin_get_texasru:
3692 case PPC::BI__builtin_get_tfhar:
3693 case PPC::BI__builtin_get_tfiar:
3694 case PPC::BI__builtin_set_texasr:
3695 case PPC::BI__builtin_set_texasru:
3696 case PPC::BI__builtin_set_tfhar:
3697 case PPC::BI__builtin_set_tfiar:
3698 case PPC::BI__builtin_ttest:
3699 return SemaFeatureCheck(*this, TheCall, "htm",
3700 diag::err_ppc_builtin_requires_htm);
3701 // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
3702 // __builtin_(un)pack_longdouble are available only if long double uses IBM
3703 // extended double representation.
3704 case PPC::BI__builtin_unpack_longdouble:
3705 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1))
3706 return true;
3707 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3708 case PPC::BI__builtin_pack_longdouble:
3709 if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
3710 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
3711 << "ibmlongdouble";
3712 return false;
3713 case PPC::BI__builtin_altivec_dst:
3714 case PPC::BI__builtin_altivec_dstt:
3715 case PPC::BI__builtin_altivec_dstst:
3716 case PPC::BI__builtin_altivec_dststt:
3717 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3718 case PPC::BI__builtin_vsx_xxpermdi:
3719 case PPC::BI__builtin_vsx_xxsldwi:
3720 return SemaBuiltinVSX(TheCall);
3721 case PPC::BI__builtin_divwe:
3722 case PPC::BI__builtin_divweu:
3723 case PPC::BI__builtin_divde:
3724 case PPC::BI__builtin_divdeu:
3725 return SemaFeatureCheck(*this, TheCall, "extdiv",
3726 diag::err_ppc_builtin_only_on_arch, "7");
3727 case PPC::BI__builtin_bpermd:
3728 return SemaFeatureCheck(*this, TheCall, "bpermd",
3729 diag::err_ppc_builtin_only_on_arch, "7");
3730 case PPC::BI__builtin_unpack_vector_int128:
3731 return SemaFeatureCheck(*this, TheCall, "vsx",
3732 diag::err_ppc_builtin_only_on_arch, "7") ||
3733 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3734 case PPC::BI__builtin_pack_vector_int128:
3735 return SemaFeatureCheck(*this, TheCall, "vsx",
3736 diag::err_ppc_builtin_only_on_arch, "7");
3737 case PPC::BI__builtin_altivec_vgnb:
3738 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3739 case PPC::BI__builtin_altivec_vec_replace_elt:
3740 case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3741 QualType VecTy = TheCall->getArg(0)->getType();
3742 QualType EltTy = TheCall->getArg(1)->getType();
3743 unsigned Width = Context.getIntWidth(EltTy);
3744 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3745 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3746 }
3747 case PPC::BI__builtin_vsx_xxeval:
3748 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3749 case PPC::BI__builtin_altivec_vsldbi:
3750 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3751 case PPC::BI__builtin_altivec_vsrdbi:
3752 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3753 case PPC::BI__builtin_vsx_xxpermx:
3754 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3755 case PPC::BI__builtin_ppc_tw:
3756 case PPC::BI__builtin_ppc_tdw:
3757 return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3758 case PPC::BI__builtin_ppc_cmpeqb:
3759 case PPC::BI__builtin_ppc_setb:
3760 case PPC::BI__builtin_ppc_maddhd:
3761 case PPC::BI__builtin_ppc_maddhdu:
3762 case PPC::BI__builtin_ppc_maddld:
3763 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3764 diag::err_ppc_builtin_only_on_arch, "9");
3765 case PPC::BI__builtin_ppc_cmprb:
3766 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3767 diag::err_ppc_builtin_only_on_arch, "9") ||
3768 SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3769 // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3770 // be a constant that represents a contiguous bit field.
3771 case PPC::BI__builtin_ppc_rlwnm:
3772 return SemaValueIsRunOfOnes(TheCall, 2);
3773 case PPC::BI__builtin_ppc_rlwimi:
3774 case PPC::BI__builtin_ppc_rldimi:
3775 return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3776 SemaValueIsRunOfOnes(TheCall, 3);
3777 case PPC::BI__builtin_ppc_extract_exp:
3778 case PPC::BI__builtin_ppc_extract_sig:
3779 case PPC::BI__builtin_ppc_insert_exp:
3780 return SemaFeatureCheck(*this, TheCall, "power9-vector",
3781 diag::err_ppc_builtin_only_on_arch, "9");
3782 case PPC::BI__builtin_ppc_addex: {
3783 if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3784 diag::err_ppc_builtin_only_on_arch, "9") ||
3785 SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3786 return true;
3787 // Output warning for reserved values 1 to 3.
3788 int ArgValue =
3789 TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3790 if (ArgValue != 0)
3791 Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3792 << ArgValue;
3793 return false;
3794 }
3795 case PPC::BI__builtin_ppc_mtfsb0:
3796 case PPC::BI__builtin_ppc_mtfsb1:
3797 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3798 case PPC::BI__builtin_ppc_mtfsf:
3799 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3800 case PPC::BI__builtin_ppc_mtfsfi:
3801 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3802 SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3803 case PPC::BI__builtin_ppc_alignx:
3804 return SemaBuiltinConstantArgPower2(TheCall, 0);
3805 case PPC::BI__builtin_ppc_rdlam:
3806 return SemaValueIsRunOfOnes(TheCall, 2);
3807 case PPC::BI__builtin_ppc_icbt:
3808 case PPC::BI__builtin_ppc_sthcx:
3809 case PPC::BI__builtin_ppc_stbcx:
3810 case PPC::BI__builtin_ppc_lharx:
3811 case PPC::BI__builtin_ppc_lbarx:
3812 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3813 diag::err_ppc_builtin_only_on_arch, "8");
3814 case PPC::BI__builtin_vsx_ldrmb:
3815 case PPC::BI__builtin_vsx_strmb:
3816 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3817 diag::err_ppc_builtin_only_on_arch, "8") ||
3818 SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3819 case PPC::BI__builtin_altivec_vcntmbb:
3820 case PPC::BI__builtin_altivec_vcntmbh:
3821 case PPC::BI__builtin_altivec_vcntmbw:
3822 case PPC::BI__builtin_altivec_vcntmbd:
3823 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3824 case PPC::BI__builtin_darn:
3825 case PPC::BI__builtin_darn_raw:
3826 case PPC::BI__builtin_darn_32:
3827 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3828 diag::err_ppc_builtin_only_on_arch, "9");
3829 case PPC::BI__builtin_vsx_xxgenpcvbm:
3830 case PPC::BI__builtin_vsx_xxgenpcvhm:
3831 case PPC::BI__builtin_vsx_xxgenpcvwm:
3832 case PPC::BI__builtin_vsx_xxgenpcvdm:
3833 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3834 case PPC::BI__builtin_ppc_compare_exp_uo:
3835 case PPC::BI__builtin_ppc_compare_exp_lt:
3836 case PPC::BI__builtin_ppc_compare_exp_gt:
3837 case PPC::BI__builtin_ppc_compare_exp_eq:
3838 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3839 diag::err_ppc_builtin_only_on_arch, "9") ||
3840 SemaFeatureCheck(*this, TheCall, "vsx",
3841 diag::err_ppc_builtin_requires_vsx);
3842 case PPC::BI__builtin_ppc_test_data_class: {
3843 // Check if the first argument of the __builtin_ppc_test_data_class call is
3844 // valid. The argument must be either a 'float' or a 'double'.
3845 QualType ArgType = TheCall->getArg(0)->getType();
3846 if (ArgType != QualType(Context.FloatTy) &&
3847 ArgType != QualType(Context.DoubleTy))
3848 return Diag(TheCall->getBeginLoc(),
3849 diag::err_ppc_invalid_test_data_class_type);
3850 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3851 diag::err_ppc_builtin_only_on_arch, "9") ||
3852 SemaFeatureCheck(*this, TheCall, "vsx",
3853 diag::err_ppc_builtin_requires_vsx) ||
3854 SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
3855 }
3856 case PPC::BI__builtin_ppc_load8r:
3857 case PPC::BI__builtin_ppc_store8r:
3858 return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
3859 diag::err_ppc_builtin_only_on_arch, "7");
3860#define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \
3861 case PPC::BI__builtin_##Name: \
3862 return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
3863#include "clang/Basic/BuiltinsPPC.def"
3864 }
3865 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3866}
3867
3868// Check if the given type is a non-pointer PPC MMA type. This function is used
3869// in Sema to prevent invalid uses of restricted PPC MMA types.
3870bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3871 if (Type->isPointerType() || Type->isArrayType())
3872 return false;
3873
3874 QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3875#define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3876 if (false
3877#include "clang/Basic/PPCTypes.def"
3878 ) {
3879 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3880 return true;
3881 }
3882 return false;
3883}
3884
3885bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3886 CallExpr *TheCall) {
3887 // position of memory order and scope arguments in the builtin
3888 unsigned OrderIndex, ScopeIndex;
3889 switch (BuiltinID) {
3890 case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3891 case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3892 case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3893 case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3894 OrderIndex = 2;
3895 ScopeIndex = 3;
3896 break;
3897 case AMDGPU::BI__builtin_amdgcn_fence:
3898 OrderIndex = 0;
3899 ScopeIndex = 1;
3900 break;
3901 default:
3902 return false;
3903 }
3904
3905 ExprResult Arg = TheCall->getArg(OrderIndex);
3906 auto ArgExpr = Arg.get();
3907 Expr::EvalResult ArgResult;
3908
3909 if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3910 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3911 << ArgExpr->getType();
3912 auto Ord = ArgResult.Val.getInt().getZExtValue();
3913
3914 // Check validity of memory ordering as per C11 / C++11's memody model.
3915 // Only fence needs check. Atomic dec/inc allow all memory orders.
3916 if (!llvm::isValidAtomicOrderingCABI(Ord))
3917 return Diag(ArgExpr->getBeginLoc(),
3918 diag::warn_atomic_op_has_invalid_memory_order)
3919 << ArgExpr->getSourceRange();
3920 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3921 case llvm::AtomicOrderingCABI::relaxed:
3922 case llvm::AtomicOrderingCABI::consume:
3923 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3924 return Diag(ArgExpr->getBeginLoc(),
3925 diag::warn_atomic_op_has_invalid_memory_order)
3926 << ArgExpr->getSourceRange();
3927 break;
3928 case llvm::AtomicOrderingCABI::acquire:
3929 case llvm::AtomicOrderingCABI::release:
3930 case llvm::AtomicOrderingCABI::acq_rel:
3931 case llvm::AtomicOrderingCABI::seq_cst:
3932 break;
3933 }
3934
3935 Arg = TheCall->getArg(ScopeIndex);
3936 ArgExpr = Arg.get();
3937 Expr::EvalResult ArgResult1;
3938 // Check that sync scope is a constant literal
3939 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3940 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3941 << ArgExpr->getType();
3942
3943 return false;
3944}
3945
3946bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3947 llvm::APSInt Result;
3948
3949 // We can't check the value of a dependent argument.
3950 Expr *Arg = TheCall->getArg(ArgNum);
3951 if (Arg->isTypeDependent() || Arg->isValueDependent())
3952 return false;
3953
3954 // Check constant-ness first.
3955 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3956 return true;
3957
3958 int64_t Val = Result.getSExtValue();
3959 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3960 return false;
3961
3962 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3963 << Arg->getSourceRange();
3964}
3965
3966bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3967 unsigned BuiltinID,
3968 CallExpr *TheCall) {
3969 // CodeGenFunction can also detect this, but this gives a better error
3970 // message.
3971 bool FeatureMissing = false;
3972 SmallVector<StringRef> ReqFeatures;
3973 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3974 Features.split(ReqFeatures, ',');
3975
3976 // Check if each required feature is included
3977 for (StringRef F : ReqFeatures) {
3978 if (TI.hasFeature(F))
3979 continue;
3980
3981 // If the feature is 64bit, alter the string so it will print better in
3982 // the diagnostic.
3983 if (F == "64bit")
3984 F = "RV64";
3985
3986 // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3987 F.consume_front("experimental-");
3988 std::string FeatureStr = F.str();
3989 FeatureStr[0] = std::toupper(FeatureStr[0]);
3990
3991 // Error message
3992 FeatureMissing = true;
3993 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3994 << TheCall->getSourceRange() << StringRef(FeatureStr);
3995 }
3996
3997 if (FeatureMissing)
3998 return true;
3999
4000 switch (BuiltinID) {
4001 case RISCVVector::BI__builtin_rvv_vsetvli:
4002 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
4003 CheckRISCVLMUL(TheCall, 2);
4004 case RISCVVector::BI__builtin_rvv_vsetvlimax:
4005 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
4006 CheckRISCVLMUL(TheCall, 1);
4007 }
4008
4009 return false;
4010}
4011
4012bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
4013 CallExpr *TheCall) {
4014 if (BuiltinID == SystemZ::BI__builtin_tabort) {
4015 Expr *Arg = TheCall->getArg(0);
4016 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
4017 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
4018 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
4019 << Arg->getSourceRange();
4020 }
4021
4022 // For intrinsics which take an immediate value as part of the instruction,
4023 // range check them here.
4024 unsigned i = 0, l = 0, u = 0;
4025 switch (BuiltinID) {
4026 default: return false;
4027 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
4028 case SystemZ::BI__builtin_s390_verimb:
4029 case SystemZ::BI__builtin_s390_verimh:
4030 case SystemZ::BI__builtin_s390_verimf:
4031 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
4032 case SystemZ::BI__builtin_s390_vfaeb:
4033 case SystemZ::BI__builtin_s390_vfaeh:
4034 case SystemZ::BI__builtin_s390_vfaef:
4035 case SystemZ::BI__builtin_s390_vfaebs:
4036 case SystemZ::BI__builtin_s390_vfaehs:
4037 case SystemZ::BI__builtin_s390_vfaefs:
4038 case SystemZ::BI__builtin_s390_vfaezb:
4039 case SystemZ::BI__builtin_s390_vfaezh:
4040 case SystemZ::BI__builtin_s390_vfaezf:
4041 case SystemZ::BI__builtin_s390_vfaezbs:
4042 case SystemZ::BI__builtin_s390_vfaezhs:
4043 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
4044 case SystemZ::BI__builtin_s390_vfisb:
4045 case SystemZ::BI__builtin_s390_vfidb:
4046 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
4047 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
4048 case SystemZ::BI__builtin_s390_vftcisb:
4049 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
4050 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
4051 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
4052 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
4053 case SystemZ::BI__builtin_s390_vstrcb:
4054 case SystemZ::BI__builtin_s390_vstrch:
4055 case SystemZ::BI__builtin_s390_vstrcf:
4056 case SystemZ::BI__builtin_s390_vstrczb:
4057 case SystemZ::BI__builtin_s390_vstrczh:
4058 case SystemZ::BI__builtin_s390_vstrczf:
4059 case SystemZ::BI__builtin_s390_vstrcbs:
4060 case SystemZ::BI__builtin_s390_vstrchs:
4061 case SystemZ::BI__builtin_s390_vstrcfs:
4062 case SystemZ::BI__builtin_s390_vstrczbs:
4063 case SystemZ::BI__builtin_s390_vstrczhs:
4064 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
4065 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
4066 case SystemZ::BI__builtin_s390_vfminsb:
4067 case SystemZ::BI__builtin_s390_vfmaxsb:
4068 case SystemZ::BI__builtin_s390_vfmindb:
4069 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
4070 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
4071 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
4072 case SystemZ::BI__builtin_s390_vclfnhs:
4073 case SystemZ::BI__builtin_s390_vclfnls:
4074 case SystemZ::BI__builtin_s390_vcfn:
4075 case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
4076 case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
4077 }
4078 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
4079}
4080
4081/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
4082/// This checks that the target supports __builtin_cpu_supports and
4083/// that the string argument is constant and valid.
4084static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
4085 CallExpr *TheCall) {
4086 Expr *Arg = TheCall->getArg(0);
4087
4088 // Check if the argument is a string literal.
4089 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4090 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4091 << Arg->getSourceRange();
4092
4093 // Check the contents of the string.
4094 StringRef Feature =
4095 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4096 if (!TI.validateCpuSupports(Feature))
4097 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
4098 << Arg->getSourceRange();
4099 return false;
4100}
4101
4102/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
4103/// This checks that the target supports __builtin_cpu_is and
4104/// that the string argument is constant and valid.
4105static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
4106 Expr *Arg = TheCall->getArg(0);
4107
4108 // Check if the argument is a string literal.
4109 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4110 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4111 << Arg->getSourceRange();
4112
4113 // Check the contents of the string.
4114 StringRef Feature =
4115 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4116 if (!TI.validateCpuIs(Feature))
4117 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
4118 << Arg->getSourceRange();
4119 return false;
4120}
4121
4122// Check if the rounding mode is legal.
4123bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
4124 // Indicates if this instruction has rounding control or just SAE.
4125 bool HasRC = false;
4126
4127 unsigned ArgNum = 0;
4128 switch (BuiltinID) {
4129 default:
4130 return false;
4131 case X86::BI__builtin_ia32_vcvttsd2si32:
4132 case X86::BI__builtin_ia32_vcvttsd2si64:
4133 case X86::BI__builtin_ia32_vcvttsd2usi32:
4134 case X86::BI__builtin_ia32_vcvttsd2usi64:
4135 case X86::BI__builtin_ia32_vcvttss2si32:
4136 case X86::BI__builtin_ia32_vcvttss2si64:
4137 case X86::BI__builtin_ia32_vcvttss2usi32:
4138 case X86::BI__builtin_ia32_vcvttss2usi64:
4139 case X86::BI__builtin_ia32_vcvttsh2si32:
4140 case X86::BI__builtin_ia32_vcvttsh2si64:
4141 case X86::BI__builtin_ia32_vcvttsh2usi32:
4142 case X86::BI__builtin_ia32_vcvttsh2usi64:
4143 ArgNum = 1;
4144 break;
4145 case X86::BI__builtin_ia32_maxpd512:
4146 case X86::BI__builtin_ia32_maxps512:
4147 case X86::BI__builtin_ia32_minpd512:
4148 case X86::BI__builtin_ia32_minps512:
4149 case X86::BI__builtin_ia32_maxph512:
4150 case X86::BI__builtin_ia32_minph512:
4151 ArgNum = 2;
4152 break;
4153 case X86::BI__builtin_ia32_vcvtph2pd512_mask:
4154 case X86::BI__builtin_ia32_vcvtph2psx512_mask:
4155 case X86::BI__builtin_ia32_cvtps2pd512_mask:
4156 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
4157 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
4158 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
4159 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
4160 case X86::BI__builtin_ia32_cvttps2dq512_mask:
4161 case X86::BI__builtin_ia32_cvttps2qq512_mask:
4162 case X86::BI__builtin_ia32_cvttps2udq512_mask:
4163 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
4164 case X86::BI__builtin_ia32_vcvttph2w512_mask:
4165 case X86::BI__builtin_ia32_vcvttph2uw512_mask:
4166 case X86::BI__builtin_ia32_vcvttph2dq512_mask:
4167 case X86::BI__builtin_ia32_vcvttph2udq512_mask:
4168 case X86::BI__builtin_ia32_vcvttph2qq512_mask:
4169 case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
4170 case X86::BI__builtin_ia32_exp2pd_mask:
4171 case X86::BI__builtin_ia32_exp2ps_mask:
4172 case X86::BI__builtin_ia32_getexppd512_mask:
4173 case X86::BI__builtin_ia32_getexpps512_mask:
4174 case X86::BI__builtin_ia32_getexpph512_mask:
4175 case X86::BI__builtin_ia32_rcp28pd_mask:
4176 case X86::BI__builtin_ia32_rcp28ps_mask:
4177 case X86::BI__builtin_ia32_rsqrt28pd_mask:
4178 case X86::BI__builtin_ia32_rsqrt28ps_mask:
4179 case X86::BI__builtin_ia32_vcomisd:
4180 case X86::BI__builtin_ia32_vcomiss:
4181 case X86::BI__builtin_ia32_vcomish:
4182 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
4183 ArgNum = 3;
4184 break;
4185 case X86::BI__builtin_ia32_cmppd512_mask:
4186 case X86::BI__builtin_ia32_cmpps512_mask:
4187 case X86::BI__builtin_ia32_cmpsd_mask:
4188 case X86::BI__builtin_ia32_cmpss_mask:
4189 case X86::BI__builtin_ia32_cmpsh_mask:
4190 case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
4191 case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
4192 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
4193 case X86::BI__builtin_ia32_getexpsd128_round_mask:
4194 case X86::BI__builtin_ia32_getexpss128_round_mask:
4195 case X86::BI__builtin_ia32_getexpsh128_round_mask:
4196 case X86::BI__builtin_ia32_getmantpd512_mask:
4197 case X86::BI__builtin_ia32_getmantps512_mask:
4198 case X86::BI__builtin_ia32_getmantph512_mask:
4199 case X86::BI__builtin_ia32_maxsd_round_mask:
4200 case X86::BI__builtin_ia32_maxss_round_mask:
4201 case X86::BI__builtin_ia32_maxsh_round_mask:
4202 case X86::BI__builtin_ia32_minsd_round_mask:
4203 case X86::BI__builtin_ia32_minss_round_mask:
4204 case X86::BI__builtin_ia32_minsh_round_mask:
4205 case X86::BI__builtin_ia32_rcp28sd_round_mask:
4206 case X86::BI__builtin_ia32_rcp28ss_round_mask:
4207 case X86::BI__builtin_ia32_reducepd512_mask:
4208 case X86::BI__builtin_ia32_reduceps512_mask:
4209 case X86::BI__builtin_ia32_reduceph512_mask:
4210 case X86::BI__builtin_ia32_rndscalepd_mask:
4211 case X86::BI__builtin_ia32_rndscaleps_mask:
4212 case X86::BI__builtin_ia32_rndscaleph_mask:
4213 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
4214 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
4215 ArgNum = 4;
4216 break;
4217 case X86::BI__builtin_ia32_fixupimmpd512_mask:
4218 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4219 case X86::BI__builtin_ia32_fixupimmps512_mask:
4220 case X86::BI__builtin_ia32_fixupimmps512_maskz:
4221 case X86::BI__builtin_ia32_fixupimmsd_mask:
4222 case X86::BI__builtin_ia32_fixupimmsd_maskz:
4223 case X86::BI__builtin_ia32_fixupimmss_mask:
4224 case X86::BI__builtin_ia32_fixupimmss_maskz:
4225 case X86::BI__builtin_ia32_getmantsd_round_mask:
4226 case X86::BI__builtin_ia32_getmantss_round_mask:
4227 case X86::BI__builtin_ia32_getmantsh_round_mask:
4228 case X86::BI__builtin_ia32_rangepd512_mask:
4229 case X86::BI__builtin_ia32_rangeps512_mask:
4230 case X86::BI__builtin_ia32_rangesd128_round_mask:
4231 case X86::BI__builtin_ia32_rangess128_round_mask:
4232 case X86::BI__builtin_ia32_reducesd_mask:
4233 case X86::BI__builtin_ia32_reducess_mask:
4234 case X86::BI__builtin_ia32_reducesh_mask:
4235 case X86::BI__builtin_ia32_rndscalesd_round_mask:
4236 case X86::BI__builtin_ia32_rndscaless_round_mask:
4237 case X86::BI__builtin_ia32_rndscalesh_round_mask:
4238 ArgNum = 5;
4239 break;
4240 case X86::BI__builtin_ia32_vcvtsd2si64:
4241 case X86::BI__builtin_ia32_vcvtsd2si32:
4242 case X86::BI__builtin_ia32_vcvtsd2usi32:
4243 case X86::BI__builtin_ia32_vcvtsd2usi64:
4244 case X86::BI__builtin_ia32_vcvtss2si32:
4245 case X86::BI__builtin_ia32_vcvtss2si64:
4246 case X86::BI__builtin_ia32_vcvtss2usi32:
4247 case X86::BI__builtin_ia32_vcvtss2usi64:
4248 case X86::BI__builtin_ia32_vcvtsh2si32:
4249 case X86::BI__builtin_ia32_vcvtsh2si64:
4250 case X86::BI__builtin_ia32_vcvtsh2usi32:
4251 case X86::BI__builtin_ia32_vcvtsh2usi64:
4252 case X86::BI__builtin_ia32_sqrtpd512:
4253 case X86::BI__builtin_ia32_sqrtps512:
4254 case X86::BI__builtin_ia32_sqrtph512:
4255 ArgNum = 1;
4256 HasRC = true;
4257 break;
4258 case X86::BI__builtin_ia32_addph512:
4259 case X86::BI__builtin_ia32_divph512:
4260 case X86::BI__builtin_ia32_mulph512:
4261 case X86::BI__builtin_ia32_subph512:
4262 case X86::BI__builtin_ia32_addpd512:
4263 case X86::BI__builtin_ia32_addps512:
4264 case X86::BI__builtin_ia32_divpd512:
4265 case X86::BI__builtin_ia32_divps512:
4266 case X86::BI__builtin_ia32_mulpd512:
4267 case X86::BI__builtin_ia32_mulps512:
4268 case X86::BI__builtin_ia32_subpd512:
4269 case X86::BI__builtin_ia32_subps512:
4270 case X86::BI__builtin_ia32_cvtsi2sd64:
4271 case X86::BI__builtin_ia32_cvtsi2ss32:
4272 case X86::BI__builtin_ia32_cvtsi2ss64:
4273 case X86::BI__builtin_ia32_cvtusi2sd64:
4274 case X86::BI__builtin_ia32_cvtusi2ss32:
4275 case X86::BI__builtin_ia32_cvtusi2ss64:
4276 case X86::BI__builtin_ia32_vcvtusi2sh:
4277 case X86::BI__builtin_ia32_vcvtusi642sh:
4278 case X86::BI__builtin_ia32_vcvtsi2sh:
4279 case X86::BI__builtin_ia32_vcvtsi642sh:
4280 ArgNum = 2;
4281 HasRC = true;
4282 break;
4283 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4284 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4285 case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4286 case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4287 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4288 case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4289 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4290 case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4291 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4292 case X86::BI__builtin_ia32_cvtps2dq512_mask:
4293 case X86::BI__builtin_ia32_cvtps2qq512_mask:
4294 case X86::BI__builtin_ia32_cvtps2udq512_mask:
4295 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4296 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4297 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4298 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4299 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4300 case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4301 case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4302 case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4303 case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4304 case X86::BI__builtin_ia32_vcvtph2w512_mask:
4305 case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4306 case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4307 case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4308 case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4309 case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4310 case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4311 case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4312 ArgNum = 3;
4313 HasRC = true;
4314 break;
4315 case X86::BI__builtin_ia32_addsh_round_mask:
4316 case X86::BI__builtin_ia32_addss_round_mask:
4317 case X86::BI__builtin_ia32_addsd_round_mask:
4318 case X86::BI__builtin_ia32_divsh_round_mask:
4319 case X86::BI__builtin_ia32_divss_round_mask:
4320 case X86::BI__builtin_ia32_divsd_round_mask:
4321 case X86::BI__builtin_ia32_mulsh_round_mask:
4322 case X86::BI__builtin_ia32_mulss_round_mask:
4323 case X86::BI__builtin_ia32_mulsd_round_mask:
4324 case X86::BI__builtin_ia32_subsh_round_mask:
4325 case X86::BI__builtin_ia32_subss_round_mask:
4326 case X86::BI__builtin_ia32_subsd_round_mask:
4327 case X86::BI__builtin_ia32_scalefph512_mask:
4328 case X86::BI__builtin_ia32_scalefpd512_mask:
4329 case X86::BI__builtin_ia32_scalefps512_mask:
4330 case X86::BI__builtin_ia32_scalefsd_round_mask:
4331 case X86::BI__builtin_ia32_scalefss_round_mask:
4332 case X86::BI__builtin_ia32_scalefsh_round_mask:
4333 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4334 case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4335 case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4336 case X86::BI__builtin_ia32_sqrtsd_round_mask:
4337 case X86::BI__builtin_ia32_sqrtss_round_mask:
4338 case X86::BI__builtin_ia32_sqrtsh_round_mask:
4339 case X86::BI__builtin_ia32_vfmaddsd3_mask:
4340 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4341 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4342 case X86::BI__builtin_ia32_vfmaddss3_mask:
4343 case X86::BI__builtin_ia32_vfmaddss3_maskz:
4344 case X86::BI__builtin_ia32_vfmaddss3_mask3:
4345 case X86::BI__builtin_ia32_vfmaddsh3_mask:
4346 case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4347 case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4348 case X86::BI__builtin_ia32_vfmaddpd512_mask:
4349 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4350 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4351 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4352 case X86::BI__builtin_ia32_vfmaddps512_mask:
4353 case X86::BI__builtin_ia32_vfmaddps512_maskz:
4354 case X86::BI__builtin_ia32_vfmaddps512_mask3:
4355 case X86::BI__builtin_ia32_vfmsubps512_mask3:
4356 case X86::BI__builtin_ia32_vfmaddph512_mask:
4357 case X86::BI__builtin_ia32_vfmaddph512_maskz:
4358 case X86::BI__builtin_ia32_vfmaddph512_mask3:
4359 case X86::BI__builtin_ia32_vfmsubph512_mask3:
4360 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4361 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4362 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4363 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4364 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4365 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4366 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4367 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4368 case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4369 case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4370 case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4371 case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4372 case X86::BI__builtin_ia32_vfmaddcsh_mask:
4373 case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
4374 case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
4375 case X86::BI__builtin_ia32_vfmaddcph512_mask:
4376 case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4377 case X86::BI__builtin_ia32_vfmaddcph512_mask3:
4378 case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4379 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
4380 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
4381 case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4382 case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4383 case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
4384 case X86::BI__builtin_ia32_vfmulcsh_mask:
4385 case X86::BI__builtin_ia32_vfmulcph512_mask:
4386 case X86::BI__builtin_ia32_vfcmulcsh_mask:
4387 case X86::BI__builtin_ia32_vfcmulcph512_mask:
4388 ArgNum = 4;
4389 HasRC = true;
4390 break;
4391 }
4392
4393 llvm::APSInt Result;
4394
4395 // We can't check the value of a dependent argument.
4396 Expr *Arg = TheCall->getArg(ArgNum);
4397 if (Arg->isTypeDependent() || Arg->isValueDependent())
4398 return false;
4399
4400 // Check constant-ness first.
4401 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4402 return true;
4403
4404 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4405 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4406 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4407 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4408 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4409 Result == 8/*ROUND_NO_EXC*/ ||
4410 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4411 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4412 return false;
4413
4414 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4415 << Arg->getSourceRange();
4416}
4417
4418// Check if the gather/scatter scale is legal.
4419bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4420 CallExpr *TheCall) {
4421 unsigned ArgNum = 0;
4422 switch (BuiltinID) {
4423 default:
4424 return false;
4425 case X86::BI__builtin_ia32_gatherpfdpd:
4426 case X86::BI__builtin_ia32_gatherpfdps:
4427 case X86::BI__builtin_ia32_gatherpfqpd:
4428 case X86::BI__builtin_ia32_gatherpfqps:
4429 case X86::BI__builtin_ia32_scatterpfdpd:
4430 case X86::BI__builtin_ia32_scatterpfdps:
4431 case X86::BI__builtin_ia32_scatterpfqpd:
4432 case X86::BI__builtin_ia32_scatterpfqps:
4433 ArgNum = 3;
4434 break;
4435 case X86::BI__builtin_ia32_gatherd_pd:
4436 case X86::BI__builtin_ia32_gatherd_pd256:
4437 case X86::BI__builtin_ia32_gatherq_pd:
4438 case X86::BI__builtin_ia32_gatherq_pd256:
4439 case X86::BI__builtin_ia32_gatherd_ps:
4440 case X86::BI__builtin_ia32_gatherd_ps256:
4441 case X86::BI__builtin_ia32_gatherq_ps:
4442 case X86::BI__builtin_ia32_gatherq_ps256:
4443 case X86::BI__builtin_ia32_gatherd_q:
4444 case X86::BI__builtin_ia32_gatherd_q256:
4445 case X86::BI__builtin_ia32_gatherq_q:
4446 case X86::BI__builtin_ia32_gatherq_q256:
4447 case X86::BI__builtin_ia32_gatherd_d:
4448 case X86::BI__builtin_ia32_gatherd_d256:
4449 case X86::BI__builtin_ia32_gatherq_d:
4450 case X86::BI__builtin_ia32_gatherq_d256:
4451 case X86::BI__builtin_ia32_gather3div2df:
4452 case X86::BI__builtin_ia32_gather3div2di:
4453 case X86::BI__builtin_ia32_gather3div4df:
4454 case X86::BI__builtin_ia32_gather3div4di:
4455 case X86::BI__builtin_ia32_gather3div4sf:
4456 case X86::BI__builtin_ia32_gather3div4si:
4457 case X86::BI__builtin_ia32_gather3div8sf:
4458 case X86::BI__builtin_ia32_gather3div8si:
4459 case X86::BI__builtin_ia32_gather3siv2df:
4460 case X86::BI__builtin_ia32_gather3siv2di:
4461 case X86::BI__builtin_ia32_gather3siv4df:
4462 case X86::BI__builtin_ia32_gather3siv4di:
4463 case X86::BI__builtin_ia32_gather3siv4sf:
4464 case X86::BI__builtin_ia32_gather3siv4si:
4465 case X86::BI__builtin_ia32_gather3siv8sf:
4466 case X86::BI__builtin_ia32_gather3siv8si:
4467 case X86::BI__builtin_ia32_gathersiv8df:
4468 case X86::BI__builtin_ia32_gathersiv16sf:
4469 case X86::BI__builtin_ia32_gatherdiv8df:
4470 case X86::BI__builtin_ia32_gatherdiv16sf:
4471 case X86::BI__builtin_ia32_gathersiv8di:
4472 case X86::BI__builtin_ia32_gathersiv16si:
4473 case X86::BI__builtin_ia32_gatherdiv8di:
4474 case X86::BI__builtin_ia32_gatherdiv16si:
4475 case X86::BI__builtin_ia32_scatterdiv2df:
4476 case X86::BI__builtin_ia32_scatterdiv2di:
4477 case X86::BI__builtin_ia32_scatterdiv4df:
4478 case X86::BI__builtin_ia32_scatterdiv4di:
4479 case X86::BI__builtin_ia32_scatterdiv4sf:
4480 case X86::BI__builtin_ia32_scatterdiv4si:
4481 case X86::BI__builtin_ia32_scatterdiv8sf:
4482 case X86::BI__builtin_ia32_scatterdiv8si:
4483 case X86::BI__builtin_ia32_scattersiv2df:
4484 case X86::BI__builtin_ia32_scattersiv2di:
4485 case X86::BI__builtin_ia32_scattersiv4df:
4486 case X86::BI__builtin_ia32_scattersiv4di:
4487 case X86::BI__builtin_ia32_scattersiv4sf:
4488 case X86::BI__builtin_ia32_scattersiv4si:
4489 case X86::BI__builtin_ia32_scattersiv8sf:
4490 case X86::BI__builtin_ia32_scattersiv8si:
4491 case X86::BI__builtin_ia32_scattersiv8df:
4492 case X86::BI__builtin_ia32_scattersiv16sf:
4493 case X86::BI__builtin_ia32_scatterdiv8df:
4494 case X86::BI__builtin_ia32_scatterdiv16sf:
4495 case X86::BI__builtin_ia32_scattersiv8di:
4496 case X86::BI__builtin_ia32_scattersiv16si:
4497 case X86::BI__builtin_ia32_scatterdiv8di:
4498 case X86::BI__builtin_ia32_scatterdiv16si:
4499 ArgNum = 4;
4500 break;
4501 }
4502
4503 llvm::APSInt Result;
4504
4505 // We can't check the value of a dependent argument.
4506 Expr *Arg = TheCall->getArg(ArgNum);
4507 if (Arg->isTypeDependent() || Arg->isValueDependent())
4508 return false;
4509
4510 // Check constant-ness first.
4511 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4512 return true;
4513
4514 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4515 return false;
4516
4517 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4518 << Arg->getSourceRange();
4519}
4520
4521enum { TileRegLow = 0, TileRegHigh = 7 };
4522
4523bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4524 ArrayRef<int> ArgNums) {
4525 for (int ArgNum : ArgNums) {
4526 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4527 return true;
4528 }
4529 return false;
4530}
4531
4532bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4533 ArrayRef<int> ArgNums) {
4534 // Because the max number of tile register is TileRegHigh + 1, so here we use
4535 // each bit to represent the usage of them in bitset.
4536 std::bitset<TileRegHigh + 1> ArgValues;
4537 for (int ArgNum : ArgNums) {
4538 Expr *Arg = TheCall->getArg(ArgNum);
4539 if (Arg->isTypeDependent() || Arg->isValueDependent())
4540 continue;
4541
4542 llvm::APSInt Result;
4543 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4544 return true;
4545 int ArgExtValue = Result.getExtValue();
4546 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&(static_cast <bool> ((ArgExtValue >= TileRegLow || ArgExtValue
<= TileRegHigh) && "Incorrect tile register num."
) ? void (0) : __assert_fail ("(ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && \"Incorrect tile register num.\""
, "clang/lib/Sema/SemaChecking.cpp", 4547, __extension__ __PRETTY_FUNCTION__
))
4547 "Incorrect tile register num.")(static_cast <bool> ((ArgExtValue >= TileRegLow || ArgExtValue
<= TileRegHigh) && "Incorrect tile register num."
) ? void (0) : __assert_fail ("(ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && \"Incorrect tile register num.\""
, "clang/lib/Sema/SemaChecking.cpp", 4547, __extension__ __PRETTY_FUNCTION__
))
;
4548 if (ArgValues.test(ArgExtValue))
4549 return Diag(TheCall->getBeginLoc(),
4550 diag::err_x86_builtin_tile_arg_duplicate)
4551 << TheCall->getArg(ArgNum)->getSourceRange();
4552 ArgValues.set(ArgExtValue);
4553 }
4554 return false;
4555}
4556
4557bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4558 ArrayRef<int> ArgNums) {
4559 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4560 CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4561}
4562
4563bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4564 switch (BuiltinID) {
4565 default:
4566 return false;
4567 case X86::BI__builtin_ia32_tileloadd64:
4568 case X86::BI__builtin_ia32_tileloaddt164:
4569 case X86::BI__builtin_ia32_tilestored64:
4570 case X86::BI__builtin_ia32_tilezero:
4571 return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4572 case X86::BI__builtin_ia32_tdpbssd:
4573 case X86::BI__builtin_ia32_tdpbsud:
4574 case X86::BI__builtin_ia32_tdpbusd:
4575 case X86::BI__builtin_ia32_tdpbuud:
4576 case X86::BI__builtin_ia32_tdpbf16ps:
4577 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4578 }
4579}
4580static bool isX86_32Builtin(unsigned BuiltinID) {
4581 // These builtins only work on x86-32 targets.
4582 switch (BuiltinID) {
4583 case X86::BI__builtin_ia32_readeflags_u32:
4584 case X86::BI__builtin_ia32_writeeflags_u32:
4585 return true;
4586 }
4587
4588 return false;
4589}
4590
4591bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4592 CallExpr *TheCall) {
4593 if (BuiltinID == X86::BI__builtin_cpu_supports)
4594 return SemaBuiltinCpuSupports(*this, TI, TheCall);
4595
4596 if (BuiltinID == X86::BI__builtin_cpu_is)
4597 return SemaBuiltinCpuIs(*this, TI, TheCall);
4598
4599 // Check for 32-bit only builtins on a 64-bit target.
4600 const llvm::Triple &TT = TI.getTriple();
4601 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4602 return Diag(TheCall->getCallee()->getBeginLoc(),
4603 diag::err_32_bit_builtin_64_bit_tgt);
4604
4605 // If the intrinsic has rounding or SAE make sure its valid.
4606 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4607 return true;
4608
4609 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4610 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4611 return true;
4612
4613 // If the intrinsic has a tile arguments, make sure they are valid.
4614 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4615 return true;
4616
4617 // For intrinsics which take an immediate value as part of the instruction,
4618 // range check them here.
4619 int i = 0, l = 0, u = 0;
4620 switch (BuiltinID) {
4621 default:
4622 return false;
4623 case X86::BI__builtin_ia32_vec_ext_v2si:
4624 case X86::BI__builtin_ia32_vec_ext_v2di:
4625 case X86::BI__builtin_ia32_vextractf128_pd256:
4626 case X86::BI__builtin_ia32_vextractf128_ps256:
4627 case X86::BI__builtin_ia32_vextractf128_si256:
4628 case X86::BI__builtin_ia32_extract128i256:
4629 case X86::BI__builtin_ia32_extractf64x4_mask:
4630 case X86::BI__builtin_ia32_extracti64x4_mask:
4631 case X86::BI__builtin_ia32_extractf32x8_mask:
4632 case X86::BI__builtin_ia32_extracti32x8_mask:
4633 case X86::BI__builtin_ia32_extractf64x2_256_mask:
4634 case X86::BI__builtin_ia32_extracti64x2_256_mask:
4635 case X86::BI__builtin_ia32_extractf32x4_256_mask:
4636 case X86::BI__builtin_ia32_extracti32x4_256_mask:
4637 i = 1; l = 0; u = 1;
4638 break;
4639 case X86::BI__builtin_ia32_vec_set_v2di:
4640 case X86::BI__builtin_ia32_vinsertf128_pd256:
4641 case X86::BI__builtin_ia32_vinsertf128_ps256:
4642 case X86::BI__builtin_ia32_vinsertf128_si256:
4643 case X86::BI__builtin_ia32_insert128i256:
4644 case X86::BI__builtin_ia32_insertf32x8:
4645 case X86::BI__builtin_ia32_inserti32x8:
4646 case X86::BI__builtin_ia32_insertf64x4:
4647 case X86::BI__builtin_ia32_inserti64x4:
4648 case X86::BI__builtin_ia32_insertf64x2_256:
4649 case X86::BI__builtin_ia32_inserti64x2_256:
4650 case X86::BI__builtin_ia32_insertf32x4_256:
4651 case X86::BI__builtin_ia32_inserti32x4_256:
4652 i = 2; l = 0; u = 1;
4653 break;
4654 case X86::BI__builtin_ia32_vpermilpd:
4655 case X86::BI__builtin_ia32_vec_ext_v4hi:
4656 case X86::BI__builtin_ia32_vec_ext_v4si:
4657 case X86::BI__builtin_ia32_vec_ext_v4sf:
4658 case X86::BI__builtin_ia32_vec_ext_v4di:
4659 case X86::BI__builtin_ia32_extractf32x4_mask:
4660 case X86::BI__builtin_ia32_extracti32x4_mask:
4661 case X86::BI__builtin_ia32_extractf64x2_512_mask:
4662 case X86::BI__builtin_ia32_extracti64x2_512_mask:
4663 i = 1; l = 0; u = 3;
4664 break;
4665 case X86::BI_mm_prefetch:
4666 case X86::BI__builtin_ia32_vec_ext_v8hi:
4667 case X86::BI__builtin_ia32_vec_ext_v8si:
4668 i = 1; l = 0; u = 7;
4669 break;
4670 case X86::BI__builtin_ia32_sha1rnds4:
4671 case X86::BI__builtin_ia32_blendpd:
4672 case X86::BI__builtin_ia32_shufpd:
4673 case X86::BI__builtin_ia32_vec_set_v4hi:
4674 case X86::BI__builtin_ia32_vec_set_v4si:
4675 case X86::BI__builtin_ia32_vec_set_v4di:
4676 case X86::BI__builtin_ia32_shuf_f32x4_256:
4677 case X86::BI__builtin_ia32_shuf_f64x2_256:
4678 case X86::BI__builtin_ia32_shuf_i32x4_256:
4679 case X86::BI__builtin_ia32_shuf_i64x2_256:
4680 case X86::BI__builtin_ia32_insertf64x2_512:
4681 case X86::BI__builtin_ia32_inserti64x2_512:
4682 case X86::BI__builtin_ia32_insertf32x4:
4683 case X86::BI__builtin_ia32_inserti32x4:
4684 i = 2; l = 0; u = 3;
4685 break;
4686 case X86::BI__builtin_ia32_vpermil2pd:
4687 case X86::BI__builtin_ia32_vpermil2pd256:
4688 case X86::BI__builtin_ia32_vpermil2ps:
4689 case X86::BI__builtin_ia32_vpermil2ps256:
4690 i = 3; l = 0; u = 3;
4691 break;
4692 case X86::BI__builtin_ia32_cmpb128_mask:
4693 case X86::BI__builtin_ia32_cmpw128_mask:
4694 case X86::BI__builtin_ia32_cmpd128_mask:
4695 case X86::BI__builtin_ia32_cmpq128_mask:
4696 case X86::BI__builtin_ia32_cmpb256_mask:
4697 case X86::BI__builtin_ia32_cmpw256_mask:
4698 case X86::BI__builtin_ia32_cmpd256_mask:
4699 case X86::BI__builtin_ia32_cmpq256_mask:
4700 case X86::BI__builtin_ia32_cmpb512_mask:
4701 case X86::BI__builtin_ia32_cmpw512_mask:
4702 case X86::BI__builtin_ia32_cmpd512_mask:
4703 case X86::BI__builtin_ia32_cmpq512_mask:
4704 case X86::BI__builtin_ia32_ucmpb128_mask:
4705 case X86::BI__builtin_ia32_ucmpw128_mask:
4706 case X86::BI__builtin_ia32_ucmpd128_mask:
4707 case X86::BI__builtin_ia32_ucmpq128_mask:
4708 case X86::BI__builtin_ia32_ucmpb256_mask:
4709 case X86::BI__builtin_ia32_ucmpw256_mask:
4710 case X86::BI__builtin_ia32_ucmpd256_mask:
4711 case X86::BI__builtin_ia32_ucmpq256_mask:
4712 case X86::BI__builtin_ia32_ucmpb512_mask:
4713 case X86::BI__builtin_ia32_ucmpw512_mask:
4714 case X86::BI__builtin_ia32_ucmpd512_mask:
4715 case X86::BI__builtin_ia32_ucmpq512_mask:
4716 case X86::BI__builtin_ia32_vpcomub:
4717 case X86::BI__builtin_ia32_vpcomuw:
4718 case X86::BI__builtin_ia32_vpcomud:
4719 case X86::BI__builtin_ia32_vpcomuq:
4720 case X86::BI__builtin_ia32_vpcomb:
4721 case X86::BI__builtin_ia32_vpcomw:
4722 case X86::BI__builtin_ia32_vpcomd:
4723 case X86::BI__builtin_ia32_vpcomq:
4724 case X86::BI__builtin_ia32_vec_set_v8hi:
4725 case X86::BI__builtin_ia32_vec_set_v8si:
4726 i = 2; l = 0; u = 7;
4727 break;
4728 case X86::BI__builtin_ia32_vpermilpd256:
4729 case X86::BI__builtin_ia32_roundps:
4730 case X86::BI__builtin_ia32_roundpd:
4731 case X86::BI__builtin_ia32_roundps256:
4732 case X86::BI__builtin_ia32_roundpd256:
4733 case X86::BI__builtin_ia32_getmantpd128_mask:
4734 case X86::BI__builtin_ia32_getmantpd256_mask:
4735 case X86::BI__builtin_ia32_getmantps128_mask:
4736 case X86::BI__builtin_ia32_getmantps256_mask:
4737 case X86::BI__builtin_ia32_getmantpd512_mask:
4738 case X86::BI__builtin_ia32_getmantps512_mask:
4739 case X86::BI__builtin_ia32_getmantph128_mask:
4740 case X86::BI__builtin_ia32_getmantph256_mask:
4741 case X86::BI__builtin_ia32_getmantph512_mask:
4742 case X86::BI__builtin_ia32_vec_ext_v16qi:
4743 case X86::BI__builtin_ia32_vec_ext_v16hi:
4744 i = 1; l = 0; u = 15;
4745 break;
4746 case X86::BI__builtin_ia32_pblendd128:
4747 case X86::BI__builtin_ia32_blendps:
4748 case X86::BI__builtin_ia32_blendpd256:
4749 case X86::BI__builtin_ia32_shufpd256:
4750 case X86::BI__builtin_ia32_roundss:
4751 case X86::BI__builtin_ia32_roundsd:
4752 case X86::BI__builtin_ia32_rangepd128_mask:
4753 case X86::BI__builtin_ia32_rangepd256_mask:
4754 case X86::BI__builtin_ia32_rangepd512_mask:
4755 case X86::BI__builtin_ia32_rangeps128_mask:
4756 case X86::BI__builtin_ia32_rangeps256_mask:
4757 case X86::BI__builtin_ia32_rangeps512_mask:
4758 case X86::BI__builtin_ia32_getmantsd_round_mask:
4759 case X86::BI__builtin_ia32_getmantss_round_mask:
4760 case X86::BI__builtin_ia32_getmantsh_round_mask:
4761 case X86::BI__builtin_ia32_vec_set_v16qi:
4762 case X86::BI__builtin_ia32_vec_set_v16hi:
4763 i = 2; l = 0; u = 15;
4764 break;
4765 case X86::BI__builtin_ia32_vec_ext_v32qi:
4766 i = 1; l = 0; u = 31;
4767 break;
4768 case X86::BI__builtin_ia32_cmpps:
4769 case X86::BI__builtin_ia32_cmpss:
4770 case X86::BI__builtin_ia32_cmppd:
4771 case X86::BI__builtin_ia32_cmpsd:
4772 case X86::BI__builtin_ia32_cmpps256:
4773 case X86::BI__builtin_ia32_cmppd256:
4774 case X86::BI__builtin_ia32_cmpps128_mask:
4775 case X86::BI__builtin_ia32_cmppd128_mask:
4776 case X86::BI__builtin_ia32_cmpps256_mask:
4777 case X86::BI__builtin_ia32_cmppd256_mask:
4778 case X86::BI__builtin_ia32_cmpps512_mask:
4779 case X86::BI__builtin_ia32_cmppd512_mask:
4780 case X86::BI__builtin_ia32_cmpsd_mask:
4781 case X86::BI__builtin_ia32_cmpss_mask:
4782 case X86::BI__builtin_ia32_vec_set_v32qi:
4783 i = 2; l = 0; u = 31;
4784 break;
4785 case X86::BI__builtin_ia32_permdf256:
4786 case X86::BI__builtin_ia32_permdi256:
4787 case X86::BI__builtin_ia32_permdf512:
4788 case X86::BI__builtin_ia32_permdi512:
4789 case X86::BI__builtin_ia32_vpermilps:
4790 case X86::BI__builtin_ia32_vpermilps256:
4791 case X86::BI__builtin_ia32_vpermilpd512:
4792 case X86::BI__builtin_ia32_vpermilps512:
4793 case X86::BI__builtin_ia32_pshufd:
4794 case X86::BI__builtin_ia32_pshufd256:
4795 case X86::BI__builtin_ia32_pshufd512:
4796 case X86::BI__builtin_ia32_pshufhw:
4797 case X86::BI__builtin_ia32_pshufhw256:
4798 case X86::BI__builtin_ia32_pshufhw512:
4799 case X86::BI__builtin_ia32_pshuflw:
4800 case X86::BI__builtin_ia32_pshuflw256:
4801 case X86::BI__builtin_ia32_pshuflw512:
4802 case X86::BI__builtin_ia32_vcvtps2ph:
4803 case X86::BI__builtin_ia32_vcvtps2ph_mask:
4804 case X86::BI__builtin_ia32_vcvtps2ph256:
4805 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4806 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4807 case X86::BI__builtin_ia32_rndscaleps_128_mask:
4808 case X86::BI__builtin_ia32_rndscalepd_128_mask:
4809 case X86::BI__builtin_ia32_rndscaleps_256_mask:
4810 case X86::BI__builtin_ia32_rndscalepd_256_mask:
4811 case X86::BI__builtin_ia32_rndscaleps_mask:
4812 case X86::BI__builtin_ia32_rndscalepd_mask:
4813 case X86::BI__builtin_ia32_rndscaleph_mask:
4814 case X86::BI__builtin_ia32_reducepd128_mask:
4815 case X86::BI__builtin_ia32_reducepd256_mask:
4816 case X86::BI__builtin_ia32_reducepd512_mask:
4817 case X86::BI__builtin_ia32_reduceps128_mask:
4818 case X86::BI__builtin_ia32_reduceps256_mask:
4819 case X86::BI__builtin_ia32_reduceps512_mask:
4820 case X86::BI__builtin_ia32_reduceph128_mask:
4821 case X86::BI__builtin_ia32_reduceph256_mask:
4822 case X86::BI__builtin_ia32_reduceph512_mask:
4823 case X86::BI__builtin_ia32_prold512:
4824 case X86::BI__builtin_ia32_prolq512:
4825 case X86::BI__builtin_ia32_prold128:
4826 case X86::BI__builtin_ia32_prold256:
4827 case X86::BI__builtin_ia32_prolq128:
4828 case X86::BI__builtin_ia32_prolq256:
4829 case X86::BI__builtin_ia32_prord512:
4830 case X86::BI__builtin_ia32_prorq512:
4831 case X86::BI__builtin_ia32_prord128:
4832 case X86::BI__builtin_ia32_prord256:
4833 case X86::BI__builtin_ia32_prorq128:
4834 case X86::BI__builtin_ia32_prorq256:
4835 case X86::BI__builtin_ia32_fpclasspd128_mask:
4836 case X86::BI__builtin_ia32_fpclasspd256_mask:
4837 case X86::BI__builtin_ia32_fpclassps128_mask:
4838 case X86::BI__builtin_ia32_fpclassps256_mask:
4839 case X86::BI__builtin_ia32_fpclassps512_mask:
4840 case X86::BI__builtin_ia32_fpclasspd512_mask:
4841 case X86::BI__builtin_ia32_fpclassph128_mask:
4842 case X86::BI__builtin_ia32_fpclassph256_mask:
4843 case X86::BI__builtin_ia32_fpclassph512_mask:
4844 case X86::BI__builtin_ia32_fpclasssd_mask:
4845 case X86::BI__builtin_ia32_fpclassss_mask:
4846 case X86::BI__builtin_ia32_fpclasssh_mask:
4847 case X86::BI__builtin_ia32_pslldqi128_byteshift:
4848 case X86::BI__builtin_ia32_pslldqi256_byteshift:
4849 case X86::BI__builtin_ia32_pslldqi512_byteshift:
4850 case X86::BI__builtin_ia32_psrldqi128_byteshift:
4851 case X86::BI__builtin_ia32_psrldqi256_byteshift:
4852 case X86::BI__builtin_ia32_psrldqi512_byteshift:
4853 case X86::BI__builtin_ia32_kshiftliqi:
4854 case X86::BI__builtin_ia32_kshiftlihi:
4855 case X86::BI__builtin_ia32_kshiftlisi:
4856 case X86::BI__builtin_ia32_kshiftlidi:
4857 case X86::BI__builtin_ia32_kshiftriqi:
4858 case X86::BI__builtin_ia32_kshiftrihi:
4859 case X86::BI__builtin_ia32_kshiftrisi:
4860 case X86::BI__builtin_ia32_kshiftridi:
4861 i = 1; l = 0; u = 255;
4862 break;
4863 case X86::BI__builtin_ia32_vperm2f128_pd256:
4864 case X86::BI__builtin_ia32_vperm2f128_ps256:
4865 case X86::BI__builtin_ia32_vperm2f128_si256:
4866 case X86::BI__builtin_ia32_permti256:
4867 case X86::BI__builtin_ia32_pblendw128:
4868 case X86::BI__builtin_ia32_pblendw256:
4869 case X86::BI__builtin_ia32_blendps256:
4870 case X86::BI__builtin_ia32_pblendd256:
4871 case X86::BI__builtin_ia32_palignr128:
4872 case X86::BI__builtin_ia32_palignr256:
4873 case X86::BI__builtin_ia32_palignr512:
4874 case X86::BI__builtin_ia32_alignq512:
4875 case X86::BI__builtin_ia32_alignd512:
4876 case X86::BI__builtin_ia32_alignd128:
4877 case X86::BI__builtin_ia32_alignd256:
4878 case X86::BI__builtin_ia32_alignq128:
4879 case X86::BI__builtin_ia32_alignq256:
4880 case X86::BI__builtin_ia32_vcomisd:
4881 case X86::BI__builtin_ia32_vcomiss:
4882 case X86::BI__builtin_ia32_shuf_f32x4:
4883 case X86::BI__builtin_ia32_shuf_f64x2:
4884 case X86::BI__builtin_ia32_shuf_i32x4:
4885 case X86::BI__builtin_ia32_shuf_i64x2:
4886 case X86::BI__builtin_ia32_shufpd512:
4887 case X86::BI__builtin_ia32_shufps:
4888 case X86::BI__builtin_ia32_shufps256:
4889 case X86::BI__builtin_ia32_shufps512:
4890 case X86::BI__builtin_ia32_dbpsadbw128:
4891 case X86::BI__builtin_ia32_dbpsadbw256:
4892 case X86::BI__builtin_ia32_dbpsadbw512:
4893 case X86::BI__builtin_ia32_vpshldd128:
4894 case X86::BI__builtin_ia32_vpshldd256:
4895 case X86::BI__builtin_ia32_vpshldd512:
4896 case X86::BI__builtin_ia32_vpshldq128:
4897 case X86::BI__builtin_ia32_vpshldq256:
4898 case X86::BI__builtin_ia32_vpshldq512:
4899 case X86::BI__builtin_ia32_vpshldw128:
4900 case X86::BI__builtin_ia32_vpshldw256:
4901 case X86::BI__builtin_ia32_vpshldw512:
4902 case X86::BI__builtin_ia32_vpshrdd128:
4903 case X86::BI__builtin_ia32_vpshrdd256:
4904 case X86::BI__builtin_ia32_vpshrdd512:
4905 case X86::BI__builtin_ia32_vpshrdq128:
4906 case X86::BI__builtin_ia32_vpshrdq256:
4907 case X86::BI__builtin_ia32_vpshrdq512:
4908 case X86::BI__builtin_ia32_vpshrdw128:
4909 case X86::BI__builtin_ia32_vpshrdw256:
4910 case X86::BI__builtin_ia32_vpshrdw512:
4911 i = 2; l = 0; u = 255;
4912 break;
4913 case X86::BI__builtin_ia32_fixupimmpd512_mask:
4914 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4915 case X86::BI__builtin_ia32_fixupimmps512_mask:
4916 case X86::BI__builtin_ia32_fixupimmps512_maskz:
4917 case X86::BI__builtin_ia32_fixupimmsd_mask:
4918 case X86::BI__builtin_ia32_fixupimmsd_maskz:
4919 case X86::BI__builtin_ia32_fixupimmss_mask:
4920 case X86::BI__builtin_ia32_fixupimmss_maskz:
4921 case X86::BI__builtin_ia32_fixupimmpd128_mask:
4922 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4923 case X86::BI__builtin_ia32_fixupimmpd256_mask:
4924 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4925 case X86::BI__builtin_ia32_fixupimmps128_mask:
4926 case X86::BI__builtin_ia32_fixupimmps128_maskz:
4927 case X86::BI__builtin_ia32_fixupimmps256_mask:
4928 case X86::BI__builtin_ia32_fixupimmps256_maskz:
4929 case X86::BI__builtin_ia32_pternlogd512_mask:
4930 case X86::BI__builtin_ia32_pternlogd512_maskz:
4931 case X86::BI__builtin_ia32_pternlogq512_mask:
4932 case X86::BI__builtin_ia32_pternlogq512_maskz:
4933 case X86::BI__builtin_ia32_pternlogd128_mask:
4934 case X86::BI__builtin_ia32_pternlogd128_maskz:
4935 case X86::BI__builtin_ia32_pternlogd256_mask:
4936 case X86::BI__builtin_ia32_pternlogd256_maskz:
4937 case X86::BI__builtin_ia32_pternlogq128_mask:
4938 case X86::BI__builtin_ia32_pternlogq128_maskz:
4939 case X86::BI__builtin_ia32_pternlogq256_mask:
4940 case X86::BI__builtin_ia32_pternlogq256_maskz:
4941 i = 3; l = 0; u = 255;
4942 break;
4943 case X86::BI__builtin_ia32_gatherpfdpd:
4944 case X86::BI__builtin_ia32_gatherpfdps:
4945 case X86::BI__builtin_ia32_gatherpfqpd:
4946 case X86::BI__builtin_ia32_gatherpfqps:
4947 case X86::BI__builtin_ia32_scatterpfdpd:
4948 case X86::BI__builtin_ia32_scatterpfdps:
4949 case X86::BI__builtin_ia32_scatterpfqpd:
4950 case X86::BI__builtin_ia32_scatterpfqps:
4951 i = 4; l = 2; u = 3;
4952 break;
4953 case X86::BI__builtin_ia32_reducesd_mask:
4954 case X86::BI__builtin_ia32_reducess_mask:
4955 case X86::BI__builtin_ia32_rndscalesd_round_mask:
4956 case X86::BI__builtin_ia32_rndscaless_round_mask:
4957 case X86::BI__builtin_ia32_rndscalesh_round_mask:
4958 case X86::BI__builtin_ia32_reducesh_mask:
4959 i = 4; l = 0; u = 255;
4960 break;
4961 }
4962
4963 // Note that we don't force a hard error on the range check here, allowing
4964 // template-generated or macro-generated dead code to potentially have out-of-
4965 // range values. These need to code generate, but don't need to necessarily
4966 // make any sense. We use a warning that defaults to an error.
4967 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4968}
4969
4970/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4971/// parameter with the FormatAttr's correct format_idx and firstDataArg.
4972/// Returns true when the format fits the function and the FormatStringInfo has
4973/// been populated.
4974bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4975 FormatStringInfo *FSI) {
4976 FSI->HasVAListArg = Format->getFirstArg() == 0;
4977 FSI->FormatIdx = Format->getFormatIdx() - 1;
4978 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4979
4980 // The way the format attribute works in GCC, the implicit this argument
4981 // of member functions is counted. However, it doesn't appear in our own
4982 // lists, so decrement format_idx in that case.
4983 if (IsCXXMember) {
4984 if(FSI->FormatIdx == 0)
4985 return false;
4986 --FSI->FormatIdx;
4987 if (FSI->FirstDataArg != 0)
4988 --FSI->FirstDataArg;
4989 }
4990 return true;
4991}
4992
4993/// Checks if a the given expression evaluates to null.
4994///
4995/// Returns true if the value evaluates to null.
4996static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4997 // If the expression has non-null type, it doesn't evaluate to null.
4998 if (auto nullability
4999 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
5000 if (*nullability == NullabilityKind::NonNull)
5001 return false;
5002 }
5003
5004 // As a special case, transparent unions initialized with zero are
5005 // considered null for the purposes of the nonnull attribute.
5006 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
5007 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
5008 if (const CompoundLiteralExpr *CLE =
5009 dyn_cast<CompoundLiteralExpr>(Expr))
5010 if (const InitListExpr *ILE =
5011 dyn_cast<InitListExpr>(CLE->getInitializer()))
5012 Expr = ILE->getInit(0);
5013 }
5014
5015 bool Result;
5016 return (!Expr->isValueDependent() &&
5017 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
5018 !Result);
5019}
5020
5021static void CheckNonNullArgument(Sema &S,
5022 const Expr *ArgExpr,
5023 SourceLocation CallSiteLoc) {
5024 if (CheckNonNullExpr(S, ArgExpr))
5025 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
5026 S.PDiag(diag::warn_null_arg)
5027 << ArgExpr->getSourceRange());
5028}
5029
5030bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
5031 FormatStringInfo FSI;
5032 if ((GetFormatStringType(Format) == FST_NSString) &&
5033 getFormatStringInfo(Format, false, &FSI)) {
5034 Idx = FSI.FormatIdx;
5035 return true;
5036 }
5037 return false;
5038}
5039
5040/// Diagnose use of %s directive in an NSString which is being passed
5041/// as formatting string to formatting method.
5042static void
5043DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
5044 const NamedDecl *FDecl,
5045 Expr **Args,
5046 unsigned NumArgs) {
5047 unsigned Idx = 0;
5048 bool Format = false;
5049 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
5050 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
5051 Idx = 2;
5052 Format = true;
5053 }
5054 else
5055 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5056 if (S.GetFormatNSStringIdx(I, Idx)) {
5057 Format = true;
5058 break;
5059 }
5060 }
5061 if (!Format || NumArgs <= Idx)
5062 return;
5063 const Expr *FormatExpr = Args[Idx];
5064 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
5065 FormatExpr = CSCE->getSubExpr();
5066 const StringLiteral *FormatString;
5067 if (const ObjCStringLiteral *OSL =
5068 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
5069 FormatString = OSL->getString();
5070 else
5071 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
5072 if (!FormatString)
5073 return;
5074 if (S.FormatStringHasSArg(FormatString)) {
5075 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
5076 << "%s" << 1 << 1;
5077 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
5078 << FDecl->getDeclName();
5079 }
5080}
5081
5082/// Determine whether the given type has a non-null nullability annotation.
5083static bool isNonNullType(ASTContext &ctx, QualType type) {
5084 if (auto nullability = type->getNullability(ctx))
5085 return *nullability == NullabilityKind::NonNull;
5086
5087 return false;
5088}
5089
5090static void CheckNonNullArguments(Sema &S,
5091 const NamedDecl *FDecl,
5092 const FunctionProtoType *Proto,
5093 ArrayRef<const Expr *> Args,
5094 SourceLocation CallSiteLoc) {
5095 assert((FDecl || Proto) && "Need a function declaration or prototype")(static_cast <bool> ((FDecl || Proto) && "Need a function declaration or prototype"
) ? void (0) : __assert_fail ("(FDecl || Proto) && \"Need a function declaration or prototype\""
, "clang/lib/Sema/SemaChecking.cpp", 5095, __extension__ __PRETTY_FUNCTION__
))
;
5096
5097 // Already checked by by constant evaluator.
5098 if (S.isConstantEvaluated())
5099 return;
5100 // Check the attributes attached to the method/function itself.
5101 llvm::SmallBitVector NonNullArgs;
5102 if (FDecl) {
5103 // Handle the nonnull attribute on the function/method declaration itself.
5104 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
5105 if (!NonNull->args_size()) {
5106 // Easy case: all pointer arguments are nonnull.
5107 for (const auto *Arg : Args)
5108 if (S.isValidPointerAttrType(Arg->getType()))
5109 CheckNonNullArgument(S, Arg, CallSiteLoc);
5110 return;
5111 }
5112
5113 for (const ParamIdx &Idx : NonNull->args()) {
5114 unsigned IdxAST = Idx.getASTIndex();
5115 if (IdxAST >= Args.size())
5116 continue;
5117 if (NonNullArgs.empty())
5118 NonNullArgs.resize(Args.size());
5119 NonNullArgs.set(IdxAST);
5120 }
5121 }
5122 }
5123
5124 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
5125 // Handle the nonnull attribute on the parameters of the
5126 // function/method.
5127 ArrayRef<ParmVarDecl*> parms;
5128 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
5129 parms = FD->parameters();
5130 else
5131 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
5132
5133 unsigned ParamIndex = 0;
5134 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
5135 I != E; ++I, ++ParamIndex) {
5136 const ParmVarDecl *PVD = *I;
5137 if (PVD->hasAttr<NonNullAttr>() ||
5138 isNonNullType(S.Context, PVD->getType())) {
5139 if (NonNullArgs.empty())
5140 NonNullArgs.resize(Args.size());
5141
5142 NonNullArgs.set(ParamIndex);
5143 }
5144 }
5145 } else {
5146 // If we have a non-function, non-method declaration but no
5147 // function prototype, try to dig out the function prototype.
5148 if (!Proto) {
5149 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
5150 QualType type = VD->getType().getNonReferenceType();
5151 if (auto pointerType = type->getAs<PointerType>())
5152 type = pointerType->getPointeeType();
5153 else if (auto blockType = type->getAs<BlockPointerType>())
5154 type = blockType->getPointeeType();
5155 // FIXME: data member pointers?
5156
5157 // Dig out the function prototype, if there is one.
5158 Proto = type->getAs<FunctionProtoType>();
5159 }
5160 }
5161
5162 // Fill in non-null argument information from the nullability
5163 // information on the parameter types (if we have them).
5164 if (Proto) {
5165 unsigned Index = 0;
5166 for (auto paramType : Proto->getParamTypes()) {
5167 if (isNonNullType(S.Context, paramType)) {
5168 if (NonNullArgs.empty())
5169 NonNullArgs.resize(Args.size());
5170
5171 NonNullArgs.set(Index);
5172 }
5173
5174 ++Index;
5175 }
5176 }
5177 }
5178
5179 // Check for non-null arguments.
5180 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
5181 ArgIndex != ArgIndexEnd; ++ArgIndex) {
5182 if (NonNullArgs[ArgIndex])
5183 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
5184 }
5185}
5186
5187/// Warn if a pointer or reference argument passed to a function points to an
5188/// object that is less aligned than the parameter. This can happen when
5189/// creating a typedef with a lower alignment than the original type and then
5190/// calling functions defined in terms of the original type.
5191void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
5192 StringRef ParamName, QualType ArgTy,
5193 QualType ParamTy) {
5194
5195 // If a function accepts a pointer or reference type
5196 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
5197 return;
5198
5199 // If the parameter is a pointer type, get the pointee type for the
5200 // argument too. If the parameter is a reference type, don't try to get
5201 // the pointee type for the argument.
5202 if (ParamTy->isPointerType())
5203 ArgTy = ArgTy->getPointeeType();
5204
5205 // Remove reference or pointer
5206 ParamTy = ParamTy->getPointeeType();
5207
5208 // Find expected alignment, and the actual alignment of the passed object.
5209 // getTypeAlignInChars requires complete types
5210 if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
5211 ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
5212 ArgTy->isUndeducedType())
5213 return;
5214
5215 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
5216 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
5217
5218 // If the argument is less aligned than the parameter, there is a
5219 // potential alignment issue.
5220 if (ArgAlign < ParamAlign)
5221 Diag(Loc, diag::warn_param_mismatched_alignment)
5222 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
5223 << ParamName << (FDecl != nullptr) << FDecl;
5224}
5225
5226/// Handles the checks for format strings, non-POD arguments to vararg
5227/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
5228/// attributes.
5229void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
5230 const Expr *ThisArg, ArrayRef<const Expr *> Args,
5231 bool IsMemberFunction, SourceLocation Loc,
5232 SourceRange Range, VariadicCallType CallType) {
5233 // FIXME: We should check as much as we can in the template definition.
5234 if (CurContext->isDependentContext())
5235 return;
5236
5237 // Printf and scanf checking.
5238 llvm::SmallBitVector CheckedVarArgs;
5239 if (FDecl) {
5240 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5241 // Only create vector if there are format attributes.
5242 CheckedVarArgs.resize(Args.size());
5243
5244 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
5245 CheckedVarArgs);
5246 }
5247 }
5248
5249 // Refuse POD arguments that weren't caught by the format string
5250 // checks above.
5251 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
5252 if (CallType != VariadicDoesNotApply &&
5253 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
5254 unsigned NumParams = Proto ? Proto->getNumParams()
5255 : FDecl && isa<FunctionDecl>(FDecl)
5256 ? cast<FunctionDecl>(FDecl)->getNumParams()
5257 : FDecl && isa<ObjCMethodDecl>(FDecl)
5258 ? cast<ObjCMethodDecl>(FDecl)->param_size()
5259 : 0;
5260
5261 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
5262 // Args[ArgIdx] can be null in malformed code.
5263 if (const Expr *Arg = Args[ArgIdx]) {
5264 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
5265 checkVariadicArgument(Arg, CallType);
5266 }
5267 }
5268 }
5269
5270 if (FDecl || Proto) {
5271 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
5272
5273 // Type safety checking.
5274 if (FDecl) {
5275 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
5276 CheckArgumentWithTypeTag(I, Args, Loc);
5277 }
5278 }
5279
5280 // Check that passed arguments match the alignment of original arguments.
5281 // Try to get the missing prototype from the declaration.
5282 if (!Proto && FDecl) {
5283 const auto *FT = FDecl->getFunctionType();
5284 if (isa_and_nonnull<FunctionProtoType>(FT))
5285 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5286 }
5287 if (Proto) {
5288 // For variadic functions, we may have more args than parameters.
5289 // For some K&R functions, we may have less args than parameters.
5290 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5291 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5292 // Args[ArgIdx] can be null in malformed code.
5293 if (const Expr *Arg = Args[ArgIdx]) {
5294 if (Arg->containsErrors())
5295 continue;
5296
5297 QualType ParamTy = Proto->getParamType(ArgIdx);
5298 QualType ArgTy = Arg->getType();
5299 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5300 ArgTy, ParamTy);
5301 }
5302 }
5303 }
5304
5305 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5306 auto *AA = FDecl->getAttr<AllocAlignAttr>();
5307 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5308 if (!Arg->isValueDependent()) {
5309 Expr::EvalResult Align;
5310 if (Arg->EvaluateAsInt(Align, Context)) {
5311 const llvm::APSInt &I = Align.Val.getInt();
5312 if (!I.isPowerOf2())
5313 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5314 << Arg->getSourceRange();
5315
5316 if (I > Sema::MaximumAlignment)
5317 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5318 << Arg->getSourceRange() << Sema::MaximumAlignment;
5319 }
5320 }
5321 }
5322
5323 if (FD)
5324 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5325}
5326
5327/// CheckConstructorCall - Check a constructor call for correctness and safety
5328/// properties not enforced by the C type system.
5329void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5330 ArrayRef<const Expr *> Args,
5331 const FunctionProtoType *Proto,
5332 SourceLocation Loc) {
5333 VariadicCallType CallType =
5334 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5335
5336 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5337 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5338 Context.getPointerType(Ctor->getThisObjectType()));
5339
5340 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5341 Loc, SourceRange(), CallType);
5342}
5343
5344/// CheckFunctionCall - Check a direct function call for various correctness
5345/// and safety properties not strictly enforced by the C type system.
5346bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5347 const FunctionProtoType *Proto) {
5348 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1
Assuming 'TheCall' is not a 'CXXOperatorCallExpr'
5349 isa<CXXMethodDecl>(FDecl);
5350 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2
Assuming 'TheCall' is not a 'CXXMemberCallExpr'
5351 IsMemberOperatorCall;
5352 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5353 TheCall->getCallee());
5354 Expr** Args = TheCall->getArgs();
5355 unsigned NumArgs = TheCall->getNumArgs();
5356
5357 Expr *ImplicitThis = nullptr;
5358 if (IsMemberOperatorCall
2.1
'IsMemberOperatorCall' is false
) {
3
Taking false branch
5359 // If this is a call to a member operator, hide the first argument
5360 // from checkCall.
5361 // FIXME: Our choice of AST representation here is less than ideal.
5362 ImplicitThis = Args[0];
5363 ++Args;
5364 --NumArgs;
5365 } else if (IsMemberFunction
3.1
'IsMemberFunction' is false
)
4
Taking false branch
5366 ImplicitThis =
5367 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5368
5369 if (ImplicitThis
4.1
'ImplicitThis' is null
) {
5
Taking false branch
5370 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5371 // used.
5372 QualType ThisType = ImplicitThis->getType();
5373 if (!ThisType->isPointerType()) {
5374 assert(!ThisType->isReferenceType())(static_cast <bool> (!ThisType->isReferenceType()) ?
void (0) : __assert_fail ("!ThisType->isReferenceType()",
"clang/lib/Sema/SemaChecking.cpp", 5374, __extension__ __PRETTY_FUNCTION__
))
;
5375 ThisType = Context.getPointerType(ThisType);
5376 }
5377
5378 QualType ThisTypeFromDecl =
5379 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5380
5381 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5382 ThisTypeFromDecl);
5383 }
5384
5385 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5386 IsMemberFunction, TheCall->getRParenLoc(),
5387 TheCall->getCallee()->getSourceRange(), CallType);
5388
5389 IdentifierInfo *FnInfo = FDecl->getIdentifier();
5390 // None of the checks below are needed for functions that don't have
5391 // simple names (e.g., C++ conversion functions).
5392 if (!FnInfo)
6
Assuming 'FnInfo' is non-null
7
Taking false branch
5393 return false;
5394
5395 CheckTCBEnforcement(TheCall, FDecl);
5396
5397 CheckAbsoluteValueFunction(TheCall, FDecl);
5398 CheckMaxUnsignedZero(TheCall, FDecl);
5399
5400 if (getLangOpts().ObjC)
8
Assuming field 'ObjC' is 0
9
Taking false branch
5401 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5402
5403 unsigned CMId = FDecl->getMemoryFunctionKind();
5404
5405 // Handle memory setting and copying functions.
5406 switch (CMId) {
10
Control jumps to 'case BIfree:' at line 5416
5407 case 0:
5408 return false;
5409/* case Builtin::BIstrlcpy: // fallthrough
5410 case Builtin::BIstrlcat:
5411 CheckStrlcpycatArguments(TheCall, FnInfo);
5412 break;*/
5413 case Builtin::BIstrncat:
5414 CheckStrncatArguments(TheCall, FnInfo);
5415 break;
5416 case Builtin::BIfree:
5417 CheckFreeArguments(TheCall);
11
Calling 'Sema::CheckFreeArguments'
5418 break;
5419 default:
5420 CheckMemaccessArguments(TheCall, CMId, FnInfo);
5421 }
5422
5423 return false;
5424}
5425
5426bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5427 ArrayRef<const Expr *> Args) {
5428 VariadicCallType CallType =
5429 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5430
5431 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5432 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5433 CallType);
5434
5435 return false;
5436}
5437
5438bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5439 const FunctionProtoType *Proto) {
5440 QualType Ty;
5441 if (const auto *V = dyn_cast<VarDecl>(NDecl))
5442 Ty = V->getType().getNonReferenceType();
5443 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5444 Ty = F->getType().getNonReferenceType();
5445 else
5446 return false;
5447
5448 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5449 !Ty->isFunctionProtoType())
5450 return false;
5451
5452 VariadicCallType CallType;
5453 if (!Proto || !Proto->isVariadic()) {
5454 CallType = VariadicDoesNotApply;
5455 } else if (Ty->isBlockPointerType()) {
5456 CallType = VariadicBlock;
5457 } else { // Ty->isFunctionPointerType()
5458 CallType = VariadicFunction;
5459 }
5460
5461 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5462 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5463 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5464 TheCall->getCallee()->getSourceRange(), CallType);
5465
5466 return false;
5467}
5468
5469/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5470/// such as function pointers returned from functions.
5471bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5472 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5473 TheCall->getCallee());
5474 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5475 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5476 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5477 TheCall->getCallee()->getSourceRange(), CallType);
5478
5479 return false;
5480}
5481
5482static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5483 if (!llvm::isValidAtomicOrderingCABI(Ordering))
5484 return false;
5485
5486 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5487 switch (Op) {
5488 case AtomicExpr::AO__c11_atomic_init:
5489 case AtomicExpr::AO__opencl_atomic_init:
5490 llvm_unreachable("There is no ordering argument for an init")::llvm::llvm_unreachable_internal("There is no ordering argument for an init"
, "clang/lib/Sema/SemaChecking.cpp", 5490)
;
5491
5492 case AtomicExpr::AO__c11_atomic_load:
5493 case AtomicExpr::AO__opencl_atomic_load:
5494 case AtomicExpr::AO__hip_atomic_load:
5495 case AtomicExpr::AO__atomic_load_n:
5496 case AtomicExpr::AO__atomic_load:
5497 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5498 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5499
5500 case AtomicExpr::AO__c11_atomic_store:
5501 case AtomicExpr::AO__opencl_atomic_store:
5502 case AtomicExpr::AO__hip_atomic_store:
5503 case AtomicExpr::AO__atomic_store:
5504 case AtomicExpr::AO__atomic_store_n:
5505 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5506 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5507 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5508
5509 default:
5510 return true;
5511 }
5512}
5513
5514ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5515 AtomicExpr::AtomicOp Op) {
5516 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5517 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5518 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5519 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5520 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5521 Op);
5522}
5523
5524ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5525 SourceLocation RParenLoc, MultiExprArg Args,
5526 AtomicExpr::AtomicOp Op,
5527 AtomicArgumentOrder ArgOrder) {
5528 // All the non-OpenCL operations take one of the following forms.
5529 // The OpenCL operations take the __c11 forms with one extra argument for
5530 // synchronization scope.
5531 enum {
5532 // C __c11_atomic_init(A *, C)
5533 Init,
5534
5535 // C __c11_atomic_load(A *, int)
5536 Load,
5537
5538 // void __atomic_load(A *, CP, int)
5539 LoadCopy,
5540
5541 // void __atomic_store(A *, CP, int)
5542 Copy,
5543
5544 // C __c11_atomic_add(A *, M, int)
5545 Arithmetic,
5546
5547 // C __atomic_exchange_n(A *, CP, int)
5548 Xchg,
5549
5550 // void __atomic_exchange(A *, C *, CP, int)
5551 GNUXchg,
5552
5553 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5554 C11CmpXchg,
5555
5556 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5557 GNUCmpXchg
5558 } Form = Init;
5559
5560 const unsigned NumForm = GNUCmpXchg + 1;
5561 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5562 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5563 // where:
5564 // C is an appropriate type,
5565 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5566 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5567 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5568 // the int parameters are for orderings.
5569
5570 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5571 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5572 "need to update code for modified forms");
5573 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5574 AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5575 AtomicExpr::AO__atomic_load,
5576 "need to update code for modified C11 atomics");
5577 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5578 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5579 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load &&
5580 Op <= AtomicExpr::AO__hip_atomic_fetch_max;
5581 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5582 Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5583 IsOpenCL;
5584 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5585 Op == AtomicExpr::AO__atomic_store_n ||
5586 Op == AtomicExpr::AO__atomic_exchange_n ||
5587 Op == AtomicExpr::AO__atomic_compare_exchange_n;
5588 bool IsAddSub = false;
5589
5590 switch (Op) {
5591 case AtomicExpr::AO__c11_atomic_init:
5592 case AtomicExpr::AO__opencl_atomic_init:
5593 Form = Init;
5594 break;
5595
5596 case AtomicExpr::AO__c11_atomic_load:
5597 case AtomicExpr::AO__opencl_atomic_load:
5598 case AtomicExpr::AO__hip_atomic_load:
5599 case AtomicExpr::AO__atomic_load_n:
5600 Form = Load;
5601 break;
5602
5603 case AtomicExpr::AO__atomic_load:
5604 Form = LoadCopy;
5605 break;
5606
5607 case AtomicExpr::AO__c11_atomic_store:
5608 case AtomicExpr::AO__opencl_atomic_store:
5609 case AtomicExpr::AO__hip_atomic_store:
5610 case AtomicExpr::AO__atomic_store:
5611 case AtomicExpr::AO__atomic_store_n:
5612 Form = Copy;
5613 break;
5614 case AtomicExpr::AO__hip_atomic_fetch_add:
5615 case AtomicExpr::AO__hip_atomic_fetch_min:
5616 case AtomicExpr::AO__hip_atomic_fetch_max:
5617 case AtomicExpr::AO__c11_atomic_fetch_add:
5618 case AtomicExpr::AO__c11_atomic_fetch_sub:
5619 case AtomicExpr::AO__opencl_atomic_fetch_add:
5620 case AtomicExpr::AO__opencl_atomic_fetch_sub:
5621 case AtomicExpr::AO__atomic_fetch_add:
5622 case AtomicExpr::AO__atomic_fetch_sub:
5623 case AtomicExpr::AO__atomic_add_fetch:
5624 case AtomicExpr::AO__atomic_sub_fetch:
5625 IsAddSub = true;
5626 Form = Arithmetic;
5627 break;
5628 case AtomicExpr::AO__c11_atomic_fetch_and:
5629 case AtomicExpr::AO__c11_atomic_fetch_or:
5630 case AtomicExpr::AO__c11_atomic_fetch_xor:
5631 case AtomicExpr::AO__hip_atomic_fetch_and:
5632 case AtomicExpr::AO__hip_atomic_fetch_or:
5633 case AtomicExpr::AO__hip_atomic_fetch_xor:
5634 case AtomicExpr::AO__c11_atomic_fetch_nand:
5635 case AtomicExpr::AO__opencl_atomic_fetch_and:
5636 case AtomicExpr::AO__opencl_atomic_fetch_or:
5637 case AtomicExpr::AO__opencl_atomic_fetch_xor:
5638 case AtomicExpr::AO__atomic_fetch_and:
5639 case AtomicExpr::AO__atomic_fetch_or:
5640 case AtomicExpr::AO__atomic_fetch_xor:
5641 case AtomicExpr::AO__atomic_fetch_nand:
5642 case AtomicExpr::AO__atomic_and_fetch:
5643 case AtomicExpr::AO__atomic_or_fetch:
5644 case AtomicExpr::AO__atomic_xor_fetch:
5645 case AtomicExpr::AO__atomic_nand_fetch:
5646 Form = Arithmetic;
5647 break;
5648 case AtomicExpr::AO__c11_atomic_fetch_min:
5649 case AtomicExpr::AO__c11_atomic_fetch_max:
5650 case AtomicExpr::AO__opencl_atomic_fetch_min:
5651 case AtomicExpr::AO__opencl_atomic_fetch_max:
5652 case AtomicExpr::AO__atomic_min_fetch:
5653 case AtomicExpr::AO__atomic_max_fetch:
5654 case AtomicExpr::AO__atomic_fetch_min:
5655 case AtomicExpr::AO__atomic_fetch_max:
5656 Form = Arithmetic;
5657 break;
5658
5659 case AtomicExpr::AO__c11_atomic_exchange:
5660 case AtomicExpr::AO__hip_atomic_exchange:
5661 case AtomicExpr::AO__opencl_atomic_exchange:
5662 case AtomicExpr::AO__atomic_exchange_n:
5663 Form = Xchg;
5664 break;
5665
5666 case AtomicExpr::AO__atomic_exchange:
5667 Form = GNUXchg;
5668 break;
5669
5670 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5671 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5672 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5673 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5674 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5675 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5676 Form = C11CmpXchg;
5677 break;
5678
5679 case AtomicExpr::AO__atomic_compare_exchange:
5680 case AtomicExpr::AO__atomic_compare_exchange_n:
5681 Form = GNUCmpXchg;
5682 break;
5683 }
5684
5685 unsigned AdjustedNumArgs = NumArgs[Form];
5686 if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init)
5687 ++AdjustedNumArgs;
5688 // Check we have the right number of arguments.
5689 if (Args.size() < AdjustedNumArgs) {
5690 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5691 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5692 << ExprRange;
5693 return ExprError();
5694 } else if (Args.size() > AdjustedNumArgs) {
5695 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5696 diag::err_typecheck_call_too_many_args)
5697 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5698 << ExprRange;
5699 return ExprError();
5700 }
5701
5702 // Inspect the first argument of the atomic operation.
5703 Expr *Ptr = Args[0];
5704 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5705 if (ConvertedPtr.isInvalid())
5706 return ExprError();
5707
5708 Ptr = ConvertedPtr.get();
5709 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5710 if (!pointerType) {
5711 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5712 << Ptr->getType() << Ptr->getSourceRange();
5713 return ExprError();
5714 }
5715
5716 // For a __c11 builtin, this should be a pointer to an _Atomic type.
5717 QualType AtomTy = pointerType->getPointeeType(); // 'A'
5718 QualType ValType = AtomTy; // 'C'
5719 if (IsC11) {
5720 if (!AtomTy->isAtomicType()) {
5721 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5722 << Ptr->getType() << Ptr->getSourceRange();
5723 return ExprError();
5724 }
5725 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5726 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5727 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5728 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5729 << Ptr->getSourceRange();
5730 return ExprError();
5731 }
5732 ValType = AtomTy->castAs<AtomicType>()->getValueType();
5733 } else if (Form != Load && Form != LoadCopy) {
5734 if (ValType.isConstQualified()) {
5735 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5736 << Ptr->getType() << Ptr->getSourceRange();
5737 return ExprError();
5738 }
5739 }
5740
5741 // For an arithmetic operation, the implied arithmetic must be well-formed.
5742 if (Form == Arithmetic) {
5743 // GCC does not enforce these rules for GNU atomics, but we do to help catch
5744 // trivial type errors.
5745 auto IsAllowedValueType = [&](QualType ValType) {
5746 if (ValType->isIntegerType())
5747 return true;
5748 if (ValType->isPointerType())
5749 return true;
5750 if (!ValType->isFloatingType())
5751 return false;
5752 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5753 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5754 &Context.getTargetInfo().getLongDoubleFormat() ==
5755 &llvm::APFloat::x87DoubleExtended())
5756 return false;
5757 return true;
5758 };
5759 if (IsAddSub && !IsAllowedValueType(ValType)) {
5760 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5761 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5762 return ExprError();
5763 }
5764 if (!IsAddSub && !ValType->isIntegerType()) {
5765 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5766 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5767 return ExprError();
5768 }
5769 if (IsC11 && ValType->isPointerType() &&
5770 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5771 diag::err_incomplete_type)) {
5772 return ExprError();
5773 }
5774 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5775 // For __atomic_*_n operations, the value type must be a scalar integral or
5776 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5777 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5778 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5779 return ExprError();
5780 }
5781
5782 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5783 !AtomTy->isScalarType()) {
5784 // For GNU atomics, require a trivially-copyable type. This is not part of
5785 // the GNU atomics specification but we enforce it for consistency with
5786 // other atomics which generally all require a trivially-copyable type. This
5787 // is because atomics just copy bits.
5788 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5789 << Ptr->getType() << Ptr->getSourceRange();
5790 return ExprError();
5791 }
5792
5793 switch (ValType.getObjCLifetime()) {
5794 case Qualifiers::OCL_None:
5795 case Qualifiers::OCL_ExplicitNone:
5796 // okay