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