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