Bug Summary

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