Bug Summary

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