clang 19.0.0git
SemaChecking.cpp
Go to the documentation of this file.
1//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements extra semantic analysis beyond what is enforced
10// by the C type system.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
16#include "clang/AST/Attr.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/ExprObjC.h"
31#include "clang/AST/NSAPI.h"
35#include "clang/AST/Stmt.h"
37#include "clang/AST/Type.h"
38#include "clang/AST/TypeLoc.h"
44#include "clang/Basic/LLVM.h"
57#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
59#include "clang/Sema/Lookup.h"
61#include "clang/Sema/Scope.h"
63#include "clang/Sema/Sema.h"
65#include "llvm/ADT/APFloat.h"
66#include "llvm/ADT/APInt.h"
67#include "llvm/ADT/APSInt.h"
68#include "llvm/ADT/ArrayRef.h"
69#include "llvm/ADT/DenseMap.h"
70#include "llvm/ADT/FoldingSet.h"
71#include "llvm/ADT/STLExtras.h"
72#include "llvm/ADT/SmallBitVector.h"
73#include "llvm/ADT/SmallPtrSet.h"
74#include "llvm/ADT/SmallString.h"
75#include "llvm/ADT/SmallVector.h"
76#include "llvm/ADT/StringExtras.h"
77#include "llvm/ADT/StringRef.h"
78#include "llvm/ADT/StringSet.h"
79#include "llvm/ADT/StringSwitch.h"
80#include "llvm/Support/AtomicOrdering.h"
81#include "llvm/Support/Casting.h"
82#include "llvm/Support/Compiler.h"
83#include "llvm/Support/ConvertUTF.h"
84#include "llvm/Support/ErrorHandling.h"
85#include "llvm/Support/Format.h"
86#include "llvm/Support/Locale.h"
87#include "llvm/Support/MathExtras.h"
88#include "llvm/Support/SaveAndRestore.h"
89#include "llvm/Support/raw_ostream.h"
90#include "llvm/TargetParser/RISCVTargetParser.h"
91#include "llvm/TargetParser/Triple.h"
92#include <algorithm>
93#include <bitset>
94#include <cassert>
95#include <cctype>
96#include <cstddef>
97#include <cstdint>
98#include <functional>
99#include <limits>
100#include <optional>
101#include <string>
102#include <tuple>
103#include <utility>
104
105using namespace clang;
106using namespace sema;
107
109 unsigned ByteNo) const {
110 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
112}
113
114static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
116 return (A << 8) | B;
117}
118
119/// Checks that a call expression's argument count is at least the desired
120/// number. This is useful when doing custom type-checking on a variadic
121/// function. Returns true on error.
123 unsigned MinArgCount) {
124 unsigned ArgCount = Call->getNumArgs();
125 if (ArgCount >= MinArgCount)
126 return false;
127
128 return S.Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
129 << 0 /*function call*/ << MinArgCount << ArgCount
130 << /*is non object*/ 0 << Call->getSourceRange();
131}
132
133/// Checks that a call expression's argument count is at most the desired
134/// number. This is useful when doing custom type-checking on a variadic
135/// function. Returns true on error.
136static bool checkArgCountAtMost(Sema &S, CallExpr *Call, unsigned MaxArgCount) {
137 unsigned ArgCount = Call->getNumArgs();
138 if (ArgCount <= MaxArgCount)
139 return false;
140 return S.Diag(Call->getEndLoc(),
141 diag::err_typecheck_call_too_many_args_at_most)
142 << 0 /*function call*/ << MaxArgCount << ArgCount
143 << /*is non object*/ 0 << Call->getSourceRange();
144}
145
146/// Checks that a call expression's argument count is in the desired range. This
147/// is useful when doing custom type-checking on a variadic function. Returns
148/// true on error.
149static bool checkArgCountRange(Sema &S, CallExpr *Call, unsigned MinArgCount,
150 unsigned MaxArgCount) {
151 return checkArgCountAtLeast(S, Call, MinArgCount) ||
152 checkArgCountAtMost(S, Call, MaxArgCount);
153}
154
155/// Checks that a call expression's argument count is the desired number.
156/// This is useful when doing custom type-checking. Returns true on error.
157static bool checkArgCount(Sema &S, CallExpr *Call, unsigned DesiredArgCount) {
158 unsigned ArgCount = Call->getNumArgs();
159 if (ArgCount == DesiredArgCount)
160 return false;
161
162 if (checkArgCountAtLeast(S, Call, DesiredArgCount))
163 return true;
164 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
165
166 // Highlight all the excess arguments.
167 SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
168 Call->getArg(ArgCount - 1)->getEndLoc());
169
170 return S.Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
171 << 0 /*function call*/ << DesiredArgCount << ArgCount
172 << /*is non object*/ 0 << Call->getArg(1)->getSourceRange();
173}
174
176 if (Value->isTypeDependent())
177 return false;
178
179 InitializedEntity Entity =
183 if (Result.isInvalid())
184 return true;
185 Value = Result.get();
186 return false;
187}
188
189/// Check that the first argument to __builtin_annotation is an integer
190/// and the second argument is a non-wide string literal.
191static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
192 if (checkArgCount(S, TheCall, 2))
193 return true;
194
195 // First argument should be an integer.
196 Expr *ValArg = TheCall->getArg(0);
197 QualType Ty = ValArg->getType();
198 if (!Ty->isIntegerType()) {
199 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
200 << ValArg->getSourceRange();
201 return true;
202 }
203
204 // Second argument should be a constant string.
205 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
206 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
207 if (!Literal || !Literal->isOrdinary()) {
208 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
209 << StrArg->getSourceRange();
210 return true;
211 }
212
213 TheCall->setType(Ty);
214 return false;
215}
216
217static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
218 // We need at least one argument.
219 if (TheCall->getNumArgs() < 1) {
220 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
221 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
222 << TheCall->getCallee()->getSourceRange();
223 return true;
224 }
225
226 // All arguments should be wide string literals.
227 for (Expr *Arg : TheCall->arguments()) {
228 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
229 if (!Literal || !Literal->isWide()) {
230 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
231 << Arg->getSourceRange();
232 return true;
233 }
234 }
235
236 return false;
237}
238
239/// Check that the argument to __builtin_addressof is a glvalue, and set the
240/// result type to the corresponding pointer type.
241static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
242 if (checkArgCount(S, TheCall, 1))
243 return true;
244
245 ExprResult Arg(TheCall->getArg(0));
246 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
247 if (ResultType.isNull())
248 return true;
249
250 TheCall->setArg(0, Arg.get());
251 TheCall->setType(ResultType);
252 return false;
253}
254
255/// Check that the argument to __builtin_function_start is a function.
256static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
257 if (checkArgCount(S, TheCall, 1))
258 return true;
259
261 if (Arg.isInvalid())
262 return true;
263
264 TheCall->setArg(0, Arg.get());
265 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
267
268 if (!FD) {
269 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
270 << TheCall->getSourceRange();
271 return true;
272 }
273
274 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
275 TheCall->getBeginLoc());
276}
277
278/// Check the number of arguments and set the result type to
279/// the argument type.
280static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
281 if (checkArgCount(S, TheCall, 1))
282 return true;
283
284 TheCall->setType(TheCall->getArg(0)->getType());
285 return false;
286}
287
288/// Check that the value argument for __builtin_is_aligned(value, alignment) and
289/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
290/// type (but not a function pointer) and that the alignment is a power-of-two.
291static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
292 if (checkArgCount(S, TheCall, 2))
293 return true;
294
295 clang::Expr *Source = TheCall->getArg(0);
296 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
297
298 auto IsValidIntegerType = [](QualType Ty) {
299 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
300 };
301 QualType SrcTy = Source->getType();
302 // We should also be able to use it with arrays (but not functions!).
303 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
304 SrcTy = S.Context.getDecayedType(SrcTy);
305 }
306 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
307 SrcTy->isFunctionPointerType()) {
308 // FIXME: this is not quite the right error message since we don't allow
309 // floating point types, or member pointers.
310 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
311 << SrcTy;
312 return true;
313 }
314
315 clang::Expr *AlignOp = TheCall->getArg(1);
316 if (!IsValidIntegerType(AlignOp->getType())) {
317 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
318 << AlignOp->getType();
319 return true;
320 }
321 Expr::EvalResult AlignResult;
322 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
323 // We can't check validity of alignment if it is value dependent.
324 if (!AlignOp->isValueDependent() &&
325 AlignOp->EvaluateAsInt(AlignResult, S.Context,
327 llvm::APSInt AlignValue = AlignResult.Val.getInt();
328 llvm::APSInt MaxValue(
329 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
330 if (AlignValue < 1) {
331 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
332 return true;
333 }
334 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
335 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
336 << toString(MaxValue, 10);
337 return true;
338 }
339 if (!AlignValue.isPowerOf2()) {
340 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
341 return true;
342 }
343 if (AlignValue == 1) {
344 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
345 << IsBooleanAlignBuiltin;
346 }
347 }
348
351 SourceLocation(), Source);
352 if (SrcArg.isInvalid())
353 return true;
354 TheCall->setArg(0, SrcArg.get());
355 ExprResult AlignArg =
357 S.Context, AlignOp->getType(), false),
358 SourceLocation(), AlignOp);
359 if (AlignArg.isInvalid())
360 return true;
361 TheCall->setArg(1, AlignArg.get());
362 // For align_up/align_down, the return type is the same as the (potentially
363 // decayed) argument type including qualifiers. For is_aligned(), the result
364 // is always bool.
365 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
366 return false;
367}
368
369static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
370 if (checkArgCount(S, TheCall, 3))
371 return true;
372
373 std::pair<unsigned, const char *> Builtins[] = {
374 { Builtin::BI__builtin_add_overflow, "ckd_add" },
375 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
376 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
377 };
378
379 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
380 const char *> &P) {
381 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
383 S.getSourceManager(), S.getLangOpts()) == P.second;
384 });
385
386 auto ValidCkdIntType = [](QualType QT) {
387 // A valid checked integer type is an integer type other than a plain char,
388 // bool, a bit-precise type, or an enumeration type.
389 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
390 return (BT->getKind() >= BuiltinType::Short &&
391 BT->getKind() <= BuiltinType::Int128) || (
392 BT->getKind() >= BuiltinType::UShort &&
393 BT->getKind() <= BuiltinType::UInt128) ||
394 BT->getKind() == BuiltinType::UChar ||
395 BT->getKind() == BuiltinType::SChar;
396 return false;
397 };
398
399 // First two arguments should be integers.
400 for (unsigned I = 0; I < 2; ++I) {
402 if (Arg.isInvalid()) return true;
403 TheCall->setArg(I, Arg.get());
404
405 QualType Ty = Arg.get()->getType();
406 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
407 if (!IsValid) {
408 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
409 << CkdOperation << Ty << Arg.get()->getSourceRange();
410 return true;
411 }
412 }
413
414 // Third argument should be a pointer to a non-const integer.
415 // IRGen correctly handles volatile, restrict, and address spaces, and
416 // the other qualifiers aren't possible.
417 {
419 if (Arg.isInvalid()) return true;
420 TheCall->setArg(2, Arg.get());
421
422 QualType Ty = Arg.get()->getType();
423 const auto *PtrTy = Ty->getAs<PointerType>();
424 if (!PtrTy ||
425 !PtrTy->getPointeeType()->isIntegerType() ||
426 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
427 PtrTy->getPointeeType().isConstQualified()) {
428 S.Diag(Arg.get()->getBeginLoc(),
429 diag::err_overflow_builtin_must_be_ptr_int)
430 << CkdOperation << Ty << Arg.get()->getSourceRange();
431 return true;
432 }
433 }
434
435 // Disallow signed bit-precise integer args larger than 128 bits to mul
436 // function until we improve backend support.
437 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
438 for (unsigned I = 0; I < 3; ++I) {
439 const auto Arg = TheCall->getArg(I);
440 // Third argument will be a pointer.
441 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
442 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
443 S.getASTContext().getIntWidth(Ty) > 128)
444 return S.Diag(Arg->getBeginLoc(),
445 diag::err_overflow_builtin_bit_int_max_size)
446 << 128;
447 }
448 }
449
450 return false;
451}
452
453namespace {
454struct BuiltinDumpStructGenerator {
455 Sema &S;
456 CallExpr *TheCall;
457 SourceLocation Loc = TheCall->getBeginLoc();
459 DiagnosticErrorTrap ErrorTracker;
460 PrintingPolicy Policy;
461
462 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
463 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
464 Policy(S.Context.getPrintingPolicy()) {
465 Policy.AnonymousTagLocations = false;
466 }
467
468 Expr *makeOpaqueValueExpr(Expr *Inner) {
469 auto *OVE = new (S.Context)
470 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
471 Inner->getObjectKind(), Inner);
472 Actions.push_back(OVE);
473 return OVE;
474 }
475
476 Expr *getStringLiteral(llvm::StringRef Str) {
478 // Wrap the literal in parentheses to attach a source location.
479 return new (S.Context) ParenExpr(Loc, Loc, Lit);
480 }
481
482 bool callPrintFunction(llvm::StringRef Format,
483 llvm::ArrayRef<Expr *> Exprs = {}) {
485 assert(TheCall->getNumArgs() >= 2);
486 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
487 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
488 Args.push_back(getStringLiteral(Format));
489 Args.insert(Args.end(), Exprs.begin(), Exprs.end());
490
491 // Register a note to explain why we're performing the call.
494 Ctx.PointOfInstantiation = Loc;
495 Ctx.CallArgs = Args.data();
496 Ctx.NumCallArgs = Args.size();
498
499 ExprResult RealCall =
500 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
501 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
502
504 if (!RealCall.isInvalid())
505 Actions.push_back(RealCall.get());
506 // Bail out if we've hit any errors, even if we managed to build the
507 // call. We don't want to produce more than one error.
508 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
509 }
510
511 Expr *getIndentString(unsigned Depth) {
512 if (!Depth)
513 return nullptr;
514
516 Indent.resize(Depth * Policy.Indentation, ' ');
517 return getStringLiteral(Indent);
518 }
519
521 return getStringLiteral(T.getAsString(Policy));
522 }
523
524 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
525 llvm::raw_svector_ostream OS(Str);
526
527 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
528 // than trying to print a single character.
529 if (auto *BT = T->getAs<BuiltinType>()) {
530 switch (BT->getKind()) {
531 case BuiltinType::Bool:
532 OS << "%d";
533 return true;
534 case BuiltinType::Char_U:
535 case BuiltinType::UChar:
536 OS << "%hhu";
537 return true;
538 case BuiltinType::Char_S:
539 case BuiltinType::SChar:
540 OS << "%hhd";
541 return true;
542 default:
543 break;
544 }
545 }
546
548 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
549 // We were able to guess how to format this.
550 if (Specifier.getConversionSpecifier().getKind() ==
551 analyze_printf::PrintfConversionSpecifier::sArg) {
552 // Wrap double-quotes around a '%s' specifier and limit its maximum
553 // length. Ideally we'd also somehow escape special characters in the
554 // contents but printf doesn't support that.
555 // FIXME: '%s' formatting is not safe in general.
556 OS << '"';
557 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
558 Specifier.toString(OS);
559 OS << '"';
560 // FIXME: It would be nice to include a '...' if the string doesn't fit
561 // in the length limit.
562 } else {
563 Specifier.toString(OS);
564 }
565 return true;
566 }
567
568 if (T->isPointerType()) {
569 // Format all pointers with '%p'.
570 OS << "%p";
571 return true;
572 }
573
574 return false;
575 }
576
577 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
578 Expr *IndentLit = getIndentString(Depth);
579 Expr *TypeLit = getTypeString(S.Context.getRecordType(RD));
580 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
581 : callPrintFunction("%s", {TypeLit}))
582 return true;
583
584 return dumpRecordValue(RD, E, IndentLit, Depth);
585 }
586
587 // Dump a record value. E should be a pointer or lvalue referring to an RD.
588 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
589 unsigned Depth) {
590 // FIXME: Decide what to do if RD is a union. At least we should probably
591 // turn off printing `const char*` members with `%s`, because that is very
592 // likely to crash if that's not the active member. Whatever we decide, we
593 // should document it.
594
595 // Build an OpaqueValueExpr so we can refer to E more than once without
596 // triggering re-evaluation.
597 Expr *RecordArg = makeOpaqueValueExpr(E);
598 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
599
600 if (callPrintFunction(" {\n"))
601 return true;
602
603 // Dump each base class, regardless of whether they're aggregates.
604 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
605 for (const auto &Base : CXXRD->bases()) {
606 QualType BaseType =
607 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
608 : S.Context.getLValueReferenceType(Base.getType());
610 Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
611 RecordArg);
612 if (BasePtr.isInvalid() ||
613 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
614 Depth + 1))
615 return true;
616 }
617 }
618
619 Expr *FieldIndentArg = getIndentString(Depth + 1);
620
621 // Dump each field.
622 for (auto *D : RD->decls()) {
623 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
624 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
625 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
626 continue;
627
628 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
629 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
630 getTypeString(FD->getType()),
631 getStringLiteral(FD->getName())};
632
633 if (FD->isBitField()) {
634 Format += ": %zu ";
636 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
637 FD->getBitWidthValue(S.Context));
638 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
639 }
640
641 Format += "=";
642
645 CXXScopeSpec(), Loc, IFD,
646 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
648 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
650 DeclarationNameInfo(FD->getDeclName(), Loc));
651 if (Field.isInvalid())
652 return true;
653
654 auto *InnerRD = FD->getType()->getAsRecordDecl();
655 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
656 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
657 // Recursively print the values of members of aggregate record type.
658 if (callPrintFunction(Format, Args) ||
659 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
660 return true;
661 } else {
662 Format += " ";
663 if (appendFormatSpecifier(FD->getType(), Format)) {
664 // We know how to print this field.
665 Args.push_back(Field.get());
666 } else {
667 // We don't know how to print this field. Print out its address
668 // with a format specifier that a smart tool will be able to
669 // recognize and treat specially.
670 Format += "*%p";
671 ExprResult FieldAddr =
672 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
673 if (FieldAddr.isInvalid())
674 return true;
675 Args.push_back(FieldAddr.get());
676 }
677 Format += "\n";
678 if (callPrintFunction(Format, Args))
679 return true;
680 }
681 }
682
683 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
684 : callPrintFunction("}\n");
685 }
686
687 Expr *buildWrapper() {
688 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
690 TheCall->setType(Wrapper->getType());
691 TheCall->setValueKind(Wrapper->getValueKind());
692 return Wrapper;
693 }
694};
695} // namespace
696
698 if (checkArgCountAtLeast(S, TheCall, 2))
699 return ExprError();
700
701 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
702 if (PtrArgResult.isInvalid())
703 return ExprError();
704 TheCall->setArg(0, PtrArgResult.get());
705
706 // First argument should be a pointer to a struct.
707 QualType PtrArgType = PtrArgResult.get()->getType();
708 if (!PtrArgType->isPointerType() ||
709 !PtrArgType->getPointeeType()->isRecordType()) {
710 S.Diag(PtrArgResult.get()->getBeginLoc(),
711 diag::err_expected_struct_pointer_argument)
712 << 1 << TheCall->getDirectCallee() << PtrArgType;
713 return ExprError();
714 }
715 QualType Pointee = PtrArgType->getPointeeType();
716 const RecordDecl *RD = Pointee->getAsRecordDecl();
717 // Try to instantiate the class template as appropriate; otherwise, access to
718 // its data() may lead to a crash.
719 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
720 diag::err_incomplete_type))
721 return ExprError();
722 // Second argument is a callable, but we can't fully validate it until we try
723 // calling it.
724 QualType FnArgType = TheCall->getArg(1)->getType();
725 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
726 !FnArgType->isBlockPointerType() &&
727 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
728 auto *BT = FnArgType->getAs<BuiltinType>();
729 switch (BT ? BT->getKind() : BuiltinType::Void) {
730 case BuiltinType::Dependent:
731 case BuiltinType::Overload:
732 case BuiltinType::BoundMember:
733 case BuiltinType::PseudoObject:
734 case BuiltinType::UnknownAny:
735 case BuiltinType::BuiltinFn:
736 // This might be a callable.
737 break;
738
739 default:
740 S.Diag(TheCall->getArg(1)->getBeginLoc(),
741 diag::err_expected_callable_argument)
742 << 2 << TheCall->getDirectCallee() << FnArgType;
743 return ExprError();
744 }
745 }
746
747 BuiltinDumpStructGenerator Generator(S, TheCall);
748
749 // Wrap parentheses around the given pointer. This is not necessary for
750 // correct code generation, but it means that when we pretty-print the call
751 // arguments in our diagnostics we will produce '(&s)->n' instead of the
752 // incorrect '&s->n'.
753 Expr *PtrArg = PtrArgResult.get();
754 PtrArg = new (S.Context)
755 ParenExpr(PtrArg->getBeginLoc(),
756 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
757 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
758 return ExprError();
759
760 return Generator.buildWrapper();
761}
762
763static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
764 if (checkArgCount(S, BuiltinCall, 2))
765 return true;
766
767 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
768 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
769 Expr *Call = BuiltinCall->getArg(0);
770 Expr *Chain = BuiltinCall->getArg(1);
771
772 if (Call->getStmtClass() != Stmt::CallExprClass) {
773 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
774 << Call->getSourceRange();
775 return true;
776 }
777
778 auto CE = cast<CallExpr>(Call);
779 if (CE->getCallee()->getType()->isBlockPointerType()) {
780 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
781 << Call->getSourceRange();
782 return true;
783 }
784
785 const Decl *TargetDecl = CE->getCalleeDecl();
786 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
787 if (FD->getBuiltinID()) {
788 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
789 << Call->getSourceRange();
790 return true;
791 }
792
793 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
794 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
795 << Call->getSourceRange();
796 return true;
797 }
798
799 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
800 if (ChainResult.isInvalid())
801 return true;
802 if (!ChainResult.get()->getType()->isPointerType()) {
803 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
804 << Chain->getSourceRange();
805 return true;
806 }
807
808 QualType ReturnTy = CE->getCallReturnType(S.Context);
809 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
810 QualType BuiltinTy = S.Context.getFunctionType(
811 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
812 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
813
814 Builtin =
815 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
816
817 BuiltinCall->setType(CE->getType());
818 BuiltinCall->setValueKind(CE->getValueKind());
819 BuiltinCall->setObjectKind(CE->getObjectKind());
820 BuiltinCall->setCallee(Builtin);
821 BuiltinCall->setArg(1, ChainResult.get());
822
823 return false;
824}
825
826namespace {
827
828class ScanfDiagnosticFormatHandler
830 // Accepts the argument index (relative to the first destination index) of the
831 // argument whose size we want.
832 using ComputeSizeFunction =
833 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
834
835 // Accepts the argument index (relative to the first destination index), the
836 // destination size, and the source size).
837 using DiagnoseFunction =
838 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
839
840 ComputeSizeFunction ComputeSizeArgument;
841 DiagnoseFunction Diagnose;
842
843public:
844 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
845 DiagnoseFunction Diagnose)
846 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
847
848 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
849 const char *StartSpecifier,
850 unsigned specifierLen) override {
851 if (!FS.consumesDataArgument())
852 return true;
853
854 unsigned NulByte = 0;
855 switch ((FS.getConversionSpecifier().getKind())) {
856 default:
857 return true;
860 NulByte = 1;
861 break;
863 break;
864 }
865
866 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
867 if (FW.getHowSpecified() !=
868 analyze_format_string::OptionalAmount::HowSpecified::Constant)
869 return true;
870
871 unsigned SourceSize = FW.getConstantAmount() + NulByte;
872
873 std::optional<llvm::APSInt> DestSizeAPS =
874 ComputeSizeArgument(FS.getArgIndex());
875 if (!DestSizeAPS)
876 return true;
877
878 unsigned DestSize = DestSizeAPS->getZExtValue();
879
880 if (DestSize < SourceSize)
881 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
882
883 return true;
884 }
885};
886
887class EstimateSizeFormatHandler
889 size_t Size;
890 /// Whether the format string contains Linux kernel's format specifier
891 /// extension.
892 bool IsKernelCompatible = true;
893
894public:
895 EstimateSizeFormatHandler(StringRef Format)
896 : Size(std::min(Format.find(0), Format.size()) +
897 1 /* null byte always written by sprintf */) {}
898
899 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
900 const char *, unsigned SpecifierLen,
901 const TargetInfo &) override {
902
903 const size_t FieldWidth = computeFieldWidth(FS);
904 const size_t Precision = computePrecision(FS);
905
906 // The actual format.
907 switch (FS.getConversionSpecifier().getKind()) {
908 // Just a char.
911 Size += std::max(FieldWidth, (size_t)1);
912 break;
913 // Just an integer.
923 Size += std::max(FieldWidth, Precision);
924 break;
925
926 // %g style conversion switches between %f or %e style dynamically.
927 // %g removes trailing zeros, and does not print decimal point if there are
928 // no digits that follow it. Thus %g can print a single digit.
929 // FIXME: If it is alternative form:
930 // For g and G conversions, trailing zeros are not removed from the result.
933 Size += 1;
934 break;
935
936 // Floating point number in the form '[+]ddd.ddd'.
939 Size += std::max(FieldWidth, 1 /* integer part */ +
940 (Precision ? 1 + Precision
941 : 0) /* period + decimal */);
942 break;
943
944 // Floating point number in the form '[-]d.ddde[+-]dd'.
947 Size +=
948 std::max(FieldWidth,
949 1 /* integer part */ +
950 (Precision ? 1 + Precision : 0) /* period + decimal */ +
951 1 /* e or E letter */ + 2 /* exponent */);
952 break;
953
954 // Floating point number in the form '[-]0xh.hhhhp±dd'.
957 Size +=
958 std::max(FieldWidth,
959 2 /* 0x */ + 1 /* integer part */ +
960 (Precision ? 1 + Precision : 0) /* period + decimal */ +
961 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
962 break;
963
964 // Just a string.
967 Size += FieldWidth;
968 break;
969
970 // Just a pointer in the form '0xddd'.
972 // Linux kernel has its own extesion for `%p` specifier.
973 // Kernel Document:
974 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
975 IsKernelCompatible = false;
976 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
977 break;
978
979 // A plain percent.
981 Size += 1;
982 break;
983
984 default:
985 break;
986 }
987
988 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
989
990 if (FS.hasAlternativeForm()) {
991 switch (FS.getConversionSpecifier().getKind()) {
992 // For o conversion, it increases the precision, if and only if necessary,
993 // to force the first digit of the result to be a zero
994 // (if the value and precision are both 0, a single 0 is printed)
996 // For b conversion, a nonzero result has 0b prefixed to it.
998 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
999 // it.
1002 // Note: even when the prefix is added, if
1003 // (prefix_width <= FieldWidth - formatted_length) holds,
1004 // the prefix does not increase the format
1005 // size. e.g.(("%#3x", 0xf) is "0xf")
1006
1007 // If the result is zero, o, b, x, X adds nothing.
1008 break;
1009 // For a, A, e, E, f, F, g, and G conversions,
1010 // the result of converting a floating-point number always contains a
1011 // decimal-point
1020 Size += (Precision ? 0 : 1);
1021 break;
1022 // For other conversions, the behavior is undefined.
1023 default:
1024 break;
1025 }
1026 }
1027 assert(SpecifierLen <= Size && "no underflow");
1028 Size -= SpecifierLen;
1029 return true;
1030 }
1031
1032 size_t getSizeLowerBound() const { return Size; }
1033 bool isKernelCompatible() const { return IsKernelCompatible; }
1034
1035private:
1036 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1037 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1038 size_t FieldWidth = 0;
1040 FieldWidth = FW.getConstantAmount();
1041 return FieldWidth;
1042 }
1043
1044 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1045 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1046 size_t Precision = 0;
1047
1048 // See man 3 printf for default precision value based on the specifier.
1049 switch (FW.getHowSpecified()) {
1051 switch (FS.getConversionSpecifier().getKind()) {
1052 default:
1053 break;
1057 Precision = 1;
1058 break;
1065 Precision = 1;
1066 break;
1073 Precision = 6;
1074 break;
1076 Precision = 1;
1077 break;
1078 }
1079 break;
1081 Precision = FW.getConstantAmount();
1082 break;
1083 default:
1084 break;
1085 }
1086 return Precision;
1087 }
1088};
1089
1090} // namespace
1091
1092static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1093 StringRef &FormatStrRef, size_t &StrLen,
1094 ASTContext &Context) {
1095 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1096 Format && (Format->isOrdinary() || Format->isUTF8())) {
1097 FormatStrRef = Format->getString();
1098 const ConstantArrayType *T =
1099 Context.getAsConstantArrayType(Format->getType());
1100 assert(T && "String literal not of constant array type!");
1101 size_t TypeSize = T->getZExtSize();
1102 // In case there's a null byte somewhere.
1103 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1104 return true;
1105 }
1106 return false;
1107}
1108
1109void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1110 CallExpr *TheCall) {
1111 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1113 return;
1114
1115 bool UseDABAttr = false;
1116 const FunctionDecl *UseDecl = FD;
1117
1118 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1119 if (DABAttr) {
1120 UseDecl = DABAttr->getFunction();
1121 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1122 UseDABAttr = true;
1123 }
1124
1125 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1126
1127 if (!BuiltinID)
1128 return;
1129
1130 const TargetInfo &TI = getASTContext().getTargetInfo();
1131 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1132
1133 auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1134 // If we refer to a diagnose_as_builtin attribute, we need to change the
1135 // argument index to refer to the arguments of the called function. Unless
1136 // the index is out of bounds, which presumably means it's a variadic
1137 // function.
1138 if (!UseDABAttr)
1139 return Index;
1140 unsigned DABIndices = DABAttr->argIndices_size();
1141 unsigned NewIndex = Index < DABIndices
1142 ? DABAttr->argIndices_begin()[Index]
1143 : Index - DABIndices + FD->getNumParams();
1144 if (NewIndex >= TheCall->getNumArgs())
1145 return std::nullopt;
1146 return NewIndex;
1147 };
1148
1149 auto ComputeExplicitObjectSizeArgument =
1150 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1151 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1152 if (!IndexOptional)
1153 return std::nullopt;
1154 unsigned NewIndex = *IndexOptional;
1156 Expr *SizeArg = TheCall->getArg(NewIndex);
1157 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
1158 return std::nullopt;
1159 llvm::APSInt Integer = Result.Val.getInt();
1160 Integer.setIsUnsigned(true);
1161 return Integer;
1162 };
1163
1164 auto ComputeSizeArgument =
1165 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1166 // If the parameter has a pass_object_size attribute, then we should use its
1167 // (potentially) more strict checking mode. Otherwise, conservatively assume
1168 // type 0.
1169 int BOSType = 0;
1170 // This check can fail for variadic functions.
1171 if (Index < FD->getNumParams()) {
1172 if (const auto *POS =
1173 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1174 BOSType = POS->getType();
1175 }
1176
1177 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1178 if (!IndexOptional)
1179 return std::nullopt;
1180 unsigned NewIndex = *IndexOptional;
1181
1182 if (NewIndex >= TheCall->getNumArgs())
1183 return std::nullopt;
1184
1185 const Expr *ObjArg = TheCall->getArg(NewIndex);
1187 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
1188 return std::nullopt;
1189
1190 // Get the object size in the target's size_t width.
1191 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
1192 };
1193
1194 auto ComputeStrLenArgument =
1195 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1196 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1197 if (!IndexOptional)
1198 return std::nullopt;
1199 unsigned NewIndex = *IndexOptional;
1200
1201 const Expr *ObjArg = TheCall->getArg(NewIndex);
1203 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
1204 return std::nullopt;
1205 // Add 1 for null byte.
1206 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
1207 };
1208
1209 std::optional<llvm::APSInt> SourceSize;
1210 std::optional<llvm::APSInt> DestinationSize;
1211 unsigned DiagID = 0;
1212 bool IsChkVariant = false;
1213
1214 auto GetFunctionName = [&]() {
1215 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
1216 // Skim off the details of whichever builtin was called to produce a better
1217 // diagnostic, as it's unlikely that the user wrote the __builtin
1218 // explicitly.
1219 if (IsChkVariant) {
1220 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
1221 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
1222 } else {
1223 FunctionName.consume_front("__builtin_");
1224 }
1225 return FunctionName;
1226 };
1227
1228 switch (BuiltinID) {
1229 default:
1230 return;
1231 case Builtin::BI__builtin_strcpy:
1232 case Builtin::BIstrcpy: {
1233 DiagID = diag::warn_fortify_strlen_overflow;
1234 SourceSize = ComputeStrLenArgument(1);
1235 DestinationSize = ComputeSizeArgument(0);
1236 break;
1237 }
1238
1239 case Builtin::BI__builtin___strcpy_chk: {
1240 DiagID = diag::warn_fortify_strlen_overflow;
1241 SourceSize = ComputeStrLenArgument(1);
1242 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1243 IsChkVariant = true;
1244 break;
1245 }
1246
1247 case Builtin::BIscanf:
1248 case Builtin::BIfscanf:
1249 case Builtin::BIsscanf: {
1250 unsigned FormatIndex = 1;
1251 unsigned DataIndex = 2;
1252 if (BuiltinID == Builtin::BIscanf) {
1253 FormatIndex = 0;
1254 DataIndex = 1;
1255 }
1256
1257 const auto *FormatExpr =
1258 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1259
1260 StringRef FormatStrRef;
1261 size_t StrLen;
1262 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1263 return;
1264
1265 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1266 unsigned SourceSize) {
1267 DiagID = diag::warn_fortify_scanf_overflow;
1268 unsigned Index = ArgIndex + DataIndex;
1269 StringRef FunctionName = GetFunctionName();
1270 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1271 PDiag(DiagID) << FunctionName << (Index + 1)
1272 << DestSize << SourceSize);
1273 };
1274
1275 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1276 return ComputeSizeArgument(Index + DataIndex);
1277 };
1278 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1279 const char *FormatBytes = FormatStrRef.data();
1281 FormatBytes + StrLen, getLangOpts(),
1283
1284 // Unlike the other cases, in this one we have already issued the diagnostic
1285 // here, so no need to continue (because unlike the other cases, here the
1286 // diagnostic refers to the argument number).
1287 return;
1288 }
1289
1290 case Builtin::BIsprintf:
1291 case Builtin::BI__builtin___sprintf_chk: {
1292 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1293 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1294
1295 StringRef FormatStrRef;
1296 size_t StrLen;
1297 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1298 EstimateSizeFormatHandler H(FormatStrRef);
1299 const char *FormatBytes = FormatStrRef.data();
1301 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1302 Context.getTargetInfo(), false)) {
1303 DiagID = H.isKernelCompatible()
1304 ? diag::warn_format_overflow
1305 : diag::warn_format_overflow_non_kprintf;
1306 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1307 .extOrTrunc(SizeTypeWidth);
1308 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1309 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1310 IsChkVariant = true;
1311 } else {
1312 DestinationSize = ComputeSizeArgument(0);
1313 }
1314 break;
1315 }
1316 }
1317 return;
1318 }
1319 case Builtin::BI__builtin___memcpy_chk:
1320 case Builtin::BI__builtin___memmove_chk:
1321 case Builtin::BI__builtin___memset_chk:
1322 case Builtin::BI__builtin___strlcat_chk:
1323 case Builtin::BI__builtin___strlcpy_chk:
1324 case Builtin::BI__builtin___strncat_chk:
1325 case Builtin::BI__builtin___strncpy_chk:
1326 case Builtin::BI__builtin___stpncpy_chk:
1327 case Builtin::BI__builtin___memccpy_chk:
1328 case Builtin::BI__builtin___mempcpy_chk: {
1329 DiagID = diag::warn_builtin_chk_overflow;
1330 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1331 DestinationSize =
1332 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1333 IsChkVariant = true;
1334 break;
1335 }
1336
1337 case Builtin::BI__builtin___snprintf_chk:
1338 case Builtin::BI__builtin___vsnprintf_chk: {
1339 DiagID = diag::warn_builtin_chk_overflow;
1340 SourceSize = ComputeExplicitObjectSizeArgument(1);
1341 DestinationSize = ComputeExplicitObjectSizeArgument(3);
1342 IsChkVariant = true;
1343 break;
1344 }
1345
1346 case Builtin::BIstrncat:
1347 case Builtin::BI__builtin_strncat:
1348 case Builtin::BIstrncpy:
1349 case Builtin::BI__builtin_strncpy:
1350 case Builtin::BIstpncpy:
1351 case Builtin::BI__builtin_stpncpy: {
1352 // Whether these functions overflow depends on the runtime strlen of the
1353 // string, not just the buffer size, so emitting the "always overflow"
1354 // diagnostic isn't quite right. We should still diagnose passing a buffer
1355 // size larger than the destination buffer though; this is a runtime abort
1356 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1357 DiagID = diag::warn_fortify_source_size_mismatch;
1358 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1359 DestinationSize = ComputeSizeArgument(0);
1360 break;
1361 }
1362
1363 case Builtin::BImemcpy:
1364 case Builtin::BI__builtin_memcpy:
1365 case Builtin::BImemmove:
1366 case Builtin::BI__builtin_memmove:
1367 case Builtin::BImemset:
1368 case Builtin::BI__builtin_memset:
1369 case Builtin::BImempcpy:
1370 case Builtin::BI__builtin_mempcpy: {
1371 DiagID = diag::warn_fortify_source_overflow;
1372 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1373 DestinationSize = ComputeSizeArgument(0);
1374 break;
1375 }
1376 case Builtin::BIsnprintf:
1377 case Builtin::BI__builtin_snprintf:
1378 case Builtin::BIvsnprintf:
1379 case Builtin::BI__builtin_vsnprintf: {
1380 DiagID = diag::warn_fortify_source_size_mismatch;
1381 SourceSize = ComputeExplicitObjectSizeArgument(1);
1382 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1383 StringRef FormatStrRef;
1384 size_t StrLen;
1385 if (SourceSize &&
1386 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1387 EstimateSizeFormatHandler H(FormatStrRef);
1388 const char *FormatBytes = FormatStrRef.data();
1390 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1391 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1392 llvm::APSInt FormatSize =
1393 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1394 .extOrTrunc(SizeTypeWidth);
1395 if (FormatSize > *SourceSize && *SourceSize != 0) {
1396 unsigned TruncationDiagID =
1397 H.isKernelCompatible() ? diag::warn_format_truncation
1398 : diag::warn_format_truncation_non_kprintf;
1399 SmallString<16> SpecifiedSizeStr;
1400 SmallString<16> FormatSizeStr;
1401 SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1402 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1403 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1404 PDiag(TruncationDiagID)
1405 << GetFunctionName() << SpecifiedSizeStr
1406 << FormatSizeStr);
1407 }
1408 }
1409 }
1410 DestinationSize = ComputeSizeArgument(0);
1411 }
1412 }
1413
1414 if (!SourceSize || !DestinationSize ||
1415 llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1416 return;
1417
1418 StringRef FunctionName = GetFunctionName();
1419
1420 SmallString<16> DestinationStr;
1421 SmallString<16> SourceStr;
1422 DestinationSize->toString(DestinationStr, /*Radix=*/10);
1423 SourceSize->toString(SourceStr, /*Radix=*/10);
1424 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1425 PDiag(DiagID)
1426 << FunctionName << DestinationStr << SourceStr);
1427}
1428
1429static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1430 Scope::ScopeFlags NeededScopeFlags,
1431 unsigned DiagID) {
1432 // Scopes aren't available during instantiation. Fortunately, builtin
1433 // functions cannot be template args so they cannot be formed through template
1434 // instantiation. Therefore checking once during the parse is sufficient.
1435 if (SemaRef.inTemplateInstantiation())
1436 return false;
1437
1438 Scope *S = SemaRef.getCurScope();
1439 while (S && !S->isSEHExceptScope())
1440 S = S->getParent();
1441 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1442 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1443 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1444 << DRE->getDecl()->getIdentifier();
1445 return true;
1446 }
1447
1448 return false;
1449}
1450
1451static inline bool isBlockPointer(Expr *Arg) {
1452 return Arg->getType()->isBlockPointerType();
1453}
1454
1455/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
1456/// void*, which is a requirement of device side enqueue.
1457static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
1458 const BlockPointerType *BPT =
1459 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1460 ArrayRef<QualType> Params =
1461 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
1462 unsigned ArgCounter = 0;
1463 bool IllegalParams = false;
1464 // Iterate through the block parameters until either one is found that is not
1465 // a local void*, or the block is valid.
1466 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
1467 I != E; ++I, ++ArgCounter) {
1468 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
1469 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
1471 // Get the location of the error. If a block literal has been passed
1472 // (BlockExpr) then we can point straight to the offending argument,
1473 // else we just point to the variable reference.
1474 SourceLocation ErrorLoc;
1475 if (isa<BlockExpr>(BlockArg)) {
1476 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
1477 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
1478 } else if (isa<DeclRefExpr>(BlockArg)) {
1479 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
1480 }
1481 S.Diag(ErrorLoc,
1482 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
1483 IllegalParams = true;
1484 }
1485 }
1486
1487 return IllegalParams;
1488}
1489
1491 // OpenCL device can support extension but not the feature as extension
1492 // requires subgroup independent forward progress, but subgroup independent
1493 // forward progress is optional in OpenCL C 3.0 __opencl_c_subgroups feature.
1494 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts()) &&
1495 !S.getOpenCLOptions().isSupported("__opencl_c_subgroups",
1496 S.getLangOpts())) {
1497 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
1498 << 1 << Call->getDirectCallee()
1499 << "cl_khr_subgroups or __opencl_c_subgroups";
1500 return true;
1501 }
1502 return false;
1503}
1504
1505static bool OpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
1506 if (checkArgCount(S, TheCall, 2))
1507 return true;
1508
1509 if (checkOpenCLSubgroupExt(S, TheCall))
1510 return true;
1511
1512 // First argument is an ndrange_t type.
1513 Expr *NDRangeArg = TheCall->getArg(0);
1514 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1515 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1516 << TheCall->getDirectCallee() << "'ndrange_t'";
1517 return true;
1518 }
1519
1520 Expr *BlockArg = TheCall->getArg(1);
1521 if (!isBlockPointer(BlockArg)) {
1522 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1523 << TheCall->getDirectCallee() << "block";
1524 return true;
1525 }
1526 return checkOpenCLBlockArgs(S, BlockArg);
1527}
1528
1529/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
1530/// get_kernel_work_group_size
1531/// and get_kernel_preferred_work_group_size_multiple builtin functions.
1533 if (checkArgCount(S, TheCall, 1))
1534 return true;
1535
1536 Expr *BlockArg = TheCall->getArg(0);
1537 if (!isBlockPointer(BlockArg)) {
1538 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1539 << TheCall->getDirectCallee() << "block";
1540 return true;
1541 }
1542 return checkOpenCLBlockArgs(S, BlockArg);
1543}
1544
1545/// Diagnose integer type and any valid implicit conversion to it.
1546static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
1547 const QualType &IntType);
1548
1550 unsigned Start, unsigned End) {
1551 bool IllegalParams = false;
1552 for (unsigned I = Start; I <= End; ++I)
1553 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
1554 S.Context.getSizeType());
1555 return IllegalParams;
1556}
1557
1558/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
1559/// 'local void*' parameter of passed block.
1561 Expr *BlockArg,
1562 unsigned NumNonVarArgs) {
1563 const BlockPointerType *BPT =
1564 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1565 unsigned NumBlockParams =
1566 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
1567 unsigned TotalNumArgs = TheCall->getNumArgs();
1568
1569 // For each argument passed to the block, a corresponding uint needs to
1570 // be passed to describe the size of the local memory.
1571 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
1572 S.Diag(TheCall->getBeginLoc(),
1573 diag::err_opencl_enqueue_kernel_local_size_args);
1574 return true;
1575 }
1576
1577 // Check that the sizes of the local memory are specified by integers.
1578 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
1579 TotalNumArgs - 1);
1580}
1581
1582/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
1583/// overload formats specified in Table 6.13.17.1.
1584/// int enqueue_kernel(queue_t queue,
1585/// kernel_enqueue_flags_t flags,
1586/// const ndrange_t ndrange,
1587/// void (^block)(void))
1588/// int enqueue_kernel(queue_t queue,
1589/// kernel_enqueue_flags_t flags,
1590/// const ndrange_t ndrange,
1591/// uint num_events_in_wait_list,
1592/// clk_event_t *event_wait_list,
1593/// clk_event_t *event_ret,
1594/// void (^block)(void))
1595/// int enqueue_kernel(queue_t queue,
1596/// kernel_enqueue_flags_t flags,
1597/// const ndrange_t ndrange,
1598/// void (^block)(local void*, ...),
1599/// uint size0, ...)
1600/// int enqueue_kernel(queue_t queue,
1601/// kernel_enqueue_flags_t flags,
1602/// const ndrange_t ndrange,
1603/// uint num_events_in_wait_list,
1604/// clk_event_t *event_wait_list,
1605/// clk_event_t *event_ret,
1606/// void (^block)(local void*, ...),
1607/// uint size0, ...)
1608static bool OpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
1609 unsigned NumArgs = TheCall->getNumArgs();
1610
1611 if (NumArgs < 4) {
1612 S.Diag(TheCall->getBeginLoc(),
1613 diag::err_typecheck_call_too_few_args_at_least)
1614 << 0 << 4 << NumArgs << /*is non object*/ 0;
1615 return true;
1616 }
1617
1618 Expr *Arg0 = TheCall->getArg(0);
1619 Expr *Arg1 = TheCall->getArg(1);
1620 Expr *Arg2 = TheCall->getArg(2);
1621 Expr *Arg3 = TheCall->getArg(3);
1622
1623 // First argument always needs to be a queue_t type.
1624 if (!Arg0->getType()->isQueueT()) {
1625 S.Diag(TheCall->getArg(0)->getBeginLoc(),
1626 diag::err_opencl_builtin_expected_type)
1627 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
1628 return true;
1629 }
1630
1631 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
1632 if (!Arg1->getType()->isIntegerType()) {
1633 S.Diag(TheCall->getArg(1)->getBeginLoc(),
1634 diag::err_opencl_builtin_expected_type)
1635 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
1636 return true;
1637 }
1638
1639 // Third argument is always an ndrange_t type.
1640 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1641 S.Diag(TheCall->getArg(2)->getBeginLoc(),
1642 diag::err_opencl_builtin_expected_type)
1643 << TheCall->getDirectCallee() << "'ndrange_t'";
1644 return true;
1645 }
1646
1647 // With four arguments, there is only one form that the function could be
1648 // called in: no events and no variable arguments.
1649 if (NumArgs == 4) {
1650 // check that the last argument is the right block type.
1651 if (!isBlockPointer(Arg3)) {
1652 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1653 << TheCall->getDirectCallee() << "block";
1654 return true;
1655 }
1656 // we have a block type, check the prototype
1657 const BlockPointerType *BPT =
1658 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1659 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1660 S.Diag(Arg3->getBeginLoc(),
1661 diag::err_opencl_enqueue_kernel_blocks_no_args);
1662 return true;
1663 }
1664 return false;
1665 }
1666 // we can have block + varargs.
1667 if (isBlockPointer(Arg3))
1668 return (checkOpenCLBlockArgs(S, Arg3) ||
1669 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1670 // last two cases with either exactly 7 args or 7 args and varargs.
1671 if (NumArgs >= 7) {
1672 // check common block argument.
1673 Expr *Arg6 = TheCall->getArg(6);
1674 if (!isBlockPointer(Arg6)) {
1675 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1676 << TheCall->getDirectCallee() << "block";
1677 return true;
1678 }
1679 if (checkOpenCLBlockArgs(S, Arg6))
1680 return true;
1681
1682 // Forth argument has to be any integer type.
1683 if (!Arg3->getType()->isIntegerType()) {
1684 S.Diag(TheCall->getArg(3)->getBeginLoc(),
1685 diag::err_opencl_builtin_expected_type)
1686 << TheCall->getDirectCallee() << "integer";
1687 return true;
1688 }
1689 // check remaining common arguments.
1690 Expr *Arg4 = TheCall->getArg(4);
1691 Expr *Arg5 = TheCall->getArg(5);
1692
1693 // Fifth argument is always passed as a pointer to clk_event_t.
1694 if (!Arg4->isNullPointerConstant(S.Context,
1697 S.Diag(TheCall->getArg(4)->getBeginLoc(),
1698 diag::err_opencl_builtin_expected_type)
1699 << TheCall->getDirectCallee()
1701 return true;
1702 }
1703
1704 // Sixth argument is always passed as a pointer to clk_event_t.
1705 if (!Arg5->isNullPointerConstant(S.Context,
1707 !(Arg5->getType()->isPointerType() &&
1708 Arg5->getType()->getPointeeType()->isClkEventT())) {
1709 S.Diag(TheCall->getArg(5)->getBeginLoc(),
1710 diag::err_opencl_builtin_expected_type)
1711 << TheCall->getDirectCallee()
1713 return true;
1714 }
1715
1716 if (NumArgs == 7)
1717 return false;
1718
1719 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1720 }
1721
1722 // None of the specific case has been detected, give generic error
1723 S.Diag(TheCall->getBeginLoc(),
1724 diag::err_opencl_enqueue_kernel_incorrect_args);
1725 return true;
1726}
1727
1728/// Returns OpenCL access qual.
1729static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1730 return D->getAttr<OpenCLAccessAttr>();
1731}
1732
1733/// Returns true if pipe element type is different from the pointer.
1735 const Expr *Arg0 = Call->getArg(0);
1736 // First argument type should always be pipe.
1737 if (!Arg0->getType()->isPipeType()) {
1738 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1739 << Call->getDirectCallee() << Arg0->getSourceRange();
1740 return true;
1741 }
1742 OpenCLAccessAttr *AccessQual =
1743 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1744 // Validates the access qualifier is compatible with the call.
1745 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1746 // read_only and write_only, and assumed to be read_only if no qualifier is
1747 // specified.
1748 switch (Call->getDirectCallee()->getBuiltinID()) {
1749 case Builtin::BIread_pipe:
1750 case Builtin::BIreserve_read_pipe:
1751 case Builtin::BIcommit_read_pipe:
1752 case Builtin::BIwork_group_reserve_read_pipe:
1753 case Builtin::BIsub_group_reserve_read_pipe:
1754 case Builtin::BIwork_group_commit_read_pipe:
1755 case Builtin::BIsub_group_commit_read_pipe:
1756 if (!(!AccessQual || AccessQual->isReadOnly())) {
1757 S.Diag(Arg0->getBeginLoc(),
1758 diag::err_opencl_builtin_pipe_invalid_access_modifier)
1759 << "read_only" << Arg0->getSourceRange();
1760 return true;
1761 }
1762 break;
1763 case Builtin::BIwrite_pipe:
1764 case Builtin::BIreserve_write_pipe:
1765 case Builtin::BIcommit_write_pipe:
1766 case Builtin::BIwork_group_reserve_write_pipe:
1767 case Builtin::BIsub_group_reserve_write_pipe:
1768 case Builtin::BIwork_group_commit_write_pipe:
1769 case Builtin::BIsub_group_commit_write_pipe:
1770 if (!(AccessQual && AccessQual->isWriteOnly())) {
1771 S.Diag(Arg0->getBeginLoc(),
1772 diag::err_opencl_builtin_pipe_invalid_access_modifier)
1773 << "write_only" << Arg0->getSourceRange();
1774 return true;
1775 }
1776 break;
1777 default:
1778 break;
1779 }
1780 return false;
1781}
1782
1783/// Returns true if pipe element type is different from the pointer.
1784static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1785 const Expr *Arg0 = Call->getArg(0);
1786 const Expr *ArgIdx = Call->getArg(Idx);
1787 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1788 const QualType EltTy = PipeTy->getElementType();
1789 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1790 // The Idx argument should be a pointer and the type of the pointer and
1791 // the type of pipe element should also be the same.
1792 if (!ArgTy ||
1794 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1795 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1796 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1797 << ArgIdx->getType() << ArgIdx->getSourceRange();
1798 return true;
1799 }
1800 return false;
1801}
1802
1803// Performs semantic analysis for the read/write_pipe call.
1804// \param S Reference to the semantic analyzer.
1805// \param Call A pointer to the builtin call.
1806// \return True if a semantic error has been found, false otherwise.
1807static bool BuiltinRWPipe(Sema &S, CallExpr *Call) {
1808 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1809 // functions have two forms.
1810 switch (Call->getNumArgs()) {
1811 case 2:
1812 if (checkOpenCLPipeArg(S, Call))
1813 return true;
1814 // The call with 2 arguments should be
1815 // read/write_pipe(pipe T, T*).
1816 // Check packet type T.
1818 return true;
1819 break;
1820
1821 case 4: {
1822 if (checkOpenCLPipeArg(S, Call))
1823 return true;
1824 // The call with 4 arguments should be
1825 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1826 // Check reserve_id_t.
1827 if (!Call->getArg(1)->getType()->isReserveIDT()) {
1828 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1829 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1830 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1831 return true;
1832 }
1833
1834 // Check the index.
1835 const Expr *Arg2 = Call->getArg(2);
1836 if (!Arg2->getType()->isIntegerType() &&
1837 !Arg2->getType()->isUnsignedIntegerType()) {
1838 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1839 << Call->getDirectCallee() << S.Context.UnsignedIntTy
1840 << Arg2->getType() << Arg2->getSourceRange();
1841 return true;
1842 }
1843
1844 // Check packet type T.
1846 return true;
1847 } break;
1848 default:
1849 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1850 << Call->getDirectCallee() << Call->getSourceRange();
1851 return true;
1852 }
1853
1854 return false;
1855}
1856
1857// Performs a semantic analysis on the {work_group_/sub_group_
1858// /_}reserve_{read/write}_pipe
1859// \param S Reference to the semantic analyzer.
1860// \param Call The call to the builtin function to be analyzed.
1861// \return True if a semantic error was found, false otherwise.
1863 if (checkArgCount(S, Call, 2))
1864 return true;
1865
1866 if (checkOpenCLPipeArg(S, Call))
1867 return true;
1868
1869 // Check the reserve size.
1870 if (!Call->getArg(1)->getType()->isIntegerType() &&
1871 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1872 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1873 << Call->getDirectCallee() << S.Context.UnsignedIntTy
1874 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1875 return true;
1876 }
1877
1878 // Since return type of reserve_read/write_pipe built-in function is
1879 // reserve_id_t, which is not defined in the builtin def file , we used int
1880 // as return type and need to override the return type of these functions.
1881 Call->setType(S.Context.OCLReserveIDTy);
1882
1883 return false;
1884}
1885
1886// Performs a semantic analysis on {work_group_/sub_group_
1887// /_}commit_{read/write}_pipe
1888// \param S Reference to the semantic analyzer.
1889// \param Call The call to the builtin function to be analyzed.
1890// \return True if a semantic error was found, false otherwise.
1892 if (checkArgCount(S, Call, 2))
1893 return true;
1894
1895 if (checkOpenCLPipeArg(S, Call))
1896 return true;
1897
1898 // Check reserve_id_t.
1899 if (!Call->getArg(1)->getType()->isReserveIDT()) {
1900 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1901 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1902 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1903 return true;
1904 }
1905
1906 return false;
1907}
1908
1909// Performs a semantic analysis on the call to built-in Pipe
1910// Query Functions.
1911// \param S Reference to the semantic analyzer.
1912// \param Call The call to the builtin function to be analyzed.
1913// \return True if a semantic error was found, false otherwise.
1915 if (checkArgCount(S, Call, 1))
1916 return true;
1917
1918 if (!Call->getArg(0)->getType()->isPipeType()) {
1919 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1920 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1921 return true;
1922 }
1923
1924 return false;
1925}
1926
1927// OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1928// Performs semantic analysis for the to_global/local/private call.
1929// \param S Reference to the semantic analyzer.
1930// \param BuiltinID ID of the builtin function.
1931// \param Call A pointer to the builtin call.
1932// \return True if a semantic error has been found, false otherwise.
1933static bool OpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, CallExpr *Call) {
1934 if (checkArgCount(S, Call, 1))
1935 return true;
1936
1937 auto RT = Call->getArg(0)->getType();
1938 if (!RT->isPointerType() || RT->getPointeeType()
1939 .getAddressSpace() == LangAS::opencl_constant) {
1940 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1941 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1942 return true;
1943 }
1944
1945 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1946 S.Diag(Call->getArg(0)->getBeginLoc(),
1947 diag::warn_opencl_generic_address_space_arg)
1948 << Call->getDirectCallee()->getNameInfo().getAsString()
1949 << Call->getArg(0)->getSourceRange();
1950 }
1951
1952 RT = RT->getPointeeType();
1953 auto Qual = RT.getQualifiers();
1954 switch (BuiltinID) {
1955 case Builtin::BIto_global:
1956 Qual.setAddressSpace(LangAS::opencl_global);
1957 break;
1958 case Builtin::BIto_local:
1959 Qual.setAddressSpace(LangAS::opencl_local);
1960 break;
1961 case Builtin::BIto_private:
1962 Qual.setAddressSpace(LangAS::opencl_private);
1963 break;
1964 default:
1965 llvm_unreachable("Invalid builtin function");
1966 }
1968 RT.getUnqualifiedType(), Qual)));
1969
1970 return false;
1971}
1972
1973namespace {
1974enum PointerAuthOpKind {
1975 PAO_Strip,
1976 PAO_Sign,
1977 PAO_Auth,
1978 PAO_SignGeneric,
1979 PAO_Discriminator,
1980 PAO_BlendPointer,
1981 PAO_BlendInteger
1982};
1983}
1984
1985static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1986 if (S.getLangOpts().PointerAuthIntrinsics)
1987 return false;
1988
1989 S.Diag(E->getExprLoc(), diag::err_ptrauth_disabled) << E->getSourceRange();
1990 return true;
1991}
1992
1993static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1994 // Convert it to type 'int'.
1995 if (convertArgumentToType(S, Arg, S.Context.IntTy))
1996 return true;
1997
1998 // Value-dependent expressions are okay; wait for template instantiation.
1999 if (Arg->isValueDependent())
2000 return false;
2001
2002 unsigned KeyValue;
2003 return S.checkConstantPointerAuthKey(Arg, KeyValue);
2004}
2005
2007 // Attempt to constant-evaluate the expression.
2008 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
2009 if (!KeyValue) {
2010 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
2011 << 0 << Arg->getSourceRange();
2012 return true;
2013 }
2014
2015 // Ask the target to validate the key parameter.
2016 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
2018 {
2019 llvm::raw_svector_ostream Str(Value);
2020 Str << *KeyValue;
2021 }
2022
2023 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
2024 << Value << Arg->getSourceRange();
2025 return true;
2026 }
2027
2028 Result = KeyValue->getZExtValue();
2029 return false;
2030}
2031
2032static bool checkPointerAuthValue(Sema &S, Expr *&Arg,
2033 PointerAuthOpKind OpKind) {
2034 if (Arg->hasPlaceholderType()) {
2036 if (R.isInvalid())
2037 return true;
2038 Arg = R.get();
2039 }
2040
2041 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
2042 return OpKind != PAO_BlendInteger;
2043 };
2044 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
2045 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
2046 OpKind == PAO_SignGeneric;
2047 };
2048
2049 // Require the value to have the right range of type.
2050 QualType ExpectedTy;
2051 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
2052 ExpectedTy = Arg->getType().getUnqualifiedType();
2053 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
2054 ExpectedTy = S.Context.VoidPtrTy;
2055 } else if (AllowsInteger(OpKind) &&
2057 ExpectedTy = S.Context.getUIntPtrType();
2058
2059 } else {
2060 // Diagnose the failures.
2061 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
2062 << unsigned(OpKind == PAO_Discriminator ? 1
2063 : OpKind == PAO_BlendPointer ? 2
2064 : OpKind == PAO_BlendInteger ? 3
2065 : 0)
2066 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
2067 << Arg->getType() << Arg->getSourceRange();
2068 return true;
2069 }
2070
2071 // Convert to that type. This should just be an lvalue-to-rvalue
2072 // conversion.
2073 if (convertArgumentToType(S, Arg, ExpectedTy))
2074 return true;
2075
2076 // Warn about null pointers for non-generic sign and auth operations.
2077 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
2079 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
2080 ? diag::warn_ptrauth_sign_null_pointer
2081 : diag::warn_ptrauth_auth_null_pointer)
2082 << Arg->getSourceRange();
2083 }
2084
2085 return false;
2086}
2087
2089 if (checkArgCount(S, Call, 2))
2090 return ExprError();
2092 return ExprError();
2093 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
2094 checkPointerAuthKey(S, Call->getArgs()[1]))
2095 return ExprError();
2096
2097 Call->setType(Call->getArgs()[0]->getType());
2098 return Call;
2099}
2100
2102 if (checkArgCount(S, Call, 2))
2103 return ExprError();
2105 return ExprError();
2106 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
2107 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
2108 return ExprError();
2109
2110 Call->setType(S.Context.getUIntPtrType());
2111 return Call;
2112}
2113
2115 if (checkArgCount(S, Call, 2))
2116 return ExprError();
2118 return ExprError();
2119 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
2120 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
2121 return ExprError();
2122
2123 Call->setType(S.Context.getUIntPtrType());
2124 return Call;
2125}
2126
2128 PointerAuthOpKind OpKind) {
2129 if (checkArgCount(S, Call, 3))
2130 return ExprError();
2132 return ExprError();
2133 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind) ||
2134 checkPointerAuthKey(S, Call->getArgs()[1]) ||
2135 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator))
2136 return ExprError();
2137
2138 Call->setType(Call->getArgs()[0]->getType());
2139 return Call;
2140}
2141
2143 if (checkArgCount(S, Call, 5))
2144 return ExprError();
2146 return ExprError();
2147 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
2148 checkPointerAuthKey(S, Call->getArgs()[1]) ||
2149 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
2150 checkPointerAuthKey(S, Call->getArgs()[3]) ||
2151 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
2152 return ExprError();
2153
2154 Call->setType(Call->getArgs()[0]->getType());
2155 return Call;
2156}
2157
2159 if (checkArgCount(S, TheCall, 1))
2160 return ExprError();
2161
2162 // Compute __builtin_launder's parameter type from the argument.
2163 // The parameter type is:
2164 // * The type of the argument if it's not an array or function type,
2165 // Otherwise,
2166 // * The decayed argument type.
2167 QualType ParamTy = [&]() {
2168 QualType ArgTy = TheCall->getArg(0)->getType();
2169 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
2170 return S.Context.getPointerType(Ty->getElementType());
2171 if (ArgTy->isFunctionType()) {
2172 return S.Context.getPointerType(ArgTy);
2173 }
2174 return ArgTy;
2175 }();
2176
2177 TheCall->setType(ParamTy);
2178
2179 auto DiagSelect = [&]() -> std::optional<unsigned> {
2180 if (!ParamTy->isPointerType())
2181 return 0;
2182 if (ParamTy->isFunctionPointerType())
2183 return 1;
2184 if (ParamTy->isVoidPointerType())
2185 return 2;
2186 return std::optional<unsigned>{};
2187 }();
2188 if (DiagSelect) {
2189 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
2190 << *DiagSelect << TheCall->getSourceRange();
2191 return ExprError();
2192 }
2193
2194 // We either have an incomplete class type, or we have a class template
2195 // whose instantiation has not been forced. Example:
2196 //
2197 // template <class T> struct Foo { T value; };
2198 // Foo<int> *p = nullptr;
2199 // auto *d = __builtin_launder(p);
2200 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
2201 diag::err_incomplete_type))
2202 return ExprError();
2203
2204 assert(ParamTy->getPointeeType()->isObjectType() &&
2205 "Unhandled non-object pointer case");
2206
2207 InitializedEntity Entity =
2209 ExprResult Arg =
2210 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
2211 if (Arg.isInvalid())
2212 return ExprError();
2213 TheCall->setArg(0, Arg.get());
2214
2215 return TheCall;
2216}
2217
2218// Emit an error and return true if the current object format type is in the
2219// list of unsupported types.
2221 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2222 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2223 llvm::Triple::ObjectFormatType CurObjFormat =
2224 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2225 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2226 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2227 << TheCall->getSourceRange();
2228 return true;
2229 }
2230 return false;
2231}
2232
2233// Emit an error and return true if the current architecture is not in the list
2234// of supported architectures.
2235static bool
2236CheckBuiltinTargetInSupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2237 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2238 llvm::Triple::ArchType CurArch =
2239 S.getASTContext().getTargetInfo().getTriple().getArch();
2240 if (llvm::is_contained(SupportedArchs, CurArch))
2241 return false;
2242 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2243 << TheCall->getSourceRange();
2244 return true;
2245}
2246
2247static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2248 SourceLocation CallSiteLoc);
2249
2250bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2251 CallExpr *TheCall) {
2252 switch (TI.getTriple().getArch()) {
2253 default:
2254 // Some builtins don't require additional checking, so just consider these
2255 // acceptable.
2256 return false;
2257 case llvm::Triple::arm:
2258 case llvm::Triple::armeb:
2259 case llvm::Triple::thumb:
2260 case llvm::Triple::thumbeb:
2261 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2262 case llvm::Triple::aarch64:
2263 case llvm::Triple::aarch64_32:
2264 case llvm::Triple::aarch64_be:
2265 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2266 case llvm::Triple::bpfeb:
2267 case llvm::Triple::bpfel:
2268 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2269 case llvm::Triple::hexagon:
2270 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2271 case llvm::Triple::mips:
2272 case llvm::Triple::mipsel:
2273 case llvm::Triple::mips64:
2274 case llvm::Triple::mips64el:
2275 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2276 case llvm::Triple::systemz:
2277 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2278 case llvm::Triple::x86:
2279 case llvm::Triple::x86_64:
2280 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
2281 case llvm::Triple::ppc:
2282 case llvm::Triple::ppcle:
2283 case llvm::Triple::ppc64:
2284 case llvm::Triple::ppc64le:
2285 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2286 case llvm::Triple::amdgcn:
2287 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
2288 case llvm::Triple::riscv32:
2289 case llvm::Triple::riscv64:
2290 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2291 case llvm::Triple::loongarch32:
2292 case llvm::Triple::loongarch64:
2293 return CheckLoongArchBuiltinFunctionCall(TI, BuiltinID, TheCall);
2294 case llvm::Triple::wasm32:
2295 case llvm::Triple::wasm64:
2296 return CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2297 case llvm::Triple::nvptx:
2298 case llvm::Triple::nvptx64:
2299 return CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2300 }
2301}
2302
2303// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2304// not a valid type, emit an error message and return true. Otherwise return
2305// false.
2307 QualType ArgTy, int ArgIndex) {
2308 if (!ArgTy->getAs<VectorType>() &&
2310 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2311 << ArgIndex << /* vector, integer or float ty*/ 0 << ArgTy;
2312 }
2313
2314 return false;
2315}
2316
2318 QualType ArgTy, int ArgIndex) {
2319 QualType EltTy = ArgTy;
2320 if (auto *VecTy = EltTy->getAs<VectorType>())
2321 EltTy = VecTy->getElementType();
2322
2323 if (!EltTy->isRealFloatingType()) {
2324 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2325 << ArgIndex << /* vector or float ty*/ 5 << ArgTy;
2326 }
2327
2328 return false;
2329}
2330
2331/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2332/// This checks that the target supports the builtin and that the string
2333/// argument is constant and valid.
2334static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2335 const TargetInfo *AuxTI, unsigned BuiltinID) {
2336 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2337 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2338 "Expecting __builtin_cpu_...");
2339
2340 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2341 const TargetInfo *TheTI = &TI;
2342 auto SupportsBI = [=](const TargetInfo *TInfo) {
2343 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2344 (!IsCPUSupports && TInfo->supportsCpuIs()));
2345 };
2346 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2347 TheTI = AuxTI;
2348
2349 if (IsCPUSupports && !TheTI->supportsCpuSupports())
2350 return S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2351 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2352 if (!IsCPUSupports && !TheTI->supportsCpuIs())
2353 return S.Diag(TheCall->getBeginLoc(),
2354 TI.getTriple().isOSAIX()
2355 ? diag::err_builtin_aix_os_unsupported
2356 : diag::err_builtin_target_unsupported)
2357 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2358
2359 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2360 // Check if the argument is a string literal.
2361 if (!isa<StringLiteral>(Arg))
2362 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2363 << Arg->getSourceRange();
2364
2365 // Check the contents of the string.
2366 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2367 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2368 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2369 << Arg->getSourceRange();
2370 return false;
2371 }
2372 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2373 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2374 << Arg->getSourceRange();
2375 return false;
2376}
2377
2378/// Checks that __builtin_popcountg was called with a single argument, which is
2379/// an unsigned integer.
2380static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2381 if (checkArgCount(S, TheCall, 1))
2382 return true;
2383
2384 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2385 if (ArgRes.isInvalid())
2386 return true;
2387
2388 Expr *Arg = ArgRes.get();
2389 TheCall->setArg(0, Arg);
2390
2391 QualType ArgTy = Arg->getType();
2392
2393 if (!ArgTy->isUnsignedIntegerType()) {
2394 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2395 << 1 << /*unsigned integer ty*/ 7 << ArgTy;
2396 return true;
2397 }
2398 return false;
2399}
2400
2401/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2402/// an unsigned integer, and an optional second argument, which is promoted to
2403/// an 'int'.
2404static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2405 if (checkArgCountRange(S, TheCall, 1, 2))
2406 return true;
2407
2408 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2409 if (Arg0Res.isInvalid())
2410 return true;
2411
2412 Expr *Arg0 = Arg0Res.get();
2413 TheCall->setArg(0, Arg0);
2414
2415 QualType Arg0Ty = Arg0->getType();
2416
2417 if (!Arg0Ty->isUnsignedIntegerType()) {
2418 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2419 << 1 << /*unsigned integer ty*/ 7 << Arg0Ty;
2420 return true;
2421 }
2422
2423 if (TheCall->getNumArgs() > 1) {
2424 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2425 if (Arg1Res.isInvalid())
2426 return true;
2427
2428 Expr *Arg1 = Arg1Res.get();
2429 TheCall->setArg(1, Arg1);
2430
2431 QualType Arg1Ty = Arg1->getType();
2432
2433 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2434 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2435 << 2 << /*'int' ty*/ 8 << Arg1Ty;
2436 return true;
2437 }
2438 }
2439
2440 return false;
2441}
2442
2444Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2445 CallExpr *TheCall) {
2446 ExprResult TheCallResult(TheCall);
2447
2448 // Find out if any arguments are required to be integer constant expressions.
2449 unsigned ICEArguments = 0;
2451 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
2452 if (Error != ASTContext::GE_None)
2453 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2454
2455 // If any arguments are required to be ICE's, check and diagnose.
2456 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2457 // Skip arguments not required to be ICE's.
2458 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2459
2460 llvm::APSInt Result;
2461 // If we don't have enough arguments, continue so we can issue better
2462 // diagnostic in checkArgCount(...)
2463 if (ArgNo < TheCall->getNumArgs() &&
2464 BuiltinConstantArg(TheCall, ArgNo, Result))
2465 return true;
2466 ICEArguments &= ~(1 << ArgNo);
2467 }
2468
2469 FPOptions FPO;
2470 switch (BuiltinID) {
2471 case Builtin::BI__builtin_cpu_supports:
2472 case Builtin::BI__builtin_cpu_is:
2473 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
2474 Context.getAuxTargetInfo(), BuiltinID))
2475 return ExprError();
2476 break;
2477 case Builtin::BI__builtin_cpu_init:
2479 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2480 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2481 return ExprError();
2482 }
2483 break;
2484 case Builtin::BI__builtin___CFStringMakeConstantString:
2485 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2486 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2488 *this, BuiltinID, TheCall,
2489 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2490 return ExprError();
2491 assert(TheCall->getNumArgs() == 1 &&
2492 "Wrong # arguments to builtin CFStringMakeConstantString");
2493 if (CheckObjCString(TheCall->getArg(0)))
2494 return ExprError();
2495 break;
2496 case Builtin::BI__builtin_ms_va_start:
2497 case Builtin::BI__builtin_stdarg_start:
2498 case Builtin::BI__builtin_va_start:
2499 if (BuiltinVAStart(BuiltinID, TheCall))
2500 return ExprError();
2501 break;
2502 case Builtin::BI__va_start: {
2503 switch (Context.getTargetInfo().getTriple().getArch()) {
2504 case llvm::Triple::aarch64:
2505 case llvm::Triple::arm:
2506 case llvm::Triple::thumb:
2507 if (BuiltinVAStartARMMicrosoft(TheCall))
2508 return ExprError();
2509 break;
2510 default:
2511 if (BuiltinVAStart(BuiltinID, TheCall))
2512 return ExprError();
2513 break;
2514 }
2515 break;
2516 }
2517
2518 // The acquire, release, and no fence variants are ARM and AArch64 only.
2519 case Builtin::BI_interlockedbittestandset_acq:
2520 case Builtin::BI_interlockedbittestandset_rel:
2521 case Builtin::BI_interlockedbittestandset_nf:
2522 case Builtin::BI_interlockedbittestandreset_acq:
2523 case Builtin::BI_interlockedbittestandreset_rel:
2524 case Builtin::BI_interlockedbittestandreset_nf:
2526 *this, BuiltinID, TheCall,
2527 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2528 return ExprError();
2529 break;
2530
2531 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2532 case Builtin::BI_bittest64:
2533 case Builtin::BI_bittestandcomplement64:
2534 case Builtin::BI_bittestandreset64:
2535 case Builtin::BI_bittestandset64:
2536 case Builtin::BI_interlockedbittestandreset64:
2537 case Builtin::BI_interlockedbittestandset64:
2538 if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall,
2539 {llvm::Triple::x86_64, llvm::Triple::arm,
2540 llvm::Triple::thumb,
2541 llvm::Triple::aarch64}))
2542 return ExprError();
2543 break;
2544
2545 case Builtin::BI__builtin_set_flt_rounds:
2546 if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall,
2547 {llvm::Triple::x86, llvm::Triple::x86_64,
2548 llvm::Triple::arm, llvm::Triple::thumb,
2549 llvm::Triple::aarch64}))
2550 return ExprError();
2551 break;
2552
2553 case Builtin::BI__builtin_isgreater:
2554 case Builtin::BI__builtin_isgreaterequal:
2555 case Builtin::BI__builtin_isless:
2556 case Builtin::BI__builtin_islessequal:
2557 case Builtin::BI__builtin_islessgreater:
2558 case Builtin::BI__builtin_isunordered:
2559 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
2560 return ExprError();
2561 break;
2562 case Builtin::BI__builtin_fpclassify:
2563 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
2564 return ExprError();
2565 break;
2566 case Builtin::BI__builtin_isfpclass:
2567 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
2568 return ExprError();
2569 break;
2570 case Builtin::BI__builtin_isfinite:
2571 case Builtin::BI__builtin_isinf:
2572 case Builtin::BI__builtin_isinf_sign:
2573 case Builtin::BI__builtin_isnan:
2574 case Builtin::BI__builtin_issignaling:
2575 case Builtin::BI__builtin_isnormal:
2576 case Builtin::BI__builtin_issubnormal:
2577 case Builtin::BI__builtin_iszero:
2578 case Builtin::BI__builtin_signbit:
2579 case Builtin::BI__builtin_signbitf:
2580 case Builtin::BI__builtin_signbitl:
2581 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
2582 return ExprError();
2583 break;
2584 case Builtin::BI__builtin_shufflevector:
2585 return BuiltinShuffleVector(TheCall);
2586 // TheCall will be freed by the smart pointer here, but that's fine, since
2587 // BuiltinShuffleVector guts it, but then doesn't release it.
2588 case Builtin::BI__builtin_prefetch:
2589 if (BuiltinPrefetch(TheCall))
2590 return ExprError();
2591 break;
2592 case Builtin::BI__builtin_alloca_with_align:
2593 case Builtin::BI__builtin_alloca_with_align_uninitialized:
2594 if (BuiltinAllocaWithAlign(TheCall))
2595 return ExprError();
2596 [[fallthrough]];
2597 case Builtin::BI__builtin_alloca:
2598 case Builtin::BI__builtin_alloca_uninitialized:
2599 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
2600 << TheCall->getDirectCallee();
2601 break;
2602 case Builtin::BI__arithmetic_fence:
2603 if (BuiltinArithmeticFence(TheCall))
2604 return ExprError();
2605 break;
2606 case Builtin::BI__assume:
2607 case Builtin::BI__builtin_assume:
2608 if (BuiltinAssume(TheCall))
2609 return ExprError();
2610 break;
2611 case Builtin::BI__builtin_assume_aligned:
2612 if (BuiltinAssumeAligned(TheCall))
2613 return ExprError();
2614 break;
2615 case Builtin::BI__builtin_dynamic_object_size:
2616 case Builtin::BI__builtin_object_size:
2617 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
2618 return ExprError();
2619 break;
2620 case Builtin::BI__builtin_longjmp:
2621 if (BuiltinLongjmp(TheCall))
2622 return ExprError();
2623 break;
2624 case Builtin::BI__builtin_setjmp:
2625 if (BuiltinSetjmp(TheCall))
2626 return ExprError();
2627 break;
2628 case Builtin::BI__builtin_classify_type:
2629 if (checkArgCount(*this, TheCall, 1)) return true;
2630 TheCall->setType(Context.IntTy);
2631 break;
2632 case Builtin::BI__builtin_complex:
2633 if (BuiltinComplex(TheCall))
2634 return ExprError();
2635 break;
2636 case Builtin::BI__builtin_constant_p: {
2637 if (checkArgCount(*this, TheCall, 1)) return true;
2639 if (Arg.isInvalid()) return true;
2640 TheCall->setArg(0, Arg.get());
2641 TheCall->setType(Context.IntTy);
2642 break;
2643 }
2644 case Builtin::BI__builtin_launder:
2645 return BuiltinLaunder(*this, TheCall);
2646 case Builtin::BI__sync_fetch_and_add:
2647 case Builtin::BI__sync_fetch_and_add_1:
2648 case Builtin::BI__sync_fetch_and_add_2:
2649 case Builtin::BI__sync_fetch_and_add_4:
2650 case Builtin::BI__sync_fetch_and_add_8:
2651 case Builtin::BI__sync_fetch_and_add_16:
2652 case Builtin::BI__sync_fetch_and_sub:
2653 case Builtin::BI__sync_fetch_and_sub_1:
2654 case Builtin::BI__sync_fetch_and_sub_2:
2655 case Builtin::BI__sync_fetch_and_sub_4:
2656 case Builtin::BI__sync_fetch_and_sub_8:
2657 case Builtin::BI__sync_fetch_and_sub_16:
2658 case Builtin::BI__sync_fetch_and_or:
2659 case Builtin::BI__sync_fetch_and_or_1:
2660 case Builtin::BI__sync_fetch_and_or_2:
2661 case Builtin::BI__sync_fetch_and_or_4:
2662 case Builtin::BI__sync_fetch_and_or_8:
2663 case Builtin::BI__sync_fetch_and_or_16:
2664 case Builtin::BI__sync_fetch_and_and:
2665 case Builtin::BI__sync_fetch_and_and_1:
2666 case Builtin::BI__sync_fetch_and_and_2:
2667 case Builtin::BI__sync_fetch_and_and_4:
2668 case Builtin::BI__sync_fetch_and_and_8:
2669 case Builtin::BI__sync_fetch_and_and_16:
2670 case Builtin::BI__sync_fetch_and_xor:
2671 case Builtin::BI__sync_fetch_and_xor_1:
2672 case Builtin::BI__sync_fetch_and_xor_2:
2673 case Builtin::BI__sync_fetch_and_xor_4:
2674 case Builtin::BI__sync_fetch_and_xor_8:
2675 case Builtin::BI__sync_fetch_and_xor_16:
2676 case Builtin::BI__sync_fetch_and_nand:
2677 case Builtin::BI__sync_fetch_and_nand_1:
2678 case Builtin::BI__sync_fetch_and_nand_2:
2679 case Builtin::BI__sync_fetch_and_nand_4:
2680 case Builtin::BI__sync_fetch_and_nand_8:
2681 case Builtin::BI__sync_fetch_and_nand_16:
2682 case Builtin::BI__sync_add_and_fetch:
2683 case Builtin::BI__sync_add_and_fetch_1:
2684 case Builtin::BI__sync_add_and_fetch_2:
2685 case Builtin::BI__sync_add_and_fetch_4:
2686 case Builtin::BI__sync_add_and_fetch_8:
2687 case Builtin::BI__sync_add_and_fetch_16:
2688 case Builtin::BI__sync_sub_and_fetch:
2689 case Builtin::BI__sync_sub_and_fetch_1:
2690 case Builtin::BI__sync_sub_and_fetch_2:
2691 case Builtin::BI__sync_sub_and_fetch_4:
2692 case Builtin::BI__sync_sub_and_fetch_8:
2693 case Builtin::BI__sync_sub_and_fetch_16:
2694 case Builtin::BI__sync_and_and_fetch:
2695 case Builtin::BI__sync_and_and_fetch_1:
2696 case Builtin::BI__sync_and_and_fetch_2:
2697 case Builtin::BI__sync_and_and_fetch_4:
2698 case Builtin::BI__sync_and_and_fetch_8:
2699 case Builtin::BI__sync_and_and_fetch_16:
2700 case Builtin::BI__sync_or_and_fetch:
2701 case Builtin::BI__sync_or_and_fetch_1:
2702 case Builtin::BI__sync_or_and_fetch_2:
2703 case Builtin::BI__sync_or_and_fetch_4:
2704 case Builtin::BI__sync_or_and_fetch_8:
2705 case Builtin::BI__sync_or_and_fetch_16:
2706 case Builtin::BI__sync_xor_and_fetch:
2707 case Builtin::BI__sync_xor_and_fetch_1:
2708 case Builtin::BI__sync_xor_and_fetch_2:
2709 case Builtin::BI__sync_xor_and_fetch_4:
2710 case Builtin::BI__sync_xor_and_fetch_8:
2711 case Builtin::BI__sync_xor_and_fetch_16:
2712 case Builtin::BI__sync_nand_and_fetch:
2713 case Builtin::BI__sync_nand_and_fetch_1:
2714 case Builtin::BI__sync_nand_and_fetch_2:
2715 case Builtin::BI__sync_nand_and_fetch_4:
2716 case Builtin::BI__sync_nand_and_fetch_8:
2717 case Builtin::BI__sync_nand_and_fetch_16:
2718 case Builtin::BI__sync_val_compare_and_swap:
2719 case Builtin::BI__sync_val_compare_and_swap_1:
2720 case Builtin::BI__sync_val_compare_and_swap_2:
2721 case Builtin::BI__sync_val_compare_and_swap_4:
2722 case Builtin::BI__sync_val_compare_and_swap_8:
2723 case Builtin::BI__sync_val_compare_and_swap_16:
2724 case Builtin::BI__sync_bool_compare_and_swap:
2725 case Builtin::BI__sync_bool_compare_and_swap_1:
2726 case Builtin::BI__sync_bool_compare_and_swap_2:
2727 case Builtin::BI__sync_bool_compare_and_swap_4:
2728 case Builtin::BI__sync_bool_compare_and_swap_8:
2729 case Builtin::BI__sync_bool_compare_and_swap_16:
2730 case Builtin::BI__sync_lock_test_and_set:
2731 case Builtin::BI__sync_lock_test_and_set_1:
2732 case Builtin::BI__sync_lock_test_and_set_2:
2733 case Builtin::BI__sync_lock_test_and_set_4:
2734 case Builtin::BI__sync_lock_test_and_set_8:
2735 case Builtin::BI__sync_lock_test_and_set_16:
2736 case Builtin::BI__sync_lock_release:
2737 case Builtin::BI__sync_lock_release_1:
2738 case Builtin::BI__sync_lock_release_2:
2739 case Builtin::BI__sync_lock_release_4:
2740 case Builtin::BI__sync_lock_release_8:
2741 case Builtin::BI__sync_lock_release_16:
2742 case Builtin::BI__sync_swap:
2743 case Builtin::BI__sync_swap_1:
2744 case Builtin::BI__sync_swap_2:
2745 case Builtin::BI__sync_swap_4:
2746 case Builtin::BI__sync_swap_8:
2747 case Builtin::BI__sync_swap_16:
2748 return BuiltinAtomicOverloaded(TheCallResult);
2749 case Builtin::BI__sync_synchronize:
2750 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
2751 << TheCall->getCallee()->getSourceRange();
2752 break;
2753 case Builtin::BI__builtin_nontemporal_load:
2754 case Builtin::BI__builtin_nontemporal_store:
2755 return BuiltinNontemporalOverloaded(TheCallResult);
2756 case Builtin::BI__builtin_memcpy_inline: {
2757 clang::Expr *SizeOp = TheCall->getArg(2);
2758 // We warn about copying to or from `nullptr` pointers when `size` is
2759 // greater than 0. When `size` is value dependent we cannot evaluate its
2760 // value so we bail out.
2761 if (SizeOp->isValueDependent())
2762 break;
2763 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
2764 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2765 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
2766 }
2767 break;
2768 }
2769 case Builtin::BI__builtin_memset_inline: {
2770 clang::Expr *SizeOp = TheCall->getArg(2);
2771 // We warn about filling to `nullptr` pointers when `size` is greater than
2772 // 0. When `size` is value dependent we cannot evaluate its value so we bail
2773 // out.
2774 if (SizeOp->isValueDependent())
2775 break;
2776 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
2777 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2778 break;
2779 }
2780#define BUILTIN(ID, TYPE, ATTRS)
2781#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
2782 case Builtin::BI##ID: \
2783 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
2784#include "clang/Basic/Builtins.inc"
2785 case Builtin::BI__annotation:
2786 if (BuiltinMSVCAnnotation(*this, TheCall))
2787 return ExprError();
2788 break;
2789 case Builtin::BI__builtin_annotation:
2790 if (BuiltinAnnotation(*this, TheCall))
2791 return ExprError();
2792 break;
2793 case Builtin::BI__builtin_addressof:
2794 if (BuiltinAddressof(*this, TheCall))
2795 return ExprError();
2796 break;
2797 case Builtin::BI__builtin_function_start:
2798 if (BuiltinFunctionStart(*this, TheCall))
2799 return ExprError();
2800 break;
2801 case Builtin::BI__builtin_is_aligned:
2802 case Builtin::BI__builtin_align_up:
2803 case Builtin::BI__builtin_align_down:
2804 if (BuiltinAlignment(*this, TheCall, BuiltinID))
2805 return ExprError();
2806 break;
2807 case Builtin::BI__builtin_add_overflow:
2808 case Builtin::BI__builtin_sub_overflow:
2809 case Builtin::BI__builtin_mul_overflow:
2810 if (BuiltinOverflow(*this, TheCall, BuiltinID))
2811 return ExprError();
2812 break;
2813 case Builtin::BI__builtin_operator_new:
2814 case Builtin::BI__builtin_operator_delete: {
2815 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
2816 ExprResult Res =
2817 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
2818 if (Res.isInvalid())
2819 CorrectDelayedTyposInExpr(TheCallResult.get());
2820 return Res;
2821 }
2822 case Builtin::BI__builtin_dump_struct:
2823 return BuiltinDumpStruct(*this, TheCall);
2824 case Builtin::BI__builtin_expect_with_probability: {
2825 // We first want to ensure we are called with 3 arguments
2826 if (checkArgCount(*this, TheCall, 3))
2827 return ExprError();
2828 // then check probability is constant float in range [0.0, 1.0]
2829 const Expr *ProbArg = TheCall->getArg(2);
2831 Expr::EvalResult Eval;
2832 Eval.Diag = &Notes;
2833 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2834 !Eval.Val.isFloat()) {
2835 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2836 << ProbArg->getSourceRange();
2837 for (const PartialDiagnosticAt &PDiag : Notes)
2838 Diag(PDiag.first, PDiag.second);
2839 return ExprError();
2840 }
2841 llvm::APFloat Probability = Eval.Val.getFloat();
2842 bool LoseInfo = false;
2843 Probability.convert(llvm::APFloat::IEEEdouble(),
2844 llvm::RoundingMode::Dynamic, &LoseInfo);
2845 if (!(Probability >= llvm::APFloat(0.0) &&
2846 Probability <= llvm::APFloat(1.0))) {
2847 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2848 << ProbArg->getSourceRange();
2849 return ExprError();
2850 }
2851 break;
2852 }
2853 case Builtin::BI__builtin_preserve_access_index:
2854 if (BuiltinPreserveAI(*this, TheCall))
2855 return ExprError();
2856 break;
2857 case Builtin::BI__builtin_call_with_static_chain:
2858 if (BuiltinCallWithStaticChain(*this, TheCall))
2859 return ExprError();
2860 break;
2861 case Builtin::BI__exception_code:
2862 case Builtin::BI_exception_code:
2863 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
2864 diag::err_seh___except_block))
2865 return ExprError();
2866 break;
2867 case Builtin::BI__exception_info:
2868 case Builtin::BI_exception_info:
2869 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2870 diag::err_seh___except_filter))
2871 return ExprError();
2872 break;
2873 case Builtin::BI__GetExceptionInfo:
2874 if (checkArgCount(*this, TheCall, 1))
2875 return ExprError();
2876
2878 TheCall->getBeginLoc(),
2880 TheCall))
2881 return ExprError();
2882
2883 TheCall->setType(Context.VoidPtrTy);
2884 break;
2885 case Builtin::BIaddressof:
2886 case Builtin::BI__addressof:
2887 case Builtin::BIforward:
2888 case Builtin::BIforward_like:
2889 case Builtin::BImove:
2890 case Builtin::BImove_if_noexcept:
2891 case Builtin::BIas_const: {
2892 // These are all expected to be of the form
2893 // T &/&&/* f(U &/&&)
2894 // where T and U only differ in qualification.
2895 if (checkArgCount(*this, TheCall, 1))
2896 return ExprError();
2897 QualType Param = FDecl->getParamDecl(0)->getType();
2898 QualType Result = FDecl->getReturnType();
2899 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
2900 BuiltinID == Builtin::BI__addressof;
2901 if (!(Param->isReferenceType() &&
2902 (ReturnsPointer ? Result->isAnyPointerType()
2903 : Result->isReferenceType()) &&
2905 Result->getPointeeType()))) {
2906 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
2907 << FDecl;
2908 return ExprError();
2909 }
2910 break;
2911 }
2912 case Builtin::BI__builtin_ptrauth_strip:
2913 return PointerAuthStrip(*this, TheCall);
2914 case Builtin::BI__builtin_ptrauth_blend_discriminator:
2915 return PointerAuthBlendDiscriminator(*this, TheCall);
2916 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
2917 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign);
2918 case Builtin::BI__builtin_ptrauth_auth:
2919 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth);
2920 case Builtin::BI__builtin_ptrauth_sign_generic_data:
2921 return PointerAuthSignGenericData(*this, TheCall);
2922 case Builtin::BI__builtin_ptrauth_auth_and_resign:
2923 return PointerAuthAuthAndResign(*this, TheCall);
2924 // OpenCL v2.0, s6.13.16 - Pipe functions
2925 case Builtin::BIread_pipe:
2926 case Builtin::BIwrite_pipe:
2927 // Since those two functions are declared with var args, we need a semantic
2928 // check for the argument.
2929 if (BuiltinRWPipe(*this, TheCall))
2930 return ExprError();
2931 break;
2932 case Builtin::BIreserve_read_pipe:
2933 case Builtin::BIreserve_write_pipe:
2934 case Builtin::BIwork_group_reserve_read_pipe:
2935 case Builtin::BIwork_group_reserve_write_pipe:
2936 if (BuiltinReserveRWPipe(*this, TheCall))
2937 return ExprError();
2938 break;
2939 case Builtin::BIsub_group_reserve_read_pipe:
2940 case Builtin::BIsub_group_reserve_write_pipe:
2941 if (checkOpenCLSubgroupExt(*this, TheCall) ||
2942 BuiltinReserveRWPipe(*this, TheCall))
2943 return ExprError();
2944 break;
2945 case Builtin::BIcommit_read_pipe:
2946 case Builtin::BIcommit_write_pipe:
2947 case Builtin::BIwork_group_commit_read_pipe:
2948 case Builtin::BIwork_group_commit_write_pipe:
2949 if (BuiltinCommitRWPipe(*this, TheCall))
2950 return ExprError();
2951 break;
2952 case Builtin::BIsub_group_commit_read_pipe:
2953 case Builtin::BIsub_group_commit_write_pipe:
2954 if (checkOpenCLSubgroupExt(*this, TheCall) ||
2955 BuiltinCommitRWPipe(*this, TheCall))
2956 return ExprError();
2957 break;
2958 case Builtin::BIget_pipe_num_packets:
2959 case Builtin::BIget_pipe_max_packets:
2960 if (BuiltinPipePackets(*this, TheCall))
2961 return ExprError();
2962 break;
2963 case Builtin::BIto_global:
2964 case Builtin::BIto_local:
2965 case Builtin::BIto_private:
2966 if (OpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
2967 return ExprError();
2968 break;
2969 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2970 case Builtin::BIenqueue_kernel:
2971 if (OpenCLBuiltinEnqueueKernel(*this, TheCall))
2972 return ExprError();
2973 break;
2974 case Builtin::BIget_kernel_work_group_size:
2975 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2976 if (OpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
2977 return ExprError();
2978 break;
2979 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2980 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2981 if (OpenCLBuiltinNDRangeAndBlock(*this, TheCall))
2982 return ExprError();
2983 break;
2984 case Builtin::BI__builtin_os_log_format:
2986 [[fallthrough]];
2987 case Builtin::BI__builtin_os_log_format_buffer_size:
2988 if (BuiltinOSLogFormat(TheCall))
2989 return ExprError();
2990 break;
2991 case Builtin::BI__builtin_frame_address:
2992 case Builtin::BI__builtin_return_address: {
2993 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
2994 return ExprError();
2995
2996 // -Wframe-address warning if non-zero passed to builtin
2997 // return/frame address.
2999 if (!TheCall->getArg(0)->isValueDependent() &&
3000 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3001 Result.Val.getInt() != 0)
3002 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3003 << ((BuiltinID == Builtin::BI__builtin_return_address)
3004 ? "__builtin_return_address"
3005 : "__builtin_frame_address")
3006 << TheCall->getSourceRange();
3007 break;
3008 }
3009
3010 case Builtin::BI__builtin_nondeterministic_value: {
3011 if (BuiltinNonDeterministicValue(TheCall))
3012 return ExprError();
3013 break;
3014 }
3015
3016 // __builtin_elementwise_abs restricts the element type to signed integers or
3017 // floating point types only.
3018 case Builtin::BI__builtin_elementwise_abs: {
3019 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
3020 return ExprError();
3021
3022 QualType ArgTy = TheCall->getArg(0)->getType();
3023 QualType EltTy = ArgTy;
3024
3025 if (auto *VecTy = EltTy->getAs<VectorType>())
3026 EltTy = VecTy->getElementType();
3027 if (EltTy->isUnsignedIntegerType()) {
3028 Diag(TheCall->getArg(0)->getBeginLoc(),
3029 diag::err_builtin_invalid_arg_type)
3030 << 1 << /* signed integer or float ty*/ 3 << ArgTy;
3031 return ExprError();
3032 }
3033 break;
3034 }
3035
3036 // These builtins restrict the element type to floating point
3037 // types only.
3038 case Builtin::BI__builtin_elementwise_ceil:
3039 case Builtin::BI__builtin_elementwise_cos:
3040 case Builtin::BI__builtin_elementwise_exp:
3041 case Builtin::BI__builtin_elementwise_exp2:
3042 case Builtin::BI__builtin_elementwise_floor:
3043 case Builtin::BI__builtin_elementwise_log:
3044 case Builtin::BI__builtin_elementwise_log2:
3045 case Builtin::BI__builtin_elementwise_log10:
3046 case Builtin::BI__builtin_elementwise_roundeven:
3047 case Builtin::BI__builtin_elementwise_round:
3048 case Builtin::BI__builtin_elementwise_rint:
3049 case Builtin::BI__builtin_elementwise_nearbyint:
3050 case Builtin::BI__builtin_elementwise_sin:
3051 case Builtin::BI__builtin_elementwise_sqrt:
3052 case Builtin::BI__builtin_elementwise_trunc:
3053 case Builtin::BI__builtin_elementwise_canonicalize: {
3054 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
3055 return ExprError();
3056
3057 QualType ArgTy = TheCall->getArg(0)->getType();
3058 if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
3059 ArgTy, 1))
3060 return ExprError();
3061 break;
3062 }
3063 case Builtin::BI__builtin_elementwise_fma: {
3064 if (BuiltinElementwiseTernaryMath(TheCall))
3065 return ExprError();
3066 break;
3067 }
3068
3069 // These builtins restrict the element type to floating point
3070 // types only, and take in two arguments.
3071 case Builtin::BI__builtin_elementwise_pow: {
3072 if (BuiltinElementwiseMath(TheCall))
3073 return ExprError();
3074
3075 QualType ArgTy = TheCall->getArg(0)->getType();
3076 if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
3077 ArgTy, 1) ||
3078 checkFPMathBuiltinElementType(*this, TheCall->getArg(1)->getBeginLoc(),
3079 ArgTy, 2))
3080 return ExprError();
3081 break;
3082 }
3083
3084 // These builtins restrict the element type to integer
3085 // types only.
3086 case Builtin::BI__builtin_elementwise_add_sat:
3087 case Builtin::BI__builtin_elementwise_sub_sat: {
3088 if (BuiltinElementwiseMath(TheCall))
3089 return ExprError();
3090
3091 const Expr *Arg = TheCall->getArg(0);
3092 QualType ArgTy = Arg->getType();
3093 QualType EltTy = ArgTy;
3094
3095 if (auto *VecTy = EltTy->getAs<VectorType>())
3096 EltTy = VecTy->getElementType();
3097
3098 if (!EltTy->isIntegerType()) {
3099 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3100 << 1 << /* integer ty */ 6 << ArgTy;
3101 return ExprError();
3102 }
3103 break;
3104 }
3105
3106 case Builtin::BI__builtin_elementwise_min:
3107 case Builtin::BI__builtin_elementwise_max:
3108 if (BuiltinElementwiseMath(TheCall))
3109 return ExprError();
3110 break;
3111
3112 case Builtin::BI__builtin_elementwise_bitreverse: {
3113 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
3114 return ExprError();
3115
3116 const Expr *Arg = TheCall->getArg(0);
3117 QualType ArgTy = Arg->getType();
3118 QualType EltTy = ArgTy;
3119
3120 if (auto *VecTy = EltTy->getAs<VectorType>())
3121 EltTy = VecTy->getElementType();
3122
3123 if (!EltTy->isIntegerType()) {
3124 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3125 << 1 << /* integer ty */ 6 << ArgTy;
3126 return ExprError();
3127 }
3128 break;
3129 }
3130
3131 case Builtin::BI__builtin_elementwise_copysign: {
3132 if (checkArgCount(*this, TheCall, 2))
3133 return ExprError();
3134
3135 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
3136 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
3137 if (Magnitude.isInvalid() || Sign.isInvalid())
3138 return ExprError();
3139
3140 QualType MagnitudeTy = Magnitude.get()->getType();
3141 QualType SignTy = Sign.get()->getType();
3142 if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
3143 MagnitudeTy, 1) ||
3144 checkFPMathBuiltinElementType(*this, TheCall->getArg(1)->getBeginLoc(),
3145 SignTy, 2)) {
3146 return ExprError();
3147 }
3148
3149 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3150 return Diag(Sign.get()->getBeginLoc(),
3151 diag::err_typecheck_call_different_arg_types)
3152 << MagnitudeTy << SignTy;
3153 }
3154
3155 TheCall->setArg(0, Magnitude.get());
3156 TheCall->setArg(1, Sign.get());
3157 TheCall->setType(Magnitude.get()->getType());
3158 break;
3159 }
3160 case Builtin::BI__builtin_reduce_max:
3161 case Builtin::BI__builtin_reduce_min: {
3162 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3163 return ExprError();
3164
3165 const Expr *Arg = TheCall->getArg(0);
3166 const auto *TyA = Arg->getType()->getAs<VectorType>();
3167 if (!TyA) {
3168 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3169 << 1 << /* vector ty*/ 4 << Arg->getType();
3170 return ExprError();
3171 }
3172
3173 TheCall->setType(TyA->getElementType());
3174 break;
3175 }
3176
3177 // These builtins support vectors of integers only.
3178 // TODO: ADD/MUL should support floating-point types.
3179 case Builtin::BI__builtin_reduce_add:
3180 case Builtin::BI__builtin_reduce_mul:
3181 case Builtin::BI__builtin_reduce_xor:
3182 case Builtin::BI__builtin_reduce_or:
3183 case Builtin::BI__builtin_reduce_and: {
3184 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3185 return ExprError();
3186
3187 const Expr *Arg = TheCall->getArg(0);
3188 const auto *TyA = Arg->getType()->getAs<VectorType>();
3189 if (!TyA || !TyA->getElementType()->isIntegerType()) {
3190 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3191 << 1 << /* vector of integers */ 6 << Arg->getType();
3192 return ExprError();
3193 }
3194 TheCall->setType(TyA->getElementType());
3195 break;
3196 }
3197
3198 case Builtin::BI__builtin_matrix_transpose:
3199 return BuiltinMatrixTranspose(TheCall, TheCallResult);
3200
3201 case Builtin::BI__builtin_matrix_column_major_load:
3202 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
3203
3204 case Builtin::BI__builtin_matrix_column_major_store:
3205 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
3206
3207 case Builtin::BI__builtin_get_device_side_mangled_name: {
3208 auto Check = [](CallExpr *TheCall) {
3209 if (TheCall->getNumArgs() != 1)
3210 return false;
3211 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
3212 if (!DRE)
3213 return false;
3214 auto *D = DRE->getDecl();
3215 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
3216 return false;
3217 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3218 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
3219 };
3220 if (!Check(TheCall)) {
3221 Diag(TheCall->getBeginLoc(),
3222 diag::err_hip_invalid_args_builtin_mangled_name);
3223 return ExprError();
3224 }
3225 break;
3226 }
3227 case Builtin::BI__builtin_popcountg:
3228 if (BuiltinPopcountg(*this, TheCall))
3229 return ExprError();
3230 break;
3231 case Builtin::BI__builtin_clzg:
3232 case Builtin::BI__builtin_ctzg:
3233 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
3234 return ExprError();
3235 break;
3236
3237 case Builtin::BI__builtin_allow_runtime_check: {
3238 Expr *Arg = TheCall->getArg(0);
3239 // Check if the argument is a string literal.
3240 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) {
3241 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3242 << Arg->getSourceRange();
3243 return ExprError();
3244 }
3245 break;
3246 }
3247 }
3248
3249 if (getLangOpts().HLSL && CheckHLSLBuiltinFunctionCall(BuiltinID, TheCall))
3250 return ExprError();
3251
3252 // Since the target specific builtins for each arch overlap, only check those
3253 // of the arch we are compiling for.
3254 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
3255 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
3256 assert(Context.getAuxTargetInfo() &&
3257 "Aux Target Builtin, but not an aux target?");
3258
3259 if (CheckTSBuiltinFunctionCall(
3261 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
3262 return ExprError();
3263 } else {
3264 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
3265 TheCall))
3266 return ExprError();
3267 }
3268 }
3269
3270 return TheCallResult;
3271}
3272
3273// Get the valid immediate range for the specified NEON type code.
3274static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
3276 int IsQuad = ForceQuad ? true : Type.isQuad();
3277 switch (Type.getEltType()) {
3280 return shift ? 7 : (8 << IsQuad) - 1;
3283 return shift ? 15 : (4 << IsQuad) - 1;
3285 return shift ? 31 : (2 << IsQuad) - 1;
3288 return shift ? 63 : (1 << IsQuad) - 1;
3290 return shift ? 127 : (1 << IsQuad) - 1;
3292 assert(!shift && "cannot shift float types!");
3293 return (4 << IsQuad) - 1;
3295 assert(!shift && "cannot shift float types!");
3296 return (2 << IsQuad) - 1;
3298 assert(!shift && "cannot shift float types!");
3299 return (1 << IsQuad) - 1;
3301 assert(!shift && "cannot shift float types!");
3302 return (4 << IsQuad) - 1;
3303 }
3304 llvm_unreachable("Invalid NeonTypeFlag!");
3305}
3306
3307/// getNeonEltType - Return the QualType corresponding to the elements of
3308/// the vector type specified by the NeonTypeFlags. This is used to check
3309/// the pointer arguments for Neon load/store intrinsics.
3311 bool IsPolyUnsigned, bool IsInt64Long) {
3312 switch (Flags.getEltType()) {
3314 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
3316 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
3318 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
3320 if (IsInt64Long)
3321 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
3322 else
3323 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
3324 : Context.LongLongTy;
3326 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
3328 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
3330 if (IsInt64Long)
3331 return Context.UnsignedLongTy;
3332 else
3333 return Context.UnsignedLongLongTy;
3335 break;
3337 return Context.HalfTy;
3339 return Context.FloatTy;
3341 return Context.DoubleTy;
3343 return Context.BFloat16Ty;
3344 }
3345 llvm_unreachable("Invalid NeonTypeFlag!");
3346}
3347
3354
3355enum ArmSMEState : unsigned {
3357
3358 ArmInZA = 0b01,
3359 ArmOutZA = 0b10,
3362
3363 ArmInZT0 = 0b01 << 2,
3364 ArmOutZT0 = 0b10 << 2,
3365 ArmInOutZT0 = 0b11 << 2,
3366 ArmZT0Mask = 0b11 << 2
3368
3369bool Sema::ParseSVEImmChecks(
3370 CallExpr *TheCall, SmallVector<std::tuple<int, int, int>, 3> &ImmChecks) {
3371 // Perform all the immediate checks for this builtin call.
3372 bool HasError = false;
3373 for (auto &I : ImmChecks) {
3374 int ArgNum, CheckTy, ElementSizeInBits;
3375 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
3376
3377 typedef bool (*OptionSetCheckFnTy)(int64_t Value);
3378
3379 // Function that checks whether the operand (ArgNum) is an immediate
3380 // that is one of the predefined values.
3381 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
3382 int ErrDiag) -> bool {
3383 // We can't check the value of a dependent argument.
3384 Expr *Arg = TheCall->getArg(ArgNum);
3385 if (Arg->isTypeDependent() || Arg->isValueDependent())
3386 return false;
3387
3388 // Check constant-ness first.
3389 llvm::APSInt Imm;
3390 if (BuiltinConstantArg(TheCall, ArgNum, Imm))
3391 return true;
3392
3393 if (!CheckImm(Imm.getSExtValue()))
3394 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
3395 return false;
3396 };
3397
3398 switch ((SVETypeFlags::ImmCheckType)CheckTy) {
3399 case SVETypeFlags::ImmCheck0_31:
3400 if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
3401 HasError = true;
3402 break;
3403 case SVETypeFlags::ImmCheck0_13:
3404 if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
3405 HasError = true;
3406 break;
3407 case SVETypeFlags::ImmCheck1_16:
3408 if (BuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
3409 HasError = true;
3410 break;
3411 case SVETypeFlags::ImmCheck0_7:
3412 if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
3413 HasError = true;
3414 break;
3415 case SVETypeFlags::ImmCheck1_1:
3416 if (BuiltinConstantArgRange(TheCall, ArgNum, 1, 1))
3417 HasError = true;
3418 break;
3419 case SVETypeFlags::ImmCheck1_3:
3420 if (BuiltinConstantArgRange(TheCall, ArgNum, 1, 3))
3421 HasError = true;
3422 break;
3423 case SVETypeFlags::ImmCheck1_7:
3424 if (BuiltinConstantArgRange(TheCall, ArgNum, 1, 7))
3425 HasError = true;
3426 break;
3427 case SVETypeFlags::ImmCheckExtract:
3428 if (BuiltinConstantArgRange(TheCall, ArgNum, 0,
3429 (2048 / ElementSizeInBits) - 1))
3430 HasError = true;
3431 break;
3432 case SVETypeFlags::ImmCheckShiftRight:
3433 if (BuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
3434 HasError = true;
3435 break;
3436 case SVETypeFlags::ImmCheckShiftRightNarrow:
3437 if (BuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits / 2))
3438 HasError = true;
3439 break;
3440 case SVETypeFlags::ImmCheckShiftLeft:
3441 if (BuiltinConstantArgRange(TheCall, ArgNum, 0, ElementSizeInBits - 1))
3442 HasError = true;
3443 break;
3444 case SVETypeFlags::ImmCheckLaneIndex:
3445 if (BuiltinConstantArgRange(TheCall, ArgNum, 0,
3446 (128 / (1 * ElementSizeInBits)) - 1))
3447 HasError = true;
3448 break;
3449 case SVETypeFlags::ImmCheckLaneIndexCompRotate:
3450 if (BuiltinConstantArgRange(TheCall, ArgNum, 0,
3451 (128 / (2 * ElementSizeInBits)) - 1))
3452 HasError = true;
3453 break;
3454 case SVETypeFlags::ImmCheckLaneIndexDot:
3455 if (BuiltinConstantArgRange(TheCall, ArgNum, 0,
3456 (128 / (4 * ElementSizeInBits)) - 1))
3457 HasError = true;
3458 break;
3459 case SVETypeFlags::ImmCheckComplexRot90_270:
3460 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
3461 diag::err_rotation_argument_to_cadd))
3462 HasError = true;
3463 break;
3464 case SVETypeFlags::ImmCheckComplexRotAll90:
3465 if (CheckImmediateInSet(
3466 [](int64_t V) {
3467 return V == 0 || V == 90 || V == 180 || V == 270;
3468 },
3469 diag::err_rotation_argument_to_cmla))
3470 HasError = true;
3471 break;
3472 case SVETypeFlags::ImmCheck0_1:
3473 if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
3474 HasError = true;
3475 break;
3476 case SVETypeFlags::ImmCheck0_2:
3477 if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
3478 HasError = true;
3479 break;
3480 case SVETypeFlags::ImmCheck0_3:
3481 if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
3482 HasError = true;
3483 break;
3484 case SVETypeFlags::ImmCheck0_0:
3485 if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 0))
3486 HasError = true;
3487 break;
3488 case SVETypeFlags::ImmCheck0_15:
3489 if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 15))
3490 HasError = true;
3491 break;
3492 case SVETypeFlags::ImmCheck0_255:
3493 if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 255))
3494 HasError = true;
3495 break;
3496 case SVETypeFlags::ImmCheck2_4_Mul2:
3497 if (BuiltinConstantArgRange(TheCall, ArgNum, 2, 4) ||
3498 BuiltinConstantArgMultiple(TheCall, ArgNum, 2))
3499 HasError = true;
3500 break;
3501 }
3502 }
3503
3504 return HasError;
3505}
3506
3508 if (FD->hasAttr<ArmLocallyStreamingAttr>())
3509 return ArmStreaming;
3510 if (const auto *T = FD->getType()->getAs<FunctionProtoType>()) {
3512 return ArmStreaming;
3515 }
3516 return ArmNonStreaming;
3517}
3518
3519static void checkArmStreamingBuiltin(Sema &S, CallExpr *TheCall,
3520 const FunctionDecl *FD,
3524 // Check intrinsics that are available in [sve2p1 or sme/sme2].
3525 llvm::StringMap<bool> CallerFeatureMap;
3526 S.Context.getFunctionFeatureMap(CallerFeatureMap, FD);
3527 if (Builtin::evaluateRequiredTargetFeatures("sve2p1", CallerFeatureMap))
3529 else
3531 }
3532
3533 if (FnType == ArmStreaming && BuiltinType == ArmNonStreaming) {
3534 S.Diag(TheCall->getBeginLoc(), diag::warn_attribute_arm_sm_incompat_builtin)
3535 << TheCall->getSourceRange() << "streaming";
3536 }
3537
3538 if (FnType == ArmStreamingCompatible &&
3540 S.Diag(TheCall->getBeginLoc(), diag::warn_attribute_arm_sm_incompat_builtin)
3541 << TheCall->getSourceRange() << "streaming compatible";
3542 return;
3543 }
3544
3545 if (FnType == ArmNonStreaming && BuiltinType == ArmStreaming) {
3546 S.Diag(TheCall->getBeginLoc(), diag::warn_attribute_arm_sm_incompat_builtin)
3547 << TheCall->getSourceRange() << "non-streaming";
3548 }
3549}
3550
3551static bool hasArmZAState(const FunctionDecl *FD) {
3552 const auto *T = FD->getType()->getAs<FunctionProtoType>();
3555 (FD->hasAttr<ArmNewAttr>() && FD->getAttr<ArmNewAttr>()->isNewZA());
3556}
3557
3558static bool hasArmZT0State(const FunctionDecl *FD) {
3559 const auto *T = FD->getType()->getAs<FunctionProtoType>();
3562 (FD->hasAttr<ArmNewAttr>() && FD->getAttr<ArmNewAttr>()->isNewZT0());
3563}
3564
3565static ArmSMEState getSMEState(unsigned BuiltinID) {
3566 switch (BuiltinID) {
3567 default:
3568 return ArmNoState;
3569#define GET_SME_BUILTIN_GET_STATE
3570#include "clang/Basic/arm_sme_builtins_za_state.inc"
3571#undef GET_SME_BUILTIN_GET_STATE
3572 }
3573}
3574
3575bool Sema::CheckSMEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3576 if (const FunctionDecl *FD = getCurFunctionDecl()) {
3577 std::optional<ArmStreamingType> BuiltinType;
3578
3579 switch (BuiltinID) {
3580#define GET_SME_STREAMING_ATTRS
3581#include "clang/Basic/arm_sme_streaming_attrs.inc"
3582#undef GET_SME_STREAMING_ATTRS
3583 }
3584
3585 if (BuiltinType)
3586 checkArmStreamingBuiltin(*this, TheCall, FD, *BuiltinType);
3587
3588 if ((getSMEState(BuiltinID) & ArmZAMask) && !hasArmZAState(FD))
3589 Diag(TheCall->getBeginLoc(),
3590 diag::warn_attribute_arm_za_builtin_no_za_state)
3591 << TheCall->getSourceRange();
3592
3593 if ((getSMEState(BuiltinID) & ArmZT0Mask) && !hasArmZT0State(FD))
3594 Diag(TheCall->getBeginLoc(),
3595 diag::warn_attribute_arm_zt0_builtin_no_zt0_state)
3596 << TheCall->getSourceRange();
3597 }
3598
3599 // Range check SME intrinsics that take immediate values.
3601
3602 switch (BuiltinID) {
3603 default:
3604 return false;
3605#define GET_SME_IMMEDIATE_CHECK
3606#include "clang/Basic/arm_sme_sema_rangechecks.inc"
3607#undef GET_SME_IMMEDIATE_CHECK
3608 }
3609
3610 return ParseSVEImmChecks(TheCall, ImmChecks);
3611}
3612
3613bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3614 if (const FunctionDecl *FD = getCurFunctionDecl()) {
3615 std::optional<ArmStreamingType> BuiltinType;
3616
3617 switch (BuiltinID) {
3618#define GET_SVE_STREAMING_ATTRS
3619#include "clang/Basic/arm_sve_streaming_attrs.inc"
3620#undef GET_SVE_STREAMING_ATTRS
3621 }
3622 if (BuiltinType)
3623 checkArmStreamingBuiltin(*this, TheCall, FD, *BuiltinType);
3624 }
3625 // Range check SVE intrinsics that take immediate values.
3627
3628 switch (BuiltinID) {
3629 default:
3630 return false;
3631#define GET_SVE_IMMEDIATE_CHECK
3632#include "clang/Basic/arm_sve_sema_rangechecks.inc"
3633#undef GET_SVE_IMMEDIATE_CHECK
3634 }
3635
3636 return ParseSVEImmChecks(TheCall, ImmChecks);
3637}
3638
3639bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
3640 unsigned BuiltinID, CallExpr *TheCall) {
3641 if (const FunctionDecl *FD = getCurFunctionDecl()) {
3642
3643 switch (BuiltinID) {
3644 default:
3645 break;
3646#define GET_NEON_BUILTINS
3647#define TARGET_BUILTIN(id, ...) case NEON::BI##id:
3648#define BUILTIN(id, ...) case NEON::BI##id:
3649#include "clang/Basic/arm_neon.inc"
3650 checkArmStreamingBuiltin(*this, TheCall, FD, ArmNonStreaming);
3651 break;
3652#undef TARGET_BUILTIN
3653#undef BUILTIN
3654#undef GET_NEON_BUILTINS
3655 }
3656 }
3657
3658 llvm::APSInt Result;
3659 uint64_t mask = 0;
3660 unsigned TV = 0;
3661 int PtrArgNum = -1;
3662 bool HasConstPtr = false;
3663 switch (BuiltinID) {
3664#define GET_NEON_OVERLOAD_CHECK
3665#include "clang/Basic/arm_neon.inc"
3666#include "clang/Basic/arm_fp16.inc"
3667#undef GET_NEON_OVERLOAD_CHECK
3668 }
3669
3670 // For NEON intrinsics which are overloaded on vector element type, validate
3671 // the immediate which specifies which variant to emit.
3672 unsigned ImmArg = TheCall->getNumArgs()-1;
3673 if (mask) {
3674 if (BuiltinConstantArg(TheCall, ImmArg, Result))
3675 return true;
3676
3677 TV = Result.getLimitedValue(64);
3678 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
3679 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
3680 << TheCall->getArg(ImmArg)->getSourceRange();
3681 }
3682
3683 if (PtrArgNum >= 0) {
3684 // Check that pointer arguments have the specified type.
3685 Expr *Arg = TheCall->getArg(PtrArgNum);
3686 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
3687 Arg = ICE->getSubExpr();
3689 QualType RHSTy = RHS.get()->getType();
3690
3691 llvm::Triple::ArchType Arch = TI.getTriple().getArch();
3692 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
3693 Arch == llvm::Triple::aarch64_32 ||
3694 Arch == llvm::Triple::aarch64_be;
3695 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
3696 QualType EltTy =
3697 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
3698 if (HasConstPtr)
3699 EltTy = EltTy.withConst();
3700 QualType LHSTy = Context.getPointerType(EltTy);
3701 AssignConvertType ConvTy;
3702 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
3703 if (RHS.isInvalid())
3704 return true;
3705 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
3706 RHS.get(), AA_Assigning))
3707 return true;
3708 }
3709
3710 // For NEON intrinsics which take an immediate value as part of the
3711 // instruction, range check them here.
3712 unsigned i = 0, l = 0, u = 0;
3713 switch (BuiltinID) {
3714 default:
3715 return false;
3716 #define GET_NEON_IMMEDIATE_CHECK
3717 #include "clang/Basic/arm_neon.inc"
3718 #include "clang/Basic/arm_fp16.inc"
3719 #undef GET_NEON_IMMEDIATE_CHECK
3720 }
3721
3722 return BuiltinConstantArgRange(TheCall, i, l, u + l);
3723}
3724
3725bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3726 switch (BuiltinID) {
3727 default:
3728 return false;
3729 #include "clang/Basic/arm_mve_builtin_sema.inc"
3730 }
3731}
3732
3733bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3734 CallExpr *TheCall) {
3735 bool Err = false;
3736 switch (BuiltinID) {
3737 default:
3738 return false;
3739#include "clang/Basic/arm_cde_builtin_sema.inc"
3740 }
3741
3742 if (Err)
3743 return true;
3744
3745 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
3746}
3747
3748bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
3749 const Expr *CoprocArg, bool WantCDE) {
3751 return false;
3752
3753 // We can't check the value of a dependent argument.
3754 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
3755 return false;
3756
3757 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
3758 int64_t CoprocNo = CoprocNoAP.getExtValue();
3759 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
3760
3761 uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
3762 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
3763
3764 if (IsCDECoproc != WantCDE)
3765 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
3766 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
3767
3768 return false;
3769}
3770
3771bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
3772 unsigned MaxWidth) {
3773 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
3774 BuiltinID == ARM::BI__builtin_arm_ldaex ||
3775 BuiltinID == ARM::BI__builtin_arm_strex ||
3776 BuiltinID == ARM::BI__builtin_arm_stlex ||
3777 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
3778 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
3779 BuiltinID == AArch64::BI__builtin_arm_strex ||
3780 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
3781 "unexpected ARM builtin");
3782 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
3783 BuiltinID == ARM::BI__builtin_arm_ldaex ||
3784 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
3785 BuiltinID == AArch64::BI__builtin_arm_ldaex;
3786
3787 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3788
3789 // Ensure that we have the proper number of arguments.
3790 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
3791 return true;
3792
3793 // Inspect the pointer argument of the atomic builtin. This should always be
3794 // a pointer type, whose element is an integral scalar or pointer type.
3795 // Because it is a pointer type, we don't have to worry about any implicit
3796 // casts here.
3797 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
3798 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
3799 if (PointerArgRes.isInvalid())
3800 return true;
3801 PointerArg = PointerArgRes.get();
3802
3803 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3804 if (!pointerType) {
3805 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
3806 << PointerArg->getType() << PointerArg->getSourceRange();
3807 return true;
3808 }
3809
3810 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
3811 // task is to insert the appropriate casts into the AST. First work out just
3812 // what the appropriate type is.
3813 QualType ValType = pointerType->getPointeeType();
3814 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
3815 if (IsLdrex)
3816 AddrType.addConst();
3817
3818 // Issue a warning if the cast is dodgy.
3819 CastKind CastNeeded = CK_NoOp;
3820 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
3821 CastNeeded = CK_BitCast;
3822 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
3823 << PointerArg->getType() << Context.getPointerType(AddrType)
3824 << AA_Passing << PointerArg->getSourceRange();
3825 }
3826
3827 // Finally, do the cast and replace the argument with the corrected version.
3828 AddrType = Context.getPointerType(AddrType);
3829 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
3830 if (PointerArgRes.isInvalid())
3831 return true;
3832 PointerArg = PointerArgRes.get();
3833
3834 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
3835
3836 // In general, we allow ints, floats and pointers to be loaded and stored.
3837 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3838 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
3839 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
3840 << PointerArg->getType() << PointerArg->getSourceRange();
3841 return true;
3842 }
3843
3844 // But ARM doesn't have instructions to deal with 128-bit versions.
3845 if (Context.getTypeSize(ValType) > MaxWidth) {
3846 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
3847 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
3848 << PointerArg->getType() << PointerArg->getSourceRange();
3849 return true;
3850 }
3851
3852 switch (ValType.getObjCLifetime()) {
3855 // okay
3856 break;
3857
3861 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
3862 << ValType << PointerArg->getSourceRange();
3863 return true;
3864 }
3865
3866 if (IsLdrex) {
3867 TheCall->setType(ValType);
3868 return false;
3869 }
3870
3871 // Initialize the argument to be stored.
3872 ExprResult ValArg = TheCall->getArg(0);
3874 Context, ValType, /*consume*/ false);
3875 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3876 if (ValArg.isInvalid())
3877 return true;
3878 TheCall->setArg(0, ValArg.get());
3879
3880 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
3881 // but the custom checker bypasses all default analysis.
3882 TheCall->setType(Context.IntTy);
3883 return false;
3884}
3885
3886bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3887 CallExpr *TheCall) {
3888 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
3889 BuiltinID == ARM::BI__builtin_arm_ldaex ||
3890 BuiltinID == ARM::BI__builtin_arm_strex ||
3891 BuiltinID == ARM::BI__builtin_arm_stlex) {
3892 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
3893 }
3894
3895 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
3896 return BuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3897 BuiltinConstantArgRange(TheCall, 2, 0, 1);
3898 }
3899
3900 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3901 BuiltinID == ARM::BI__builtin_arm_wsr64)
3902 return BuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
3903
3904 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
3905 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3906 BuiltinID == ARM::BI__builtin_arm_wsr ||
3907 BuiltinID == ARM::BI__builtin_arm_wsrp)
3908 return BuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
3909
3910 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
3911 return true;
3912 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
3913 return true;
3914 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
3915 return true;
3916
3917 // For intrinsics which take an immediate value as part of the instruction,
3918 // range check them here.
3919 // FIXME: VFP Intrinsics should error if VFP not present.
3920 switch (BuiltinID) {
3921 default: return false;
3922 case ARM::BI__builtin_arm_ssat:
3923 return BuiltinConstantArgRange(TheCall, 1, 1, 32);
3924 case ARM::BI__builtin_arm_usat:
3925 return BuiltinConstantArgRange(TheCall, 1, 0, 31);
3926 case ARM::BI__builtin_arm_ssat16:
3927 return BuiltinConstantArgRange(TheCall, 1, 1, 16);
3928 case ARM::BI__builtin_arm_usat16:
3929 return BuiltinConstantArgRange(TheCall, 1, 0, 15);
3930 case ARM::BI__builtin_arm_vcvtr_f:
3931 case ARM::BI__builtin_arm_vcvtr_d:
3932 return BuiltinConstantArgRange(TheCall, 1, 0, 1);
3933 case ARM::BI__builtin_arm_dmb:
3934 case ARM::BI__builtin_arm_dsb:
3935 case ARM::BI__builtin_arm_isb:
3936 case ARM::BI__builtin_arm_dbg:
3937 return BuiltinConstantArgRange(TheCall, 0, 0, 15);
3938 case ARM::BI__builtin_arm_cdp:
3939 case ARM::BI__builtin_arm_cdp2:
3940 case ARM::BI__builtin_arm_mcr:
3941 case ARM::BI__builtin_arm_mcr2:
3942 case ARM::BI__builtin_arm_mrc:
3943 case ARM::BI__builtin_arm_mrc2:
3944 case ARM::BI__builtin_arm_mcrr:
3945 case ARM::BI__builtin_arm_mcrr2:
3946 case ARM::BI__builtin_arm_mrrc:
3947 case ARM::BI__builtin_arm_mrrc2:
3948 case ARM::BI__builtin_arm_ldc:
3949 case ARM::BI__builtin_arm_ldcl:
3950 case ARM::BI__builtin_arm_ldc2:
3951 case ARM::BI__builtin_arm_ldc2l:
3952 case ARM::BI__builtin_arm_stc:
3953 case ARM::BI__builtin_arm_stcl:
3954 case ARM::BI__builtin_arm_stc2:
3955 case ARM::BI__builtin_arm_stc2l:
3956 return BuiltinConstantArgRange(TheCall, 0, 0, 15) ||
3957 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
3958 /*WantCDE*/ false);
3959 }
3960}
3961
3962bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
3963 unsigned BuiltinID,
3964 CallExpr *TheCall) {
3965 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
3966 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
3967 BuiltinID == AArch64::BI__builtin_arm_strex ||
3968 BuiltinID == AArch64::BI__builtin_arm_stlex) {
3969 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
3970 }
3971
3972 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
3973 return BuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3974 BuiltinConstantArgRange(TheCall, 2, 0, 3) ||
3975 BuiltinConstantArgRange(TheCall, 3, 0, 1) ||
3976 BuiltinConstantArgRange(TheCall, 4, 0, 1);
3977 }
3978
3979 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3980 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3981 BuiltinID == AArch64::BI__builtin_arm_rsr128 ||
3982 BuiltinID == AArch64::BI__builtin_arm_wsr128)
3983 return BuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
3984
3985 // Memory Tagging Extensions (MTE) Intrinsics
3986 if (BuiltinID == AArch64::BI__builtin_arm_irg ||
3987 BuiltinID == AArch64::BI__builtin_arm_addg ||
3988 BuiltinID == AArch64::BI__builtin_arm_gmi ||
3989 BuiltinID == AArch64::BI__builtin_arm_ldg ||
3990 BuiltinID == AArch64::BI__builtin_arm_stg ||
3991 BuiltinID == AArch64::BI__builtin_arm_subp) {
3992 return BuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
3993 }
3994
3995 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
3996 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3997 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3998 BuiltinID == AArch64::BI__builtin_arm_wsrp)
3999 return BuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
4000
4001 // Only check the valid encoding range. Any constant in this range would be
4002 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
4003 // an exception for incorrect registers. This matches MSVC behavior.
4004 if (BuiltinID == AArch64::BI_ReadStatusReg ||
4005 BuiltinID == AArch64::BI_WriteStatusReg)
4006 return BuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
4007
4008 if (BuiltinID == AArch64::BI__getReg)
4009 return BuiltinConstantArgRange(TheCall, 0, 0, 31);
4010
4011 if (BuiltinID == AArch64::BI__break)
4012 return BuiltinConstantArgRange(TheCall, 0, 0, 0xffff);
4013
4014 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
4015 return true;
4016
4017 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
4018 return true;
4019
4020 if (CheckSMEBuiltinFunctionCall(BuiltinID, TheCall))
4021 return true;
4022
4023 // For intrinsics which take an immediate value as part of the instruction,
4024 // range check them here.
4025 unsigned i = 0, l = 0, u = 0;
4026 switch (BuiltinID) {
4027 default: return false;
4028 case AArch64::BI__builtin_arm_dmb:
4029 case AArch64::BI__builtin_arm_dsb:
4030 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
4031 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
4032 }
4033
4034 return BuiltinConstantArgRange(TheCall, i, l, u + l);
4035}
4036
4038 if (Arg->getType()->getAsPlaceholderType())
4039 return false;
4040
4041 // The first argument needs to be a record field access.
4042 // If it is an array element access, we delay decision
4043 // to BPF backend to check whether the access is a
4044 // field access or not.
4045 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
4046 isa<MemberExpr>(Arg->IgnoreParens()) ||
4047 isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
4048}
4049
4051 QualType ArgType = Arg->getType();
4052 if (ArgType->getAsPlaceholderType())
4053 return false;
4054
4055 // for TYPE_EXISTENCE/TYPE_MATCH/TYPE_SIZEOF reloc type
4056 // format:
4057 // 1. __builtin_preserve_type_info(*(<type> *)0, flag);
4058 // 2. <type> var;
4059 // __builtin_preserve_type_info(var, flag);
4060 if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
4061 !isa<UnaryOperator>(Arg->IgnoreParens()))
4062 return false;
4063
4064 // Typedef type.
4065 if (ArgType->getAs<TypedefType>())
4066 return true;
4067
4068 // Record type or Enum type.
4069 const Type *Ty = ArgType->getUnqualifiedDesugaredType();
4070 if (const auto *RT = Ty->getAs<RecordType>()) {
4071 if (!RT->getDecl()->getDeclName().isEmpty())
4072 return true;
4073 } else if (const auto *ET = Ty->getAs<EnumType>()) {
4074 if (!ET->getDecl()->getDeclName().isEmpty())
4075 return true;
4076 }
4077
4078 return false;
4079}
4080
4082 QualType ArgType = Arg->getType();
4083 if (ArgType->getAsPlaceholderType())
4084 return false;
4085
4086 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
4087 // format:
4088 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
4089 // flag);
4090 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
4091 if (!UO)
4092 return false;
4093
4094 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
4095 if (!CE)
4096 return false;
4097 if (CE->getCastKind() != CK_IntegralToPointer &&
4098 CE->getCastKind() != CK_NullToPointer)
4099 return false;
4100
4101 // The integer must be from an EnumConstantDecl.
4102 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
4103 if (!DR)
4104 return false;
4105
4106 const EnumConstantDecl *Enumerator =
4107 dyn_cast<EnumConstantDecl>(DR->getDecl());
4108 if (!Enumerator)
4109 return false;
4110
4111 // The type must be EnumType.
4112 const Type *Ty = ArgType->getUnqualifiedDesugaredType();
4113 const auto *ET = Ty->getAs<EnumType>();
4114 if (!ET)
4115 return false;
4116
4117 // The enum value must be supported.
4118 return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
4119}
4120
4121bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
4122 CallExpr *TheCall) {
4123 assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
4124 BuiltinID == BPF::BI__builtin_btf_type_id ||
4125 BuiltinID == BPF::BI__builtin_preserve_type_info ||
4126 BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
4127 "unexpected BPF builtin");
4128
4129 if (checkArgCount(*this, TheCall, 2))
4130 return true;
4131
4132 // The second argument needs to be a constant int
4133 Expr *Arg = TheCall->getArg(1);
4134 std::optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
4136 if (!Value) {
4137 if (BuiltinID == BPF::BI__builtin_preserve_field_info)
4138 kind = diag::err_preserve_field_info_not_const;
4139 else if (BuiltinID == BPF::BI__builtin_btf_type_id)
4140 kind = diag::err_btf_type_id_not_const;
4141 else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
4142 kind = diag::err_preserve_type_info_not_const;
4143 else
4144 kind = diag::err_preserve_enum_value_not_const;
4145 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
4146 return true;
4147 }
4148
4149 // The first argument
4150 Arg = TheCall->getArg(0);
4151 bool InvalidArg = false;
4152 bool ReturnUnsignedInt = true;
4153 if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
4155 InvalidArg = true;
4156 kind = diag::err_preserve_field_info_not_field;
4157 }
4158 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
4160 InvalidArg = true;
4161 kind = diag::err_preserve_type_info_invalid;
4162 }
4163 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
4165 InvalidArg = true;
4166 kind = diag::err_preserve_enum_value_invalid;
4167 }
4168 ReturnUnsignedInt = false;
4169 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
4170 ReturnUnsignedInt = false;
4171 }
4172
4173 if (InvalidArg) {
4174 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
4175 return true;
4176 }
4177
4178 if (ReturnUnsignedInt)
4179 TheCall->setType(Context.UnsignedIntTy);
4180 else
4181 TheCall->setType(Context.UnsignedLongTy);
4182 return false;
4183}
4184
4185bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
4186 struct ArgInfo {
4187 uint8_t OpNum;
4188 bool IsSigned;
4189 uint8_t BitWidth;
4190 uint8_t Align;
4191 };
4192 struct BuiltinInfo {
4193 unsigned BuiltinID;
4194 ArgInfo Infos[2];
4195 };
4196
4197 static BuiltinInfo Infos[] = {
4198 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
4199 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
4200 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
4201 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} },
4202 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
4203 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
4204 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
4205 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
4206 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
4207 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
4208 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
4209
4210 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
4211 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
4212 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
4213 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
4214 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
4215 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
4216 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
4217 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
4218 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
4219 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
4220 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
4221
4222 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
4223 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
4224 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
4225 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
4226 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
4227 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
4228 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
4229 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
4230 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
4231 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
4232 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
4233 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
4234 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
4235 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
4236 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
4237 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
4238 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
4239 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
4240 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
4241 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
4242 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
4243 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
4244 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
4245 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
4246 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
4247 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
4248 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
4249 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
4250 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
4251 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
4252 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
4253 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
4254 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
4255 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
4256 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
4257 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
4258 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
4259 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
4260 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
4261 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
4262 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
4263 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
4264 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
4265 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
4266 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
4267 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
4268 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
4269 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
4270 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
4271 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
4272 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
4273 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
4274 {{ 1, false, 6, 0 }} },
4275 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
4276 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
4277 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
4278 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
4279 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
4280 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
4281 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
4282 {{ 1, false, 5, 0 }} },
4283 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
4284 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
4285 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
4286 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
4287 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
4288 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
4289 { 2, false, 5, 0 }} },
4290 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
4291 { 2, false, 6, 0 }} },
4292 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
4293 { 3, false, 5, 0 }} },
4294 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
4295 { 3, false, 6, 0 }} },
4296 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
4297 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
4298 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
4299 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
4300 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
4301 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
4302 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
4303 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
4304 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
4305 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
4306 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
4307 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
4308 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
4309 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
4310 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
4311 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
4312 {{ 2, false, 4, 0 },
4313 { 3, false, 5, 0 }} },
4314 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
4315 {{ 2, false, 4, 0 },
4316 { 3, false, 5, 0 }} },
4317 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
4318 {{ 2, false, 4, 0 },
4319 { 3, false, 5, 0 }} },
4320 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
4321 {{ 2, false, 4, 0 },
4322 { 3, false, 5, 0 }} },
4323 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
4324 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
4325 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
4326 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
4327 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
4328 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
4329 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
4330 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
4331 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
4332 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
4333 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
4334 { 2, false, 5, 0 }} },
4335 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
4336 { 2, false, 6, 0 }} },
4337 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
4338 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
4339 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
4340 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
4341 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
4342 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
4343 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
4344 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
4345 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
4346 {{ 1, false, 4, 0 }} },
4347 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
4348 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
4349 {{ 1, false, 4, 0 }} },
4350 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
4351 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
4352 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
4353 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
4354 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
4355 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
4356 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
4357 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
4358 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
4359 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
4360 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
4361 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
4362 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
4363 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
4364 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
4365 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
4366 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
4367 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
4368 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
4369 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
4370 {{ 3, false, 1, 0 }} },
4371 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
4372 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
4373 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
4374 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
4375 {{ 3, false, 1, 0 }} },
4376 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
4377 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
4378 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
4379 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
4380 {{ 3, false, 1, 0 }} },
4381
4382 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyhubs10, {{ 2, false, 2, 0 }} },
4383 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyhubs10_128B,
4384 {{ 2, false, 2, 0 }} },
4385 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyhubs10_vxx,
4386 {{ 3, false, 2, 0 }} },
4387 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyhubs10_vxx_128B,
4388 {{ 3, false, 2, 0 }} },
4389 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyvubs10, {{ 2, false, 2, 0 }} },
4390 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyvubs10_128B,
4391 {{ 2, false, 2, 0 }} },
4392 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyvubs10_vxx,
4393 {{ 3, false, 2, 0 }} },
4394 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyvubs10_vxx_128B,
4395 {{ 3, false, 2, 0 }} },
4396 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, {{ 2, false, 3, 0 }} },
4397 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, {{ 2, false, 3, 0 }} },
4398 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, {{ 3, false, 3, 0 }} },
4399 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B,
4400 {{ 3, false, 3, 0 }} },
4401 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, {{ 2, false, 3, 0 }} },
4402 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, {{ 2, false, 3, 0 }} },
4403 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, {{ 3, false, 3, 0 }} },
4404 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B,
4405 {{ 3, false, 3, 0 }} },
4406 };
4407
4408 // Use a dynamically initialized static to sort the table exactly once on
4409 // first run.
4410 static const bool SortOnce =
4411 (llvm::sort(Infos,
4412 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
4413 return LHS.BuiltinID < RHS.BuiltinID;
4414 }),
4415 true);
4416 (void)SortOnce;
4417
4418 const BuiltinInfo *F = llvm::partition_point(
4419 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
4420 if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
4421 return false;
4422
4423 bool Error = false;
4424
4425 for (const ArgInfo &A : F->Infos) {
4426 // Ignore empty ArgInfo elements.
4427 if (A.BitWidth == 0)
4428 continue;
4429
4430 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
4431 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
4432 if (!A.Align) {
4433 Error |= BuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
4434 } else {
4435 unsigned M = 1 << A.Align;
4436 Min *= M;
4437 Max *= M;
4438 Error |= BuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
4439 Error |= BuiltinConstantArgMultiple(TheCall, A.OpNum, M);
4440 }
4441 }
4442 return Error;
4443}
4444
4445bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
4446 CallExpr *TheCall) {
4447 return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
4448}
4449
4450bool Sema::CheckLoongArchBuiltinFunctionCall(const TargetInfo &TI,
4451 unsigned BuiltinID,
4452 CallExpr *TheCall) {
4453 switch (BuiltinID) {
4454 default:
4455 break;
4456 // Basic intrinsics.
4457 case LoongArch::BI__builtin_loongarch_cacop_d:
4458 case LoongArch::BI__builtin_loongarch_cacop_w: {
4459 BuiltinConstantArgRange(TheCall, 0, 0, llvm::maxUIntN(5));
4460 BuiltinConstantArgRange(TheCall, 2, llvm::minIntN(12), llvm::maxIntN(12));
4461 break;
4462 }
4463 case LoongArch::BI__builtin_loongarch_break:
4464 case LoongArch::BI__builtin_loongarch_dbar:
4465 case LoongArch::BI__builtin_loongarch_ibar:
4466 case LoongArch::BI__builtin_loongarch_syscall:
4467 // Check if immediate is in [0, 32767].
4468 return BuiltinConstantArgRange(TheCall, 0, 0, 32767);
4469 case LoongArch::BI__builtin_loongarch_csrrd_w:
4470 case LoongArch::BI__builtin_loongarch_csrrd_d:
4471 return BuiltinConstantArgRange(TheCall, 0, 0, 16383);
4472 case LoongArch::BI__builtin_loongarch_csrwr_w:
4473 case LoongArch::BI__builtin_loongarch_csrwr_d:
4474 return BuiltinConstantArgRange(TheCall, 1, 0, 16383);
4475 case LoongArch::BI__builtin_loongarch_csrxchg_w:
4476 case LoongArch::BI__builtin_loongarch_csrxchg_d:
4477 return BuiltinConstantArgRange(TheCall, 2, 0, 16383);
4478 case LoongArch::BI__builtin_loongarch_lddir_d:
4479 case LoongArch::BI__builtin_loongarch_ldpte_d:
4480 return BuiltinConstantArgRange(TheCall, 1, 0, 31);
4481 case LoongArch::BI__builtin_loongarch_movfcsr2gr:
4482 case LoongArch::BI__builtin_loongarch_movgr2fcsr:
4483 return BuiltinConstantArgRange(TheCall, 0, 0, llvm::maxUIntN(2));
4484
4485 // LSX intrinsics.
4486 case LoongArch::BI__builtin_lsx_vbitclri_b:
4487 case LoongArch::BI__builtin_lsx_vbitrevi_b:
4488 case LoongArch::BI__builtin_lsx_vbitseti_b:
4489 case LoongArch::BI__builtin_lsx_vsat_b:
4490 case LoongArch::BI__builtin_lsx_vsat_bu:
4491 case LoongArch::BI__builtin_lsx_vslli_b:
4492 case LoongArch::BI__builtin_lsx_vsrai_b:
4493 case LoongArch::BI__builtin_lsx_vsrari_b:
4494 case LoongArch::BI__builtin_lsx_vsrli_b:
4495 case LoongArch::BI__builtin_lsx_vsllwil_h_b:
4496 case LoongArch::BI__builtin_lsx_vsllwil_hu_bu:
4497 case LoongArch::BI__builtin_lsx_vrotri_b:
4498 case LoongArch::BI__builtin_lsx_vsrlri_b:
4499 return BuiltinConstantArgRange(TheCall, 1, 0, 7);
4500 case LoongArch::BI__builtin_lsx_vbitclri_h:
4501 case LoongArch::BI__builtin_lsx_vbitrevi_h:
4502 case LoongArch::BI__builtin_lsx_vbitseti_h:
4503 case LoongArch::BI__builtin_lsx_vsat_h:
4504 case LoongArch::BI__builtin_lsx_vsat_hu:
4505 case LoongArch::BI__builtin_lsx_vslli_h:
4506 case LoongArch::BI__builtin_lsx_vsrai_h:
4507 case LoongArch::BI__builtin_lsx_vsrari_h:
4508 case LoongArch::BI__builtin_lsx_vsrli_h:
4509 case LoongArch::BI__builtin_lsx_vsllwil_w_h:
4510 case LoongArch::BI__builtin_lsx_vsllwil_wu_hu:
4511 case LoongArch::BI__builtin_lsx_vrotri_h:
4512 case LoongArch::BI__builtin_lsx_vsrlri_h:
4513 return BuiltinConstantArgRange(TheCall, 1, 0, 15);
4514 case LoongArch::BI__builtin_lsx_vssrarni_b_h:
4515 case LoongArch::BI__builtin_lsx_vssrarni_bu_h:
4516 case LoongArch::BI__builtin_lsx_vssrani_b_h:
4517 case LoongArch::BI__builtin_lsx_vssrani_bu_h:
4518 case LoongArch::BI__builtin_lsx_vsrarni_b_h:
4519 case LoongArch::BI__builtin_lsx_vsrlni_b_h:
4520 case LoongArch::BI__builtin_lsx_vsrlrni_b_h:
4521 case LoongArch::BI__builtin_lsx_vssrlni_b_h:
4522 case LoongArch::BI__builtin_lsx_vssrlni_bu_h:
4523 case LoongArch::BI__builtin_lsx_vssrlrni_b_h:
4524 case LoongArch::BI__builtin_lsx_vssrlrni_bu_h:
4525 case LoongArch::BI__builtin_lsx_vsrani_b_h:
4526 return BuiltinConstantArgRange(TheCall, 2, 0, 15);
4527 case LoongArch::BI__builtin_lsx_vslei_bu:
4528 case LoongArch::BI__builtin_lsx_vslei_hu:
4529 case LoongArch::BI__builtin_lsx_vslei_wu:
4530 case LoongArch::BI__builtin_lsx_vslei_du:
4531 case LoongArch::BI__builtin_lsx_vslti_bu:
4532 case LoongArch::BI__builtin_lsx_vslti_hu:
4533 case LoongArch::BI__builtin_lsx_vslti_wu:
4534 case LoongArch::BI__builtin_lsx_vslti_du:
4535 case LoongArch::BI__builtin_lsx_vmaxi_bu:
4536 case LoongArch::BI__builtin_lsx_vmaxi_hu:
4537 case LoongArch::BI__builtin_lsx_vmaxi_wu:
4538 case LoongArch::BI__builtin_lsx_vmaxi_du:
4539 case LoongArch::BI__builtin_lsx_vmini_bu:
4540 case LoongArch::BI__builtin_lsx_vmini_hu:
4541 case LoongArch::BI__builtin_lsx_vmini_wu:
4542 case LoongArch::BI__builtin_lsx_vmini_du:
4543 case LoongArch::BI__builtin_lsx_vaddi_bu:
4544 case LoongArch::BI__builtin_lsx_vaddi_hu:
4545 case LoongArch::BI__builtin_lsx_vaddi_wu:
4546 case LoongArch::BI__builtin_lsx_vaddi_du:
4547 case LoongArch::BI__builtin_lsx_vbitclri_w:
4548 case LoongArch::BI__builtin_lsx_vbitrevi_w:
4549 case LoongArch::BI__builtin_lsx_vbitseti_w:
4550 case LoongArch::BI__builtin_lsx_vsat_w:
4551 case LoongArch::BI__builtin_lsx_vsat_wu:
4552 case LoongArch::BI__builtin_lsx_vslli_w:
4553 case LoongArch::BI__builtin_lsx_vsrai_w:
4554 case LoongArch::BI__builtin_lsx_vsrari_w:
4555 case LoongArch::BI__builtin_lsx_vsrli_w:
4556 case LoongArch::BI__builtin_lsx_vsllwil_d_w:
4557 case LoongArch::BI__builtin_lsx_vsllwil_du_wu:
4558 case LoongArch::BI__builtin_lsx_vsrlri_w:
4559 case LoongArch::BI__builtin_lsx_vrotri_w:
4560 case LoongArch::BI__builtin_lsx_vsubi_bu:
4561 case LoongArch::BI__builtin_lsx_vsubi_hu:
4562 case LoongArch::BI__builtin_lsx_vbsrl_v:
4563 case LoongArch::BI__builtin_lsx_vbsll_v:
4564 case LoongArch::BI__builtin_lsx_vsubi_wu:
4565 case LoongArch::BI__builtin_lsx_vsubi_du:
4566 return BuiltinConstantArgRange(TheCall, 1, 0, 31);
4567 case LoongArch::BI__builtin_lsx_vssrarni_h_w:
4568 case LoongArch::BI__builtin_lsx_vssrarni_hu_w:
4569 case LoongArch::BI__builtin_lsx_vssrani_h_w:
4570 case LoongArch::BI__builtin_lsx_vssrani_hu_w:
4571 case LoongArch::BI__builtin_lsx_vsrarni_h_w:
4572 case LoongArch::BI__builtin_lsx_vsrani_h_w:
4573 case LoongArch::BI__builtin_lsx_vfrstpi_b:
4574 case LoongArch::BI__builtin_lsx_vfrstpi_h:
4575 case LoongArch::BI__builtin_lsx_vsrlni_h_w:
4576 case LoongArch::BI__builtin_lsx_vsrlrni_h_w:
4577 case LoongArch::BI__builtin_lsx_vssrlni_h_w:
4578 case LoongArch::BI__builtin_lsx_vssrlni_hu_w:
4579 case LoongArch::BI__builtin_lsx_vssrlrni_h_w:
4580 case LoongArch::BI__builtin_lsx_vssrlrni_hu_w:
4581 return BuiltinConstantArgRange(TheCall, 2, 0, 31);
4582 case LoongArch::BI__builtin_lsx_vbitclri_d:
4583 case LoongArch::BI__builtin_lsx_vbitrevi_d:
4584 case LoongArch::BI__builtin_lsx_vbitseti_d:
4585 case LoongArch::BI__builtin_lsx_vsat_d:
4586 case LoongArch::BI__builtin_lsx_vsat_du:
4587 case LoongArch::BI__builtin_lsx_vslli_d:
4588 case LoongArch::BI__builtin_lsx_vsrai_d:
4589 case LoongArch::BI__builtin_lsx_vsrli_d:
4590 case LoongArch::BI__builtin_lsx_vsrari_d:
4591 case LoongArch::BI__builtin_lsx_vrotri_d:
4592 case LoongArch::BI__builtin_lsx_vsrlri_d:
4593 return BuiltinConstantArgRange(TheCall, 1, 0, 63);
4594 case LoongArch::BI__builtin_lsx_vssrarni_w_d:
4595 case LoongArch::BI__builtin_lsx_vssrarni_wu_d:
4596 case LoongArch::BI__builtin_lsx_vssrani_w_d:
4597 case LoongArch::BI__builtin_lsx_vssrani_wu_d:
4598 case LoongArch::BI__builtin_lsx_vsrarni_w_d:
4599 case LoongArch::BI__builtin_lsx_vsrlni_w_d:
4600 case LoongArch::BI__builtin_lsx_vsrlrni_w_d:
4601 case LoongArch::BI__builtin_lsx_vssrlni_w_d:
4602 case LoongArch::BI__builtin_lsx_vssrlni_wu_d:
4603 case LoongArch::BI__builtin_lsx_vssrlrni_w_d:
4604 case LoongArch::BI__builtin_lsx_vssrlrni_wu_d:
4605 case LoongArch::BI__builtin_lsx_vsrani_w_d:
4606 return BuiltinConstantArgRange(TheCall, 2, 0, 63);
4607 case LoongArch::BI__builtin_lsx_vssrarni_d_q:
4608 case LoongArch::BI__builtin_lsx_vssrarni_du_q:
4609 case LoongArch::BI__builtin_lsx_vssrani_d_q:
4610 case LoongArch::BI__builtin_lsx_vssrani_du_q:
4611 case LoongArch::BI__builtin_lsx_vsrarni_d_q:
4612 case LoongArch::BI__builtin_lsx_vssrlni_d_q:
4613 case LoongArch::BI__builtin_lsx_vssrlni_du_q:
4614 case LoongArch::BI__builtin_lsx_vssrlrni_d_q:
4615 case LoongArch::BI__builtin_lsx_vssrlrni_du_q:
4616 case LoongArch::BI__builtin_lsx_vsrani_d_q:
4617 case LoongArch::BI__builtin_lsx_vsrlrni_d_q:
4618 case LoongArch::BI__builtin_lsx_vsrlni_d_q:
4619 return BuiltinConstantArgRange(TheCall, 2, 0, 127);
4620 case LoongArch::BI__builtin_lsx_vseqi_b:
4621 case LoongArch::BI__builtin_lsx_vseqi_h:
4622 case LoongArch::BI__builtin_lsx_vseqi_w:
4623 case LoongArch::BI__builtin_lsx_vseqi_d:
4624 case LoongArch::BI__builtin_lsx_vslti_b:
4625 case LoongArch::BI__builtin_lsx_vslti_h:
4626 case LoongArch::BI__builtin_lsx_vslti_w:
4627 case LoongArch::BI__builtin_lsx_vslti_d:
4628 case LoongArch::BI__builtin_lsx_vslei_b:
4629 case LoongArch::BI__builtin_lsx_vslei_h:
4630 case LoongArch::BI__builtin_lsx_vslei_w:
4631 case LoongArch::BI__builtin_lsx_vslei_d:
4632 case LoongArch::BI__builtin_lsx_vmaxi_b:
4633 case LoongArch::BI__builtin_lsx_vmaxi_h:
4634 case LoongArch::BI__builtin_lsx_vmaxi_w:
4635 case LoongArch::BI__builtin_lsx_vmaxi_d:
4636 case LoongArch::BI__builtin_lsx_vmini_b:
4637 case LoongArch::BI__builtin_lsx_vmini_h:
4638 case LoongArch::BI__builtin_lsx_vmini_w:
4639 case LoongArch::BI__builtin_lsx_vmini_d:
4640 return BuiltinConstantArgRange(TheCall, 1, -16, 15);
4641 case LoongArch::BI__builtin_lsx_vandi_b:
4642 case LoongArch::BI__builtin_lsx_vnori_b:
4643 case LoongArch::BI__builtin_lsx_vori_b:
4644 case LoongArch::BI__builtin_lsx_vshuf4i_b:
4645 case LoongArch::BI__builtin_lsx_vshuf4i_h:
4646 case LoongArch::BI__builtin_lsx_vshuf4i_w:
4647 case LoongArch::BI__builtin_lsx_vxori_b:
4648 return BuiltinConstantArgRange(TheCall, 1, 0, 255);
4649 case LoongArch::BI__builtin_lsx_vbitseli_b:
4650 case LoongArch::BI__builtin_lsx_vshuf4i_d:
4651 case LoongArch::BI__builtin_lsx_vextrins_b:
4652 case LoongArch::BI__builtin_lsx_vextrins_h:
4653 case LoongArch::BI__builtin_lsx_vextrins_w:
4654 case LoongArch::BI__builtin_lsx_vextrins_d:
4655 case LoongArch::BI__builtin_lsx_vpermi_w:
4656 return BuiltinConstantArgRange(TheCall, 2, 0, 255);
4657 case LoongArch::BI__builtin_lsx_vpickve2gr_b:
4658 case LoongArch::BI__builtin_lsx_vpickve2gr_bu:
4659 case LoongArch::BI__builtin_lsx_vreplvei_b:
4660 return BuiltinConstantArgRange(TheCall, 1, 0, 15);
4661 case LoongArch::BI__builtin_lsx_vinsgr2vr_b:
4662 return BuiltinConstantArgRange(TheCall, 2, 0, 15);
4663 case LoongArch::BI__builtin_lsx_vpickve2gr_h:
4664 case LoongArch::BI__builtin_lsx_vpickve2gr_hu:
4665 case LoongArch::BI__builtin_lsx_vreplvei_h:
4666 return BuiltinConstantArgRange(TheCall, 1, 0, 7);
4667 case LoongArch::BI__builtin_lsx_vinsgr2vr_h:
4668 return BuiltinConstantArgRange(TheCall, 2, 0, 7);
4669 case LoongArch::BI__builtin_lsx_vpickve2gr_w:
4670 case LoongArch::BI__builtin_lsx_vpickve2gr_wu:
4671 case LoongArch::BI__builtin_lsx_vreplvei_w:
4672 return BuiltinConstantArgRange(TheCall, 1, 0, 3);
4673 case LoongArch::BI__builtin_lsx_vinsgr2vr_w:
4674 return BuiltinConstantArgRange(TheCall, 2, 0, 3);
4675 case LoongArch::BI__builtin_lsx_vpickve2gr_d:
4676 case LoongArch::BI__builtin_lsx_vpickve2gr_du:
4677 case LoongArch::BI__builtin_lsx_vreplvei_d:
4678 return BuiltinConstantArgRange(TheCall, 1, 0, 1);
4679 case LoongArch::BI__builtin_lsx_vinsgr2vr_d:
4680 return BuiltinConstantArgRange(TheCall, 2, 0, 1);
4681 case LoongArch::BI__builtin_lsx_vstelm_b:
4682 return BuiltinConstantArgRange(TheCall, 2, -128, 127) ||
4683 BuiltinConstantArgRange(TheCall, 3, 0, 15);
4684 case LoongArch::BI__builtin_lsx_vstelm_h:
4685 return BuiltinConstantArgRange(TheCall, 2, -256, 254) ||
4686 BuiltinConstantArgRange(TheCall, 3, 0, 7);
4687 case LoongArch::BI__builtin_lsx_vstelm_w:
4688 return BuiltinConstantArgRange(TheCall, 2, -512, 508) ||
4689 BuiltinConstantArgRange(TheCall, 3, 0, 3);
4690 case LoongArch::BI__builtin_lsx_vstelm_d:
4691 return BuiltinConstantArgRange(TheCall, 2, -1024, 1016) ||
4692 BuiltinConstantArgRange(TheCall, 3, 0, 1);
4693 case LoongArch::BI__builtin_lsx_vldrepl_b:
4694 case LoongArch::BI__builtin_lsx_vld:
4695 return BuiltinConstantArgRange(TheCall, 1, -2048, 2047);
4696 case LoongArch::BI__builtin_lsx_vldrepl_h:
4697 return BuiltinConstantArgRange(TheCall, 1, -2048, 2046);
4698 case LoongArch::BI__builtin_lsx_vldrepl_w:
4699 return BuiltinConstantArgRange(TheCall, 1, -2048, 2044);
4700 case LoongArch::BI__builtin_lsx_vldrepl_d:
4701 return BuiltinConstantArgRange(TheCall, 1, -2048, 2040);
4702 case LoongArch::BI__builtin_lsx_vst:
4703 return BuiltinConstantArgRange(TheCall, 2, -2048, 2047);
4704 case LoongArch::BI__builtin_lsx_vldi:
4705 return BuiltinConstantArgRange(TheCall, 0, -4096, 4095);
4706 case LoongArch::BI__builtin_lsx_vrepli_b:
4707 case LoongArch::BI__builtin_lsx_vrepli_h:
4708 case LoongArch::BI__builtin_lsx_vrepli_w:
4709 case LoongArch::BI__builtin_lsx_vrepli_d:
4710 return BuiltinConstantArgRange(TheCall, 0, -512, 511);
4711
4712 // LASX intrinsics.
4713 case LoongArch::BI__builtin_lasx_xvbitclri_b:
4714 case LoongArch::BI__builtin_lasx_xvbitrevi_b:
4715 case LoongArch::BI__builtin_lasx_xvbitseti_b:
4716 case LoongArch::BI__builtin_lasx_xvsat_b:
4717 case LoongArch::BI__builtin_lasx_xvsat_bu:
4718 case LoongArch::BI__builtin_lasx_xvslli_b:
4719 case LoongArch::BI__builtin_lasx_xvsrai_b:
4720 case LoongArch::BI__builtin_lasx_xvsrari_b:
4721 case LoongArch::BI__builtin_lasx_xvsrli_b:
4722 case LoongArch::BI__builtin_lasx_xvsllwil_h_b:
4723 case LoongArch::BI__builtin_lasx_xvsllwil_hu_bu:
4724 case LoongArch::BI__builtin_lasx_xvrotri_b:
4725 case LoongArch::BI__builtin_lasx_xvsrlri_b:
4726 return BuiltinConstantArgRange(TheCall, 1, 0, 7);
4727 case LoongArch::BI__builtin_lasx_xvbitclri_h:
4728 case LoongArch::BI__builtin_lasx_xvbitrevi_h:
4729 case LoongArch::BI__builtin_lasx_xvbitseti_h:
4730 case LoongArch::BI__builtin_lasx_xvsat_h:
4731 case LoongArch::BI__builtin_lasx_xvsat_hu:
4732 case LoongArch::BI__builtin_lasx_xvslli_h:
4733 case LoongArch::BI__builtin_lasx_xvsrai_h:
4734 case LoongArch::BI__builtin_lasx_xvsrari_h:
4735 case LoongArch::BI__builtin_lasx_xvsrli_h:
4736 case LoongArch::BI__builtin_lasx_xvsllwil_w_h:
4737 case LoongArch::BI__builtin_lasx_xvsllwil_wu_hu:
4738 case LoongArch::BI__builtin_lasx_xvrotri_h:
4739 case LoongArch::BI__builtin_lasx_xvsrlri_h:
4740 return BuiltinConstantArgRange(TheCall, 1, 0, 15);
4741 case LoongArch::BI__builtin_lasx_xvssrarni_b_h:
4742 case LoongArch::BI__builtin_lasx_xvssrarni_bu_h:
4743 case LoongArch::BI__builtin_lasx_xvssrani_b_h:
4744 case LoongArch::BI__builtin_lasx_xvssrani_bu_h:
4745 case LoongArch::BI__builtin_lasx_xvsrarni_b_h:
4746 case LoongArch::BI__builtin_lasx_xvsrlni_b_h:
4747 case LoongArch::BI__builtin_lasx_xvsrlrni_b_h:
4748 case LoongArch::BI__builtin_lasx_xvssrlni_b_h:
4749 case LoongArch::BI__builtin_lasx_xvssrlni_bu_h:
4750 case LoongArch::BI__builtin_lasx_xvssrlrni_b_h:
4751 case LoongArch::BI__builtin_lasx_xvssrlrni_bu_h:
4752 case LoongArch::BI__builtin_lasx_xvsrani_b_h:
4753 return BuiltinConstantArgRange(TheCall, 2, 0, 15);
4754 case LoongArch::BI__builtin_lasx_xvslei_bu:
4755 case LoongArch::BI__builtin_lasx_xvslei_hu:
4756 case LoongArch::BI__builtin_lasx_xvslei_wu:
4757 case LoongArch::BI__builtin_lasx_xvslei_du:
4758 case LoongArch::BI__builtin_lasx_xvslti_bu:
4759 case LoongArch::BI__builtin_lasx_xvslti_hu:
4760 case LoongArch::BI__builtin_lasx_xvslti_wu:
4761 case LoongArch::BI__builtin_lasx_xvslti_du:
4762 case LoongArch::BI__builtin_lasx_xvmaxi_bu:
4763 case LoongArch::BI__builtin_lasx_xvmaxi_hu:
4764 case LoongArch::BI__builtin_lasx_xvmaxi_wu:
4765 case LoongArch::BI__builtin_lasx_xvmaxi_du:
4766 case LoongArch::BI__builtin_lasx_xvmini_bu:
4767 case LoongArch::BI__builtin_lasx_xvmini_hu:
4768 case LoongArch::BI__builtin_lasx_xvmini_wu:
4769 case LoongArch::BI__builtin_lasx_xvmini_du:
4770 case LoongArch::BI__builtin_lasx_xvaddi_bu:
4771 case LoongArch::BI__builtin_lasx_xvaddi_hu:
4772 case LoongArch::BI__builtin_lasx_xvaddi_wu:
4773 case LoongArch::BI__builtin_lasx_xvaddi_du:
4774 case LoongArch::BI__builtin_lasx_xvbitclri_w:
4775 case LoongArch::BI__builtin_lasx_xvbitrevi_w:
4776 case LoongArch::BI__builtin_lasx_xvbitseti_w:
4777 case LoongArch::BI__builtin_lasx_xvsat_w:
4778 case LoongArch::BI__builtin_lasx_xvsat_wu:
4779 case LoongArch::BI__builtin_lasx_xvslli_w:
4780 case LoongArch::BI__builtin_lasx_xvsrai_w:
4781 case LoongArch::BI__builtin_lasx_xvsrari_w:
4782 case LoongArch::BI__builtin_lasx_xvsrli_w:
4783 case LoongArch::BI__builtin_lasx_xvsllwil_d_w:
4784 case LoongArch::BI__builtin_lasx_xvsllwil_du_wu:
4785 case LoongArch::BI__builtin_lasx_xvsrlri_w:
4786 case LoongArch::BI__builtin_lasx_xvrotri_w:
4787 case LoongArch::BI__builtin_lasx_xvsubi_bu:
4788 case LoongArch::BI__builtin_lasx_xvsubi_hu:
4789 case LoongArch::BI__builtin_lasx_xvsubi_wu:
4790 case LoongArch::BI__builtin_lasx_xvsubi_du:
4791 case LoongArch::BI__builtin_lasx_xvbsrl_v:
4792 case LoongArch::BI__builtin_lasx_xvbsll_v:
4793 return BuiltinConstantArgRange(TheCall, 1, 0, 31);
4794 case LoongArch::BI__builtin_lasx_xvssrarni_h_w:
4795 case LoongArch::BI__builtin_lasx_xvssrarni_hu_w:
4796 case LoongArch::BI__builtin_lasx_xvssrani_h_w:
4797 case LoongArch::BI__builtin_lasx_xvssrani_hu_w:
4798 case LoongArch::BI__builtin_lasx_xvsrarni_h_w:
4799 case LoongArch::BI__builtin_lasx_xvsrani_h_w:
4800 case LoongArch::BI__builtin_lasx_xvfrstpi_b:
4801 case LoongArch::BI__builtin_lasx_xvfrstpi_h:
4802 case LoongArch::BI__builtin_lasx_xvsrlni_h_w:
4803 case LoongArch::BI__builtin_lasx_xvsrlrni_h_w:
4804 case LoongArch::BI__builtin_lasx_xvssrlni_h_w:
4805 case LoongArch::BI__builtin_lasx_xvssrlni_hu_w:
4806 case LoongArch::BI__builtin_lasx_xvssrlrni_h_w:
4807 case LoongArch::BI__builtin_lasx_xvssrlrni_hu_w:
4808 return BuiltinConstantArgRange(TheCall, 2, 0, 31);
4809 case LoongArch::BI__builtin_lasx_xvbitclri_d:
4810 case LoongArch::BI__builtin_lasx_xvbitrevi_d:
4811 case LoongArch::BI__builtin_lasx_xvbitseti_d:
4812 case LoongArch::BI__builtin_lasx_xvsat_d:
4813 case LoongArch::BI__builtin_lasx_xvsat_du:
4814 case LoongArch::BI__builtin_lasx_xvslli_d:
4815 case LoongArch::BI__builtin_lasx_xvsrai_d:
4816 case LoongArch::BI__builtin_lasx_xvsrli_d:
4817 case LoongArch::BI__builtin_lasx_xvsrari_d:
4818 case LoongArch::BI__builtin_lasx_xvrotri_d:
4819 case LoongArch::BI__builtin_lasx_xvsrlri_d:
4820 return BuiltinConstantArgRange(TheCall, 1, 0, 63);
4821 case LoongArch::BI__builtin_lasx_xvssrarni_w_d:
4822 case LoongArch::BI__builtin_lasx_xvssrarni_wu_d:
4823 case LoongArch::BI__builtin_lasx_xvssrani_w_d:
4824 case LoongArch::BI__builtin_lasx_xvssrani_wu_d:
4825 case LoongArch::BI__builtin_lasx_xvsrarni_w_d:
4826 case LoongArch::BI__builtin_lasx_xvsrlni_w_d:
4827 case LoongArch::BI__builtin_lasx_xvsrlrni_w_d:
4828 case LoongArch::BI__builtin_lasx_xvssrlni_w_d:
4829 case LoongArch::BI__builtin_lasx_xvssrlni_wu_d:
4830 case LoongArch::BI__builtin_lasx_xvssrlrni_w_d:
4831 case LoongArch::BI__builtin_lasx_xvssrlrni_wu_d:
4832 case LoongArch::BI__builtin_lasx_xvsrani_w_d:
4833 return BuiltinConstantArgRange(TheCall, 2, 0, 63);
4834 case LoongArch::BI__builtin_lasx_xvssrarni_d_q:
4835 case LoongArch::BI__builtin_lasx_xvssrarni_du_q:
4836 case LoongArch::BI__builtin_lasx_xvssrani_d_q:
4837 case LoongArch::BI__builtin_lasx_xvssrani_du_q:
4838 case LoongArch::BI__builtin_lasx_xvsrarni_d_q:
4839 case LoongArch::BI__builtin_lasx_xvssrlni_d_q:
4840 case LoongArch::BI__builtin_lasx_xvssrlni_du_q:
4841 case LoongArch::BI__builtin_lasx_xvssrlrni_d_q:
4842 case LoongArch::BI__builtin_lasx_xvssrlrni_du_q:
4843 case LoongArch::BI__builtin_lasx_xvsrani_d_q:
4844 case LoongArch::BI__builtin_lasx_xvsrlni_d_q:
4845 case LoongArch::BI__builtin_lasx_xvsrlrni_d_q:
4846 return BuiltinConstantArgRange(TheCall, 2, 0, 127);
4847 case LoongArch::BI__builtin_lasx_xvseqi_b:
4848 case LoongArch::BI__builtin_lasx_xvseqi_h:
4849 case LoongArch::BI__builtin_lasx_xvseqi_w:
4850 case LoongArch::BI__builtin_lasx_xvseqi_d:
4851 case LoongArch::BI__builtin_lasx_xvslti_b:
4852 case LoongArch::BI__builtin_lasx_xvslti_h:
4853 case LoongArch::BI__builtin_lasx_xvslti_w:
4854 case LoongArch::BI__builtin_lasx_xvslti_d:
4855 case LoongArch::BI__builtin_lasx_xvslei_b:
4856 case LoongArch::BI__builtin_lasx_xvslei_h:
4857 case LoongArch::BI__builtin_lasx_xvslei_w:
4858 case LoongArch::BI__builtin_lasx_xvslei_d:
4859 case LoongArch::BI__builtin_lasx_xvmaxi_b:
4860 case LoongArch::BI__builtin_lasx_xvmaxi_h:
4861 case LoongArch::BI__builtin_lasx_xvmaxi_w:
4862 case LoongArch::BI__builtin_lasx_xvmaxi_d:
4863 case LoongArch::BI__builtin_lasx_xvmini_b:
4864 case LoongArch::BI__builtin_lasx_xvmini_h:
4865 case LoongArch::BI__builtin_lasx_xvmini_w:
4866 case LoongArch::BI__builtin_lasx_xvmini_d:
4867 return BuiltinConstantArgRange(TheCall, 1, -16, 15);
4868 case LoongArch::BI__builtin_lasx_xvandi_b:
4869 case LoongArch::BI__builtin_lasx_xvnori_b:
4870 case LoongArch::BI__builtin_lasx_xvori_b:
4871 case LoongArch::BI__builtin_lasx_xvshuf4i_b:
4872 case LoongArch::BI__builtin_lasx_xvshuf4i_h:
4873 case LoongArch::BI__builtin_lasx_xvshuf4i_w:
4874 case LoongArch::BI__builtin_lasx_xvxori_b:
4875 case LoongArch::BI__builtin_lasx_xvpermi_d:
4876 return BuiltinConstantArgRange(TheCall, 1, 0, 255);
4877 case LoongArch::BI__builtin_lasx_xvbitseli_b:
4878 case LoongArch::BI__builtin_lasx_xvshuf4i_d:
4879 case LoongArch::BI__builtin_lasx_xvextrins_b:
4880 case LoongArch::BI__builtin_lasx_xvextrins_h:
4881 case LoongArch::BI__builtin_lasx_xvextrins_w:
4882 case LoongArch::BI__builtin_lasx_xvextrins_d:
4883 case LoongArch::BI__builtin_lasx_xvpermi_q:
4884 case LoongArch::BI__builtin_lasx_xvpermi_w:
4885 return BuiltinConstantArgRange(TheCall, 2, 0, 255);
4886 case LoongArch::BI__builtin_lasx_xvrepl128vei_b:
4887 return BuiltinConstantArgRange(TheCall, 1, 0, 15);
4888 case LoongArch::BI__builtin_lasx_xvrepl128vei_h:
4889 case LoongArch::BI__builtin_lasx_xvpickve2gr_w:
4890 case LoongArch::BI__builtin_lasx_xvpickve2gr_wu:
4891 case LoongArch::BI__builtin_lasx_xvpickve_w_f:
4892 case LoongArch::BI__builtin_lasx_xvpickve_w:
4893 return BuiltinConstantArgRange(TheCall, 1, 0, 7);
4894 case LoongArch::BI__builtin_lasx_xvinsgr2vr_w:
4895 case LoongArch::BI__builtin_lasx_xvinsve0_w:
4896 return BuiltinConstantArgRange(TheCall, 2, 0, 7);
4897 case LoongArch::BI__builtin_lasx_xvrepl128vei_w:
4898 case LoongArch::BI__builtin_lasx_xvpickve2gr_d:
4899 case LoongArch::BI__builtin_lasx_xvpickve2gr_du:
4900 case LoongArch::BI__builtin_lasx_xvpickve_d_f:
4901 case LoongArch::BI__builtin_lasx_xvpickve_d:
4902 return BuiltinConstantArgRange(TheCall, 1, 0, 3);
4903 case LoongArch::BI__builtin_lasx_xvinsve0_d:
4904 case LoongArch::BI__builtin_lasx_xvinsgr2vr_d:
4905 return BuiltinConstantArgRange(TheCall, 2, 0, 3);
4906 case LoongArch::BI__builtin_lasx_xvstelm_b:
4907 return BuiltinConstantArgRange(TheCall, 2, -128, 127) ||
4908 BuiltinConstantArgRange(TheCall, 3, 0, 31);
4909 case LoongArch::BI__builtin_lasx_xvstelm_h:
4910 return BuiltinConstantArgRange(TheCall, 2, -256, 254) ||
4911 BuiltinConstantArgRange(TheCall, 3, 0, 15);
4912 case LoongArch::BI__builtin_lasx_xvstelm_w:
4913 return BuiltinConstantArgRange(TheCall, 2, -512, 508) ||
4914 BuiltinConstantArgRange(TheCall, 3, 0, 7);
4915 case LoongArch::BI__builtin_lasx_xvstelm_d:
4916 return BuiltinConstantArgRange(TheCall, 2, -1024, 1016) ||
4917 BuiltinConstantArgRange(TheCall, 3, 0, 3);
4918 case LoongArch::BI__builtin_lasx_xvrepl128vei_d:
4919 return BuiltinConstantArgRange(TheCall, 1, 0, 1);
4920 case LoongArch::BI__builtin_lasx_xvldrepl_b:
4921 case LoongArch::BI__builtin_lasx_xvld:
4922 return BuiltinConstantArgRange(TheCall, 1, -2048, 2047);
4923 case LoongArch::BI__builtin_lasx_xvldrepl_h:
4924 return BuiltinConstantArgRange(TheCall, 1, -2048, 2046);
4925 case LoongArch::BI__builtin_lasx_xvldrepl_w:
4926 return BuiltinConstantArgRange(TheCall, 1, -2048, 2044);
4927 case LoongArch::BI__builtin_lasx_xvldrepl_d:
4928 return BuiltinConstantArgRange(TheCall, 1, -2048, 2040);
4929 case LoongArch::BI__builtin_lasx_xvst:
4930 return BuiltinConstantArgRange(TheCall, 2, -2048, 2047);
4931 case LoongArch::BI__builtin_lasx_xvldi:
4932 return BuiltinConstantArgRange(TheCall, 0, -4096, 4095);
4933 case LoongArch::BI__builtin_lasx_xvrepli_b:
4934 case LoongArch::BI__builtin_lasx_xvrepli_h:
4935 case LoongArch::BI__builtin_lasx_xvrepli_w:
4936 case LoongArch::BI__builtin_lasx_xvrepli_d:
4937 return BuiltinConstantArgRange(TheCall, 0, -512, 511);
4938 }
4939 return false;
4940}
4941
4942bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
4943 unsigned BuiltinID, CallExpr *TheCall) {
4944 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
4945 CheckMipsBuiltinArgument(BuiltinID, TheCall);
4946}
4947
4948bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
4949 CallExpr *TheCall) {
4950
4951 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
4952 BuiltinID <= Mips::BI__builtin_mips_lwx) {
4953 if (!TI.hasFeature("dsp"))
4954 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
4955 }
4956
4957 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
4958 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
4959 if (!TI.hasFeature("dspr2"))
4960 return Diag(TheCall->getBeginLoc(),
4961 diag::err_mips_builtin_requires_dspr2);
4962 }
4963
4964 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
4965 BuiltinID <= Mips::BI__builtin_msa_xori_b) {
4966 if (!TI.hasFeature("msa"))
4967 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
4968 }
4969
4970 return false;
4971}
4972
4973// CheckMipsBuiltinArgument - Checks the constant value passed to the
4974// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
4975// ordering for DSP is unspecified. MSA is ordered by the data format used
4976// by the underlying instruction i.e., df/m, df/n and then by size.
4977//
4978// FIXME: The size tests here should instead be tablegen'd along with the
4979// definitions from include/clang/Basic/BuiltinsMips.def.
4980// FIXME: GCC is strict on signedness for some of these intrinsics, we should
4981// be too.
4982bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
4983 unsigned i = 0, l = 0, u = 0, m = 0;
4984 switch (BuiltinID) {
4985 default: return false;
4986 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
4987 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
4988 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
4989 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
4990 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
4991 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
4992 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
4993 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
4994 // df/m field.
4995 // These intrinsics take an unsigned 3 bit immediate.
4996 case Mips::BI__builtin_msa_bclri_b:
4997 case Mips::BI__builtin_msa_bnegi_b:
4998 case Mips::BI__builtin_msa_bseti_b:
4999 case Mips::BI__builtin_msa_sat_s_b:
5000 case Mips::BI__builtin_msa_sat_u_b:
5001 case Mips::BI__builtin_msa_slli_b:
5002 case Mips::BI__builtin_msa_srai_b:
5003 case Mips::BI__builtin_msa_srari_b:
5004 case Mips::BI__builtin_msa_srli_b:
5005 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
5006 case Mips::BI__builtin_msa_binsli_b:
5007 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
5008 // These intrinsics take an unsigned 4 bit immediate.
5009 case Mips::BI__builtin_msa_bclri_h:
5010 case Mips::BI__builtin_msa_bnegi_h:
5011 case Mips::BI__builtin_msa_bseti_h:
5012 case Mips::BI__builtin_msa_sat_s_h:
5013 case Mips::BI__builtin_msa_sat_u_h:
5014 case Mips::BI__builtin_msa_slli_h:
5015 case Mips::BI__builtin_msa_srai_h:
5016 case Mips::BI__builtin_msa_srari_h:
5017 case Mips::BI__builtin_msa_srli_h:
5018 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
5019 case Mips::BI__builtin_msa_binsli_h:
5020 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
5021 // These intrinsics take an unsigned 5 bit immediate.
5022 // The first block of intrinsics actually have an unsigned 5 bit field,
5023 // not a df/n field.
5024 case Mips::BI__builtin_msa_cfcmsa:
5025 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
5026 case Mips::BI__builtin_msa_clei_u_b:
5027 case Mips::BI__builtin_msa_clei_u_h:
5028 case Mips::BI__builtin_msa_clei_u_w:
5029 case Mips::BI__builtin_msa_clei_u_d:
5030 case Mips::BI__builtin_msa_clti_u_b:
5031 case Mips::BI__builtin_msa_clti_u_h:
5032 case Mips::BI__builtin_msa_clti_u_w:
5033 case Mips::BI__builtin_msa_clti_u_d:
5034 case Mips::BI__builtin_msa_maxi_u_b:
5035 case Mips::BI__builtin_msa_maxi_u_h:
5036 case Mips::BI__builtin_msa_maxi_u_w:
5037 case Mips::BI__builtin_msa_maxi_u_d:
5038 case Mips::BI__builtin_msa_mini_u_b:
5039 case Mips::BI__builtin_msa_mini_u_h:
5040 case Mips::BI__builtin_msa_mini_u_w:
5041 case Mips::BI__builtin_msa_mini_u_d:
5042 case Mips::BI__builtin_msa_addvi_b:
5043 case Mips::BI__builtin_msa_addvi_h:
5044 case Mips::BI__builtin_msa_addvi_w:
5045 case Mips::BI__builtin_msa_addvi_d:
5046 case Mips::BI__builtin_msa_bclri_w:
5047 case Mips::BI__builtin_msa_bnegi_w:
5048 case Mips::BI__builtin_msa_bseti_w:
5049 case Mips::BI__builtin_msa_sat_s_w:
5050 case Mips::BI__builtin_msa_sat_u_w:
5051 case Mips::BI__builtin_msa_slli_w:
5052 case Mips::BI__builtin_msa_srai_w:
5053 case Mips::BI__builtin_msa_srari_w:
5054 case Mips::BI__builtin_msa_srli_w:
5055 case Mips::BI__builtin_msa_srlri_w:
5056 case Mips::BI__builtin_msa_subvi_b:
5057 case Mips::BI__builtin_msa_subvi_h:
5058 case Mips::BI__builtin_msa_subvi_w:
5059 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
5060 case Mips::BI__builtin_msa_binsli_w:
5061 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
5062 // These intrinsics take an unsigned 6 bit immediate.
5063 case Mips::BI__builtin_msa_bclri_d:
5064 case Mips::BI__builtin_msa_bnegi_d:
5065 case Mips::BI__builtin_msa_bseti_d:
5066 case Mips::BI__builtin_msa_sat_s_d:
5067 case Mips::BI__builtin_msa_sat_u_d:
5068 case Mips::BI__builtin_msa_slli_d:
5069 case Mips::BI__builtin_msa_srai_d:
5070 case Mips::BI__builtin_msa_srari_d:
5071 case Mips::BI__builtin_msa_srli_d:
5072 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
5073 case Mips::BI__builtin_msa_binsli_d:
5074 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
5075 // These intrinsics take a signed 5 bit immediate.
5076 case Mips::BI__builtin_msa_ceqi_b:
5077 case Mips::BI__builtin_msa_ceqi_h:
5078 case Mips::BI__builtin_msa_ceqi_w:
5079 case Mips::BI__builtin_msa_ceqi_d:
5080 case Mips::BI__builtin_msa_clti_s_b:
5081 case Mips::BI__builtin_msa_clti_s_h:
5082 case Mips::BI__builtin_msa_clti_s_w:
5083 case Mips::BI__builtin_msa_clti_s_d:
5084 case Mips::BI__builtin_msa_clei_s_b:
5085 case Mips::BI__builtin_msa_clei_s_h:
5086 case Mips::BI__builtin_msa_clei_s_w:
5087 case Mips::BI__builtin_msa_clei_s_d:
5088 case Mips::BI__builtin_msa_maxi_s_b:
5089 case Mips::BI__builtin_msa_maxi_s_h:
5090 case Mips::BI__builtin_msa_maxi_s_w:
5091 case Mips::BI__builtin_msa_maxi_s_d:
5092 case Mips::BI__builtin_msa_mini_s_b:
5093 case Mips::BI__builtin_msa_mini_s_h:
5094 case Mips::BI__builtin_msa_mini_s_w:
5095 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
5096 // These intrinsics take an unsigned 8 bit immediate.
5097 case Mips::BI__builtin_msa_andi_b:
5098 case Mips::BI__builtin_msa_nori_b:
5099 case Mips::BI__builtin_msa_ori_b:
5100 case Mips::BI__builtin_msa_shf_b:
5101 case Mips::BI__builtin_msa_shf_h:
5102 case Mips::BI__builtin_msa_shf_w:
5103 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
5104 case Mips::BI__builtin_msa_bseli_b:
5105 case Mips::BI__builtin_msa_bmnzi_b:
5106 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
5107 // df/n format
5108 // These intrinsics take an unsigned 4 bit immediate.
5109 case Mips::BI__builtin_msa_copy_s_b:
5110 case Mips::BI__builtin_msa_copy_u_b:
5111 case Mips::BI__builtin_msa_insve_b:
5112 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
5113 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
5114 // These intrinsics take an unsigned 3 bit immediate.
5115 case Mips::BI__builtin_msa_copy_s_h:
5116 case Mips::BI__builtin_msa_copy_u_h:
5117 case Mips::BI__builtin_msa_insve_h:
5118 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
5119 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
5120 // These intrinsics take an unsigned 2 bit immediate.
5121 case Mips::BI__builtin_msa_copy_s_w:
5122 case Mips::BI__builtin_msa_copy_u_w:
5123 case Mips::BI__builtin_msa_insve_w:
5124 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
5125 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
5126 // These intrinsics take an unsigned 1 bit immediate.
5127 case Mips::BI__builtin_msa_copy_s_d:
5128 case Mips::BI__builtin_msa_copy_u_d:
5129 case Mips::BI__builtin_msa_insve_d:
5130 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
5131 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
5132 // Memory offsets and immediate loads.
5133 // These intrinsics take a signed 10 bit immediate.
5134 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
5135 case Mips::BI__builtin_msa_ldi_h:
5136 case Mips::BI__builtin_msa_ldi_w:
5137 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
5138 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
5139 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
5140 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
5141 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
5142 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
5143 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
5144 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
5145 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
5146 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
5147 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
5148 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
5149 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
5150 }
5151
5152 if (!m)
5153 return BuiltinConstantArgRange(TheCall, i, l, u);
5154
5155 return BuiltinConstantArgRange(TheCall, i, l, u) ||
5156 BuiltinConstantArgMultiple(TheCall, i, m);
5157}
5158
5159/// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
5160/// advancing the pointer over the consumed characters. The decoded type is
5161/// returned. If the decoded type represents a constant integer with a
5162/// constraint on its value then Mask is set to that value. The type descriptors
5163/// used in Str are specific to PPC MMA builtins and are documented in the file
5164/// defining the PPC builtins.
5165static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
5166 unsigned &Mask) {
5167 bool RequireICE = false;
5169 switch (*Str++) {
5170 case 'V':
5171 return Context.getVectorType(Context.UnsignedCharTy, 16,
5173 case 'i': {
5174 char *End;
5175 unsigned size = strtoul(Str, &End, 10);
5176 assert(End != Str && "Missing constant parameter constraint");
5177 Str = End;
5178 Mask = size;
5179 return Context.IntTy;
5180 }
5181 case 'W': {
5182 char *End;
5183 unsigned size = strtoul(Str, &End, 10);
5184 assert(End != Str && "Missing PowerPC MMA type size");
5185 Str = End;
5186 QualType Type;
5187 switch (size) {
5188 #define PPC_VECTOR_TYPE(typeName, Id, size) \
5189 case size: Type = Context.Id##Ty; break;
5190 #include "clang/Basic/PPCTypes.def"
5191 default: llvm_unreachable("Invalid PowerPC MMA vector type");
5192 }
5193 bool CheckVectorArgs = false;
5194 while (!CheckVectorArgs) {
5195 switch (*Str++) {
5196 case '*':
5197 Type = Context.getPointerType(Type);
5198 break;
5199 case 'C':
5200 Type = Type.withConst();
5201 break;
5202 default:
5203 CheckVectorArgs = true;
5204 --Str;
5205 break;
5206 }
5207 }
5208 return Type;
5209 }
5210 default:
5211 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
5212 }
5213}
5214
5215static bool isPPC_64Builtin(unsigned BuiltinID) {
5216 // These builtins only work on PPC 64bit targets.
5217 switch (BuiltinID) {
5218 case PPC::BI__builtin_divde:
5219 case PPC::BI__builtin_divdeu:
5220 case PPC::BI__builtin_bpermd:
5221 case PPC::BI__builtin_pdepd:
5222 case PPC::BI__builtin_pextd:
5223 case PPC::BI__builtin_ppc_ldarx:
5224 case PPC::BI__builtin_ppc_stdcx:
5225 case PPC::BI__builtin_ppc_tdw:
5226 case PPC::BI__builtin_ppc_trapd:
5227 case PPC::BI__builtin_ppc_cmpeqb:
5228 case PPC::BI__builtin_ppc_setb:
5229 case PPC::BI__builtin_ppc_mulhd:
5230 case PPC::BI__builtin_ppc_mulhdu:
5231 case PPC::BI__builtin_ppc_maddhd:
5232 case PPC::BI__builtin_ppc_maddhdu:
5233 case PPC::BI__builtin_ppc_maddld:
5234 case PPC::BI__builtin_ppc_load8r:
5235 case PPC::BI__builtin_ppc_store8r:
5236 case PPC::BI__builtin_ppc_insert_exp:
5237 case PPC::BI__builtin_ppc_extract_sig:
5238 case PPC::BI__builtin_ppc_addex:
5239 case PPC::BI__builtin_darn:
5240 case PPC::BI__builtin_darn_raw:
5241 case PPC::BI__builtin_ppc_compare_and_swaplp:
5242 case PPC::BI__builtin_ppc_fetch_and_addlp:
5243 case PPC::BI__builtin_ppc_fetch_and_andlp:
5244 case PPC::BI__builtin_ppc_fetch_and_orlp:
5245 case PPC::BI__builtin_ppc_fetch_and_swaplp:
5246 return true;
5247 }
5248 return false;
5249}
5250
5251/// Returns true if the argument consists of one contiguous run of 1s with any
5252/// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
5253/// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
5254/// since all 1s are not contiguous.
5255bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
5256 llvm::APSInt Result;
5257 // We can't check the value of a dependent argument.
5258 Expr *Arg = TheCall->getArg(ArgNum);
5259 if (Arg->isTypeDependent() || Arg->isValueDependent())
5260 return false;
5261
5262 // Check constant-ness first.
5263 if (BuiltinConstantArg(TheCall, ArgNum, Result))
5264 return true;
5265
5266 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
5267 if (Result.isShiftedMask() || (~Result).isShiftedMask())
5268 return false;
5269
5270 return Diag(TheCall->getBeginLoc(),
5271 diag::err_argument_not_contiguous_bit_field)
5272 << ArgNum << Arg->getSourceRange();
5273}
5274
5275bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
5276 CallExpr *TheCall) {
5277 unsigned i = 0, l = 0, u = 0;
5278 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
5279 llvm::APSInt Result;
5280
5281 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
5282 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
5283 << TheCall->getSourceRange();
5284
5285 switch (BuiltinID) {
5286 default: return false;
5287 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
5288 case PPC::BI__builtin_altivec_crypto_vshasigmad:
5289 return BuiltinConstantArgRange(TheCall, 1, 0, 1) ||
5290 BuiltinConstantArgRange(TheCall, 2, 0, 15);
5291 case PPC::BI__builtin_altivec_dss:
5292 return BuiltinConstantArgRange(TheCall, 0, 0, 3);
5293 case PPC::BI__builtin_tbegin:
5294 case PPC::BI__builtin_tend:
5295 return BuiltinConstantArgRange(TheCall, 0, 0, 1);
5296 case PPC::BI__builtin_tsr:
5297 return BuiltinConstantArgRange(TheCall, 0, 0, 7);
5298 case PPC::BI__builtin_tabortwc:
5299 case PPC::BI__builtin_tabortdc:
5300 return BuiltinConstantArgRange(TheCall, 0, 0, 31);
5301 case PPC::BI__builtin_tabortwci:
5302 case PPC::BI__builtin_tabortdci:
5303 return BuiltinConstantArgRange(TheCall, 0, 0, 31) ||
5304 BuiltinConstantArgRange(TheCall, 2, 0, 31);
5305 // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
5306 // __builtin_(un)pack_longdouble are available only if long double uses IBM
5307 // extended double representation.
5308 case PPC::BI__builtin_unpack_longdouble:
5309 if (BuiltinConstantArgRange(TheCall, 1, 0, 1))
5310 return true;
5311 [[fallthrough]];
5312 case PPC::BI__builtin_pack_longdouble:
5313 if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
5314 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
5315 << "ibmlongdouble";
5316 return false;
5317 case PPC::BI__builtin_altivec_dst:
5318 case PPC::BI__builtin_altivec_dstt:
5319 case PPC::BI__builtin_altivec_dstst:
5320 case PPC::BI__builtin_altivec_dststt:
5321 return BuiltinConstantArgRange(TheCall, 2, 0, 3);
5322 case PPC::BI__builtin_vsx_xxpermdi:
5323 case PPC::BI__builtin_vsx_xxsldwi:
5324 return BuiltinVSX(TheCall);
5325 case PPC::BI__builtin_unpack_vector_int128:
5326 return BuiltinConstantArgRange(TheCall, 1, 0, 1);
5327 case PPC::BI__builtin_altivec_vgnb:
5328 return BuiltinConstantArgRange(TheCall, 1, 2, 7);
5329 case PPC::BI__builtin_vsx_xxeval:
5330 return BuiltinConstantArgRange(TheCall, 3, 0, 255);
5331 case PPC::BI__builtin_altivec_vsldbi:
5332 return BuiltinConstantArgRange(TheCall, 2, 0, 7);
5333 case PPC::BI__builtin_altivec_vsrdbi:
5334 return BuiltinConstantArgRange(TheCall, 2, 0, 7);
5335 case PPC::BI__builtin_vsx_xxpermx:
5336 return BuiltinConstantArgRange(TheCall, 3, 0, 7);
5337 case PPC::BI__builtin_ppc_tw:
5338 case PPC::BI__builtin_ppc_tdw:
5339 return BuiltinConstantArgRange(TheCall, 2, 1, 31);
5340 case PPC::BI__builtin_ppc_cmprb:
5341 return BuiltinConstantArgRange(TheCall, 0, 0, 1);
5342 // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
5343 // be a constant that represents a contiguous bit field.
5344 case PPC::BI__builtin_ppc_rlwnm:
5345 return ValueIsRunOfOnes(TheCall, 2);
5346 case PPC::BI__builtin_ppc_rlwimi:
5347 return BuiltinConstantArgRange(TheCall, 2, 0, 31) ||
5348 ValueIsRunOfOnes(TheCall, 3);
5349 case PPC::BI__builtin_ppc_rldimi:
5350 return BuiltinConstantArgRange(TheCall, 2, 0, 63) ||
5351 ValueIsRunOfOnes(TheCall, 3);
5352 case PPC::BI__builtin_ppc_addex: {
5353 if (BuiltinConstantArgRange(TheCall, 2, 0, 3))
5354 return true;
5355 // Output warning for reserved values 1 to 3.
5356 int ArgValue =
5357 TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
5358 if (ArgValue != 0)
5359 Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
5360 << ArgValue;
5361 return false;
5362 }
5363 case PPC::BI__builtin_ppc_mtfsb0:
5364 case PPC::BI__builtin_ppc_mtfsb1:
5365 return BuiltinConstantArgRange(TheCall, 0, 0, 31);
5366 case PPC::BI__builtin_ppc_mtfsf:
5367 return BuiltinConstantArgRange(TheCall, 0, 0, 255);
5368 case PPC::BI__builtin_ppc_mtfsfi:
5369 return BuiltinConstantArgRange(TheCall, 0, 0, 7) ||
5370 BuiltinConstantArgRange(TheCall, 1, 0, 15);
5371 case PPC::BI__builtin_ppc_alignx:
5372 return BuiltinConstantArgPower2(TheCall, 0);
5373 case PPC::BI__builtin_ppc_rdlam:
5374 return ValueIsRunOfOnes(TheCall, 2);
5375 case PPC::BI__builtin_vsx_ldrmb:
5376 case PPC::BI__builtin_vsx_strmb:
5377 return BuiltinConstantArgRange(TheCall, 1, 1, 16);
5378 case PPC::BI__builtin_altivec_vcntmbb:
5379 case PPC::BI__builtin_altivec_vcntmbh:
5380 case PPC::BI__builtin_altivec_vcntmbw:
5381 case PPC::BI__builtin_altivec_vcntmbd:
5382 return BuiltinConstantArgRange(TheCall, 1, 0, 1);
5383 case PPC::BI__builtin_vsx_xxgenpcvbm:
5384 case PPC::BI__builtin_vsx_xxgenpcvhm:
5385 case PPC::BI__builtin_vsx_xxgenpcvwm:
5386 case PPC::BI__builtin_vsx_xxgenpcvdm:
5387 return BuiltinConstantArgRange(TheCall, 1, 0, 3);
5388 case PPC::BI__builtin_ppc_test_data_class: {
5389 // Check if the first argument of the __builtin_ppc_test_data_class call is
5390 // valid. The argument must be 'float' or 'double' or '__float128'.
5391 QualType ArgType = TheCall->getArg(0)->getType();
5392 if (ArgType != QualType(Context.FloatTy) &&
5393 ArgType != QualType(Context.DoubleTy) &&
5394 ArgType != QualType(Context.Float128Ty))
5395 return Diag(TheCall->getBeginLoc(),
5396 diag::err_ppc_invalid_test_data_class_type);
5397 return BuiltinConstantArgRange(TheCall, 1, 0, 127);
5398 }
5399 case PPC::BI__builtin_ppc_maxfe:
5400 case PPC::BI__builtin_ppc_minfe:
5401 case PPC::BI__builtin_ppc_maxfl:
5402 case PPC::BI__builtin_ppc_minfl:
5403 case PPC::BI__builtin_ppc_maxfs:
5404 case PPC::BI__builtin_ppc_minfs: {
5405 if (Context.getTargetInfo().getTriple().isOSAIX() &&
5406 (BuiltinID == PPC::BI__builtin_ppc_maxfe ||
5407 BuiltinID == PPC::BI__builtin_ppc_minfe))
5408 return Diag(TheCall->getBeginLoc(), diag::err_target_unsupported_type)
5409 << "builtin" << true << 128 << QualType(Context.LongDoubleTy)
5410 << false << Context.getTargetInfo().getTriple().str();
5411 // Argument type should be exact.
5413 if (BuiltinID == PPC::BI__builtin_ppc_maxfl ||
5414 BuiltinID == PPC::BI__builtin_ppc_minfl)
5415 ArgType = QualType(Context.DoubleTy);
5416 else if (BuiltinID == PPC::BI__builtin_ppc_maxfs ||
5417 BuiltinID == PPC::BI__builtin_ppc_minfs)
5418 ArgType = QualType(Context.FloatTy);
5419 for (unsigned I = 0, E = TheCall->getNumArgs(); I < E; ++I)
5420 if (TheCall->getArg(I)->getType() != ArgType)
5421 return Diag(TheCall->getBeginLoc(),
5422 diag::err_typecheck_convert_incompatible)
5423 << TheCall->getArg(I)->getType() << ArgType << 1 << 0 << 0;
5424 return false;
5425 }
5426#define CUSTOM_BUILTIN(Name, Intr, Types, Acc, Feature) \
5427 case PPC::BI__builtin_##Name: \
5428 return BuiltinPPCMMACall(TheCall, BuiltinID, Types);
5429#include "clang/Basic/BuiltinsPPC.def"
5430 }
5431 return BuiltinConstantArgRange(TheCall, i, l, u);
5432}
5433
5434// Check if the given type is a non-pointer PPC MMA type. This function is used
5435// in Sema to prevent invalid uses of restricted PPC MMA types.
5436bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
5437 if (Type->isPointerType() || Type->isArrayType())
5438 return false;
5439
5440 QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
5441#define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
5442 if (false
5443#include "clang/Basic/PPCTypes.def"
5444 ) {
5445 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
5446 return true;
5447 }
5448 return false;
5449}
5450
5451// Helper function for CheckHLSLBuiltinFunctionCall
5453 assert(TheCall->getNumArgs() > 1);
5454 ExprResult A = TheCall->getArg(0);
5455
5456 QualType ArgTyA = A.get()->getType();
5457
5458 auto *VecTyA = ArgTyA->getAs<VectorType>();
5459 SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5460
5461 for (unsigned i = 1; i < TheCall->getNumArgs(); ++i) {
5462 ExprResult B = TheCall->getArg(i);
5463 QualType ArgTyB = B.get()->getType();
5464 auto *VecTyB = ArgTyB->getAs<VectorType>();
5465 if (VecTyA == nullptr && VecTyB == nullptr)
5466 return false;
5467
5468 if (VecTyA && VecTyB) {
5469 bool retValue = false;
5470 if (VecTyA->getElementType() != VecTyB->getElementType()) {
5471 // Note: type promotion is intended to be handeled via the intrinsics
5472 // and not the builtin itself.
5473 S->Diag(TheCall->getBeginLoc(),
5474 diag::err_vec_builtin_incompatible_vector)
5475 << TheCall->getDirectCallee() << /*useAllTerminology*/ true
5476 << SourceRange(A.get()->getBeginLoc(), B.get()->getEndLoc());
5477 retValue = true;
5478 }
5479 if (VecTyA->getNumElements() != VecTyB->getNumElements()) {
5480 // You should only be hitting this case if you are calling the builtin
5481 // directly. HLSL intrinsics should avoid this case via a
5482 // HLSLVectorTruncation.
5483 S->Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5484 << TheCall->getDirectCallee() << /*useAllTerminology*/ true
5485 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5486 TheCall->getArg(1)->getEndLoc());
5487 retValue = true;
5488 }
5489 return retValue;
5490 }
5491 }
5492
5493 // Note: if we get here one of the args is a scalar which
5494 // requires a VectorSplat on Arg0 or Arg1
5495 S->Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5496 << TheCall->getDirectCallee() << /*useAllTerminology*/ true
5497 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5498 TheCall->getArg(1)->getEndLoc());
5499 return true;
5500}
5501
5503 Sema *S, CallExpr *TheCall, QualType ExpectedType,
5504 llvm::function_ref<bool(clang::QualType PassedType)> Check) {
5505 for (unsigned i = 0; i < TheCall->getNumArgs(); ++i) {
5506 QualType PassedType = TheCall->getArg(i)->getType();
5507 if (Check(PassedType)) {
5508 if (auto *VecTyA = PassedType->getAs<VectorType>())
5510 ExpectedType, VecTyA->getNumElements(), VecTyA->getVectorKind());
5511 S->Diag(TheCall->getArg(0)->getBeginLoc(),
5512 diag::err_typecheck_convert_incompatible)
5513 << PassedType << ExpectedType << 1 << 0 << 0;
5514 return true;
5515 }
5516 }
5517 return false;
5518}
5519
5521 auto checkAllFloatTypes = [](clang::QualType PassedType) -> bool {
5522 return !PassedType->hasFloatingRepresentation();
5523 };
5524 return CheckArgsTypesAreCorrect(S, TheCall, S->Context.FloatTy,
5525 checkAllFloatTypes);
5526}
5527
5529 auto checkFloatorHalf = [](clang::QualType PassedType) -> bool {
5530 clang::QualType BaseType =
5531 PassedType->isVectorType()
5532 ? PassedType->getAs<clang::VectorType>()->getElementType()
5533 : PassedType;
5534 return !BaseType->isHalfType() && !BaseType->isFloat32Type();
5535 };
5536 return CheckArgsTypesAreCorrect(S, TheCall, S->Context.FloatTy,
5537 checkFloatorHalf);
5538}
5539
5541 auto checkDoubleVector = [](clang::QualType PassedType) -> bool {
5542 if (const auto *VecTy = PassedType->getAs<VectorType>())
5543 return VecTy->getElementType()->isDoubleType();
5544 return false;
5545 };
5546 return CheckArgsTypesAreCorrect(S, TheCall, S->Context.FloatTy,
5547 checkDoubleVector);
5548}
5549
5551 auto checkAllUnsignedTypes = [](clang::QualType PassedType) -> bool {
5552 return !PassedType->hasUnsignedIntegerRepresentation();
5553 };
5554 return CheckArgsTypesAreCorrect(S, TheCall, S->Context.UnsignedIntTy,
5555 checkAllUnsignedTypes);
5556}
5557
5559 QualType ReturnType) {
5560 auto *VecTyA = TheCall->getArg(0)->getType()->getAs<VectorType>();
5561 if (VecTyA)
5562 ReturnType = S->Context.getVectorType(ReturnType, VecTyA->getNumElements(),
5564 TheCall->setType(ReturnType);
5565}
5566
5567// Note: returning true in this case results in CheckBuiltinFunctionCall
5568// returning an ExprError
5569bool Sema::CheckHLSLBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
5570 switch (BuiltinID) {
5571 case Builtin::BI__builtin_hlsl_elementwise_all:
5572 case Builtin::BI__builtin_hlsl_elementwise_any: {
5573 if (checkArgCount(*this, TheCall, 1))
5574 return true;
5575 break;
5576 }
5577 case Builtin::BI__builtin_hlsl_elementwise_clamp: {
5578 if (checkArgCount(*this, TheCall, 3))
5579 return true;
5580 if (CheckVectorElementCallArgs(this, TheCall))
5581 return true;
5582 if (BuiltinElementwiseTernaryMath(
5583 TheCall, /*CheckForFloatArgs*/
5584 TheCall->getArg(0)->getType()->hasFloatingRepresentation()))
5585 return true;
5586 break;
5587 }
5588 case Builtin::BI__builtin_hlsl_dot: {
5589 if (checkArgCount(*this, TheCall, 2))
5590 return true;
5591 if (CheckVectorElementCallArgs(this, TheCall))
5592 return true;
5593 if (BuiltinVectorToScalarMath(TheCall))
5594 return true;
5595 if (CheckNoDoubleVectors(this, TheCall))
5596 return true;
5597 break;
5598 }
5599 case Builtin::BI__builtin_hlsl_elementwise_rcp: {
5600 if (CheckAllArgsHaveFloatRepresentation(this, TheCall))
5601 return true;
5602 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5603 return true;
5604 break;
5605 }
5606 case Builtin::BI__builtin_hlsl_elementwise_rsqrt:
5607 case Builtin::BI__builtin_hlsl_elementwise_frac: {
5608 if (CheckFloatOrHalfRepresentations(this, TheCall))
5609 return true;
5610 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5611 return true;
5612 break;
5613 }
5614 case Builtin::BI__builtin_hlsl_elementwise_isinf: {
5615 if (CheckFloatOrHalfRepresentations(this, TheCall))
5616 return true;
5617 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5618 return true;
5619 SetElementTypeAsReturnType(this, TheCall, this->Context.BoolTy);
5620 break;
5621 }
5622 case Builtin::BI__builtin_hlsl_lerp: {
5623 if (checkArgCount(*this, TheCall, 3))
5624 return true;
5625 if (CheckVectorElementCallArgs(this, TheCall))
5626 return true;
5627 if (BuiltinElementwiseTernaryMath(TheCall))
5628 return true;
5629 if (CheckFloatOrHalfRepresentations(this, TheCall))
5630 return true;
5631 break;
5632 }
5633 case Builtin::BI__builtin_hlsl_mad: {
5634 if (checkArgCount(*this, TheCall, 3))
5635 return true;
5636 if (CheckVectorElementCallArgs(this, TheCall))
5637 return true;
5638 if (BuiltinElementwiseTernaryMath(
5639 TheCall, /*CheckForFloatArgs*/
5640 TheCall->getArg(0)->getType()->hasFloatingRepresentation()))
5641 return true;
5642 break;
5643 }
5644 // Note these are llvm builtins that we want to catch invalid intrinsic
5645 // generation. Normal handling of these builitns will occur elsewhere.
5646 case Builtin::BI__builtin_elementwise_bitreverse: {
5647 if (CheckUnsignedIntRepresentation(this, TheCall))
5648 return true;
5649 break;
5650 }
5651 case Builtin::BI__builtin_elementwise_ceil:
5652 case Builtin::BI__builtin_elementwise_cos:
5653 case Builtin::BI__builtin_elementwise_exp:
5654 case Builtin::BI__builtin_elementwise_exp2:
5655 case Builtin::BI__builtin_elementwise_floor:
5656 case Builtin::BI__builtin_elementwise_log:
5657 case Builtin::BI__builtin_elementwise_log2:
5658 case Builtin::BI__builtin_elementwise_log10:
5659 case Builtin::BI__builtin_elementwise_pow:
5660 case Builtin::BI__builtin_elementwise_roundeven:
5661 case Builtin::BI__builtin_elementwise_sin:
5662 case Builtin::BI__builtin_elementwise_sqrt:
5663 case Builtin::BI__builtin_elementwise_trunc: {
5664 if (CheckFloatOrHalfRepresentations(this, TheCall))
5665 return true;
5666 break;
5667 }
5668 }
5669 return false;
5670}
5671
5672bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
5673 CallExpr *TheCall) {
5674 // position of memory order and scope arguments in the builtin
5675 unsigned OrderIndex, ScopeIndex;
5676 switch (BuiltinID) {
5677 case AMDGPU::BI__builtin_amdgcn_get_fpenv:
5678 case AMDGPU::BI__builtin_amdgcn_set_fpenv:
5679 return false;
5680 case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
5681 case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
5682 case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
5683 case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
5684 OrderIndex = 2;
5685 ScopeIndex = 3;
5686 break;
5687 case AMDGPU::BI__builtin_amdgcn_fence:
5688 OrderIndex = 0;
5689 ScopeIndex = 1;
5690 break;
5691 default:
5692 return false;
5693 }
5694
5695 ExprResult Arg = TheCall->getArg(OrderIndex);
5696 auto ArgExpr = Arg.get();
5697 Expr::EvalResult ArgResult;
5698
5699 if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
5700 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
5701 << ArgExpr->getType();
5702 auto Ord = ArgResult.Val.getInt().getZExtValue();
5703
5704 // Check validity of memory ordering as per C11 / C++11's memody model.
5705 // Only fence needs check. Atomic dec/inc allow all memory orders.
5706 if (!llvm::isValidAtomicOrderingCABI(Ord))
5707 return Diag(ArgExpr->getBeginLoc(),
5708 diag::warn_atomic_op_has_invalid_memory_order)
5709 << 0 << ArgExpr->getSourceRange();
5710 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
5711 case llvm::AtomicOrderingCABI::relaxed:
5712 case llvm::AtomicOrderingCABI::consume:
5713 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
5714 return Diag(ArgExpr->getBeginLoc(),
5715 diag::warn_atomic_op_has_invalid_memory_order)
5716 << 0 << ArgExpr->getSourceRange();
5717 break;
5718 case llvm::AtomicOrderingCABI::acquire:
5719 case llvm::AtomicOrderingCABI::release:
5720 case llvm::AtomicOrderingCABI::acq_rel:
5721 case llvm::AtomicOrderingCABI::seq_cst:
5722 break;
5723 }
5724
5725 Arg = TheCall->getArg(ScopeIndex);
5726 ArgExpr = Arg.get();
5727 Expr::EvalResult ArgResult1;
5728 // Check that sync scope is a constant literal
5729 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
5730 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
5731 << ArgExpr->getType();
5732
5733 return false;
5734}
5735
5736bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
5737 llvm::APSInt Result;
5738
5739 // We can't check the value of a dependent argument.
5740 Expr *Arg = TheCall->getArg(ArgNum);
5741 if (Arg->isTypeDependent() || Arg->isValueDependent())
5742 return false;
5743
5744 // Check constant-ness first.
5745 if (BuiltinConstantArg(TheCall, ArgNum, Result))
5746 return true;
5747
5748 int64_t Val = Result.getSExtValue();
5749 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
5750 return false;
5751
5752 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
5753 << Arg->getSourceRange();
5754}
5755
5756static bool CheckInvalidVLENandLMUL(const TargetInfo &TI, CallExpr *TheCall,
5757 Sema &S, QualType Type, int EGW) {
5758 assert((EGW == 128 || EGW == 256) && "EGW can only be 128 or 256 bits");
5759
5760 // LMUL * VLEN >= EGW
5763 unsigned ElemSize = S.Context.getTypeSize(Info.ElementType);
5764 unsigned MinElemCount = Info.EC.getKnownMinValue();
5765
5766 unsigned EGS = EGW / ElemSize;
5767 // If EGS is less than or equal to the minimum number of elements, then the
5768 // type is valid.
5769 if (EGS <= MinElemCount)
5770 return false;
5771
5772 // Otherwise, we need vscale to be at least EGS / MinElemCont.
5773 assert(EGS % MinElemCount == 0);
5774 unsigned VScaleFactor = EGS / MinElemCount;
5775 // Vscale is VLEN/RVVBitsPerBlock.
5776 unsigned MinRequiredVLEN = VScaleFactor * llvm::RISCV::RVVBitsPerBlock;
5777 std::string RequiredExt = "zvl" + std::to_string(MinRequiredVLEN) + "b";
5778 if (!TI.hasFeature(RequiredExt))
5779 return S.Diag(TheCall->getBeginLoc(),
5780 diag::err_riscv_type_requires_extension) << Type << RequiredExt;
5781
5782 return false;
5783}
5784
5785bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
5786 unsigned BuiltinID,
5787 CallExpr *TheCall) {
5788 // vmulh.vv, vmulh.vx, vmulhu.vv, vmulhu.vx, vmulhsu.vv, vmulhsu.vx,
5789 // vsmul.vv, vsmul.vx are not included for EEW=64 in Zve64*.
5790 switch (BuiltinID) {
5791 default:
5792 break;
5793 case RISCVVector::BI__builtin_rvv_vmulhsu_vv:
5794 case RISCVVector::BI__builtin_rvv_vmulhsu_vx:
5795 case RISCVVector::BI__builtin_rvv_vmulhsu_vv_tu:
5796 case RISCVVector::BI__builtin_rvv_vmulhsu_vx_tu:
5797 case RISCVVector::BI__builtin_rvv_vmulhsu_vv_m:
5798 case RISCVVector::BI__builtin_rvv_vmulhsu_vx_m:
5799 case RISCVVector::BI__builtin_rvv_vmulhsu_vv_mu:
5800 case RISCVVector::BI__builtin_rvv_vmulhsu_vx_mu:
5801 case RISCVVector::BI__builtin_rvv_vmulhsu_vv_tum:
5802 case RISCVVector::BI__builtin_rvv_vmulhsu_vx_tum:
5803 case RISCVVector::BI__builtin_rvv_vmulhsu_vv_tumu:
5804 case RISCVVector::BI__builtin_rvv_vmulhsu_vx_tumu:
5805 case RISCVVector::BI__builtin_rvv_vmulhu_vv:
5806 case RISCVVector::BI__builtin_rvv_vmulhu_vx:
5807 case RISCVVector::BI__builtin_rvv_vmulhu_vv_tu:
5808 case RISCVVector::BI__builtin_rvv_vmulhu_vx_tu:
5809 case RISCVVector::BI__builtin_rvv_vmulhu_vv_m:
5810 case RISCVVector::BI__builtin_rvv_vmulhu_vx_m:
5811 case RISCVVector::BI__builtin_rvv_vmulhu_vv_mu:
5812 case RISCVVector::BI__builtin_rvv_vmulhu_vx_mu:
5813 case RISCVVector::BI__builtin_rvv_vmulhu_vv_tum:
5814 case RISCVVector::BI__builtin_rvv_vmulhu_vx_tum:
5815 case RISCVVector::BI__builtin_rvv_vmulhu_vv_tumu:
5816 case RISCVVector::BI__builtin_rvv_vmulhu_vx_tumu:
5817 case RISCVVector::BI__builtin_rvv_vmulh_vv:
5818 case RISCVVector::BI__builtin_rvv_vmulh_vx:
5819 case RISCVVector::BI__builtin_rvv_vmulh_vv_tu:
5820 case RISCVVector::BI__builtin_rvv_vmulh_vx_tu:
5821 case RISCVVector::BI__builtin_rvv_vmulh_vv_m:
5822 case RISCVVector::BI__builtin_rvv_vmulh_vx_m:
5823 case RISCVVector::BI__builtin_rvv_vmulh_vv_mu:
5824 case RISCVVector::BI__builtin_rvv_vmulh_vx_mu:
5825 case RISCVVector::BI__builtin_rvv_vmulh_vv_tum:
5826 case RISCVVector::BI__builtin_rvv_vmulh_vx_tum:
5827 case RISCVVector::BI__builtin_rvv_vmulh_vv_tumu:
5828 case RISCVVector::BI__builtin_rvv_vmulh_vx_tumu:
5829 case RISCVVector::BI__builtin_rvv_vsmul_vv:
5830 case RISCVVector::BI__builtin_rvv_vsmul_vx:
5831 case RISCVVector::BI__builtin_rvv_vsmul_vv_tu:
5832 case RISCVVector::BI__builtin_rvv_vsmul_vx_tu:
5833 case RISCVVector::BI__builtin_rvv_vsmul_vv_m:
5834 case RISCVVector::BI__builtin_rvv_vsmul_vx_m:
5835 case RISCVVector::BI__builtin_rvv_vsmul_vv_mu:
5836 case RISCVVector::BI__builtin_rvv_vsmul_vx_mu:
5837 case RISCVVector::BI__builtin_rvv_vsmul_vv_tum:
5838 case RISCVVector::BI__builtin_rvv_vsmul_vx_tum:
5839 case RISCVVector::BI__builtin_rvv_vsmul_vv_tumu:
5840 case RISCVVector::BI__builtin_rvv_vsmul_vx_tumu: {
5842 TheCall->getType()->castAs<BuiltinType>());
5843
5844 if (Context.getTypeSize(Info.ElementType) == 64 && !TI.hasFeature("v"))
5845 return Diag(TheCall->getBeginLoc(),
5846 diag::err_riscv_builtin_requires_extension)
5847 << /* IsExtension */ true << TheCall->getSourceRange() << "v";
5848
5849 break;
5850 }
5851 }
5852
5853 switch (BuiltinID) {
5854 case RISCVVector::BI__builtin_rvv_vsetvli:
5855 return BuiltinConstantArgRange(TheCall, 1, 0, 3) ||
5856 CheckRISCVLMUL(TheCall, 2);
5857 case RISCVVector::BI__builtin_rvv_vsetvlimax:
5858 return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
5859 CheckRISCVLMUL(TheCall, 1);
5860 case RISCVVector::BI__builtin_rvv_vget_v: {
5862 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
5863 TheCall->getType().getCanonicalType().getTypePtr()));
5865 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
5866 TheCall->getArg(0)->getType().getCanonicalType().getTypePtr()));
5867 unsigned MaxIndex;
5868 if (VecInfo.NumVectors != 1) // vget for tuple type
5869 MaxIndex = VecInfo.NumVectors;
5870 else // vget for non-tuple type
5871 MaxIndex = (VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors) /
5872 (ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors);
5873 return BuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1);
5874 }
5875 case RISCVVector::BI__builtin_rvv_vset_v: {
5877 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
5878 TheCall->getType().getCanonicalType().getTypePtr()));
5880 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
5881 TheCall->getArg(2)->getType().getCanonicalType().getTypePtr()));
5882 unsigned MaxIndex;
5883 if (ResVecInfo.NumVectors != 1) // vset for tuple type
5884 MaxIndex = ResVecInfo.NumVectors;
5885 else // vset fo non-tuple type
5886 MaxIndex = (ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors) /
5887 (VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors);
5888 return BuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1);
5889 }
5890 // Vector Crypto
5891 case RISCVVector::BI__builtin_rvv_vaeskf1_vi_tu:
5892 case RISCVVector::BI__builtin_rvv_vaeskf2_vi_tu:
5893 case RISCVVector::BI__builtin_rvv_vaeskf2_vi:
5894 case RISCVVector::BI__builtin_rvv_vsm4k_vi_tu: {
5895 QualType Op1Type = TheCall->getArg(0)->getType();
5896 QualType Op2Type = TheCall->getArg(1)->getType();
5897 return CheckInvalidVLENandLMUL(TI, TheCall, *this, Op1Type, 128) ||
5898 CheckInvalidVLENandLMUL(TI, TheCall, *this, Op2Type, 128) ||
5899 BuiltinConstantArgRange(TheCall, 2, 0, 31);
5900 }
5901 case RISCVVector::BI__builtin_rvv_vsm3c_vi_tu:
5902 case RISCVVector::BI__builtin_rvv_vsm3c_vi: {
5903 QualType Op1Type = TheCall->getArg(0)->getType();
5904 return CheckInvalidVLENandLMUL(TI, TheCall, *this, Op1Type, 256) ||
5905 BuiltinConstantArgRange(TheCall, 2, 0, 31);
5906 }
5907 case RISCVVector::BI__builtin_rvv_vaeskf1_vi:
5908 case RISCVVector::BI__builtin_rvv_vsm4k_vi: {
5909 QualType Op1Type = TheCall->getArg(0)->getType();
5910 return CheckInvalidVLENandLMUL(TI, TheCall, *this, Op1Type, 128) ||
5911 BuiltinConstantArgRange(TheCall, 1, 0, 31);
5912 }
5913 case RISCVVector::BI__builtin_rvv_vaesdf_vv:
5914 case RISCVVector::BI__builtin_rvv_vaesdf_vs:
5915 case RISCVVector::BI__builtin_rvv_vaesdm_vv:
5916 case RISCVVector::BI__builtin_rvv_vaesdm_vs:
5917 case RISCVVector::BI__builtin_rvv_vaesef_vv:
5918 case RISCVVector::BI__builtin_rvv_vaesef_vs:
5919 case RISCVVector::BI__builtin_rvv_vaesem_vv:
5920 case RISCVVector::BI__builtin_rvv_vaesem_vs:
5921 case RISCVVector::BI__builtin_rvv_vaesz_vs:
5922 case RISCVVector::BI__builtin_rvv_vsm4r_vv:
5923 case RISCVVector::BI__builtin_rvv_vsm4r_vs:
5924 case RISCVVector::BI__builtin_rvv_vaesdf_vv_tu:
5925 case RISCVVector::BI__builtin_rvv_vaesdf_vs_tu:
5926 case RISCVVector::BI__builtin_rvv_vaesdm_vv_tu:
5927 case RISCVVector::BI__builtin_rvv_vaesdm_vs_tu:
5928 case RISCVVector::BI__builtin_rvv_vaesef_vv_tu:
5929 case RISCVVector::BI__builtin_rvv_vaesef_vs_tu:
5930 case RISCVVector::BI__builtin_rvv_vaesem_vv_tu:
5931 case RISCVVector::BI__builtin_rvv_vaesem_vs_tu:
5932 case RISCVVector::BI__builtin_rvv_vaesz_vs_tu:
5933 case RISCVVector::BI__builtin_rvv_vsm4r_vv_tu:
5934 case RISCVVector::BI__builtin_rvv_vsm4r_vs_tu: {
5935 QualType Op1Type = TheCall->getArg(0)->getType();
5936 QualType Op2Type = TheCall->getArg(1)->getType();
5937 return CheckInvalidVLENandLMUL(TI, TheCall, *this, Op1Type, 128) ||
5938 CheckInvalidVLENandLMUL(TI, TheCall, *this, Op2Type, 128);
5939 }
5940 case RISCVVector::BI__builtin_rvv_vsha2ch_vv:
5941 case RISCVVector::BI__builtin_rvv_vsha2cl_vv:
5942 case RISCVVector::BI__builtin_rvv_vsha2ms_vv:
5943 case RISCVVector::BI__builtin_rvv_vsha2ch_vv_tu:
5944 case RISCVVector::BI__builtin_rvv_vsha2cl_vv_tu:
5945 case RISCVVector::BI__builtin_rvv_vsha2ms_vv_tu: {
5946 QualType Op1Type = TheCall->getArg(0)->getType();
5947 QualType Op2Type = TheCall->getArg(1)->getType();
5948 QualType Op3Type = TheCall->getArg(2)->getType();
5951 uint64_t ElemSize = Context.getTypeSize(Info.ElementType);
5952 if (ElemSize == 64 && !TI.hasFeature("zvknhb"))
5953 return Diag(TheCall->getBeginLoc(),
5954 diag::err_riscv_builtin_requires_extension)
5955 << /* IsExtension */ true << TheCall->getSourceRange() << "zvknb";
5956
5957 return CheckInvalidVLENandLMUL(TI, TheCall, *this, Op1Type, ElemSize * 4) ||
5958 CheckInvalidVLENandLMUL(TI, TheCall, *this, Op2Type, ElemSize * 4) ||
5959 CheckInvalidVLENandLMUL(TI, TheCall, *this, Op3Type, ElemSize * 4);
5960 }
5961
5962 case RISCVVector::BI__builtin_rvv_sf_vc_i_se:
5963 // bit_27_26, bit_24_20, bit_11_7, simm5, sew, log2lmul
5964 return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
5965 BuiltinConstantArgRange(TheCall, 1, 0, 31) ||
5966 BuiltinConstantArgRange(TheCall, 2, 0, 31) ||
5967 BuiltinConstantArgRange(TheCall, 3, -16, 15) ||
5968 CheckRISCVLMUL(TheCall, 5);
5969 case RISCVVector::BI__builtin_rvv_sf_vc_iv_se:
5970 // bit_27_26, bit_11_7, vs2, simm5
5971 return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
5972 BuiltinConstantArgRange(TheCall, 1, 0, 31) ||
5973 BuiltinConstantArgRange(TheCall, 3, -16, 15);
5974 case RISCVVector::BI__builtin_rvv_sf_vc_v_i:
5975 case RISCVVector::BI__builtin_rvv_sf_vc_v_i_se:
5976 // bit_27_26, bit_24_20, simm5
5977 return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
5978 BuiltinConstantArgRange(TheCall, 1, 0, 31) ||
5979 BuiltinConstantArgRange(TheCall, 2, -16, 15);
5980 case RISCVVector::BI__builtin_rvv_sf_vc_v_iv:
5981 case RISCVVector::BI__builtin_rvv_sf_vc_v_iv_se:
5982 // bit_27_26, vs2, simm5
5983 return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
5984 BuiltinConstantArgRange(TheCall, 2, -16, 15);
5985 case RISCVVector::BI__builtin_rvv_sf_vc_ivv_se:
5986 case RISCVVector::BI__builtin_rvv_sf_vc_ivw_se:
5987 case RISCVVector::BI__builtin_rvv_sf_vc_v_ivv:
5988 case RISCVVector::BI__builtin_rvv_sf_vc_v_ivw:
5989 case RISCVVector::BI__builtin_rvv_sf_vc_v_ivv_se:
5990 case RISCVVector::BI__builtin_rvv_sf_vc_v_ivw_se:
5991 // bit_27_26, vd, vs2, simm5
5992 return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
5993 BuiltinConstantArgRange(TheCall, 3, -16, 15);
5994 case RISCVVector::BI__builtin_rvv_sf_vc_x_se:
5995 // bit_27_26, bit_24_20, bit_11_7, xs1, sew, log2lmul
5996 return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
5997 BuiltinConstantArgRange(TheCall, 1, 0, 31) ||
5998 BuiltinConstantArgRange(TheCall, 2, 0, 31) ||
5999 CheckRISCVLMUL(TheCall, 5);
6000 case RISCVVector::BI__builtin_rvv_sf_vc_xv_se:
6001 case RISCVVector::BI__builtin_rvv_sf_vc_vv_se:
6002 // bit_27_26, bit_11_7, vs2, xs1/vs1
6003 case RISCVVector::BI__builtin_rvv_sf_vc_v_x:
6004 case RISCVVector::BI__builtin_rvv_sf_vc_v_x_se:
6005 // bit_27_26, bit_24-20, xs1
6006 return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
6007 BuiltinConstantArgRange(TheCall, 1, 0, 31);
6008 case RISCVVector::BI__builtin_rvv_sf_vc_vvv_se:
6009 case RISCVVector::BI__builtin_rvv_sf_vc_xvv_se:
6010 case RISCVVector::BI__builtin_rvv_sf_vc_vvw_se:
6011 case RISCVVector::BI__builtin_rvv_sf_vc_xvw_se:
6012 // bit_27_26, vd, vs2, xs1
6013 case RISCVVector::BI__builtin_rvv_sf_vc_v_xv:
6014 case RISCVVector::BI__builtin_rvv_sf_vc_v_vv:
6015 case RISCVVector::BI__builtin_rvv_sf_vc_v_xv_se:
6016 case RISCVVector::BI__builtin_rvv_sf_vc_v_vv_se:
6017 // bit_27_26, vs2, xs1/vs1
6018 case RISCVVector::BI__builtin_rvv_sf_vc_v_xvv:
6019 case RISCVVector::BI__builtin_rvv_sf_vc_v_vvv:
6020 case RISCVVector::BI__builtin_rvv_sf_vc_v_xvw:
6021 case RISCVVector::BI__builtin_rvv_sf_vc_v_vvw:
6022 case RISCVVector::BI__builtin_rvv_sf_vc_v_xvv_se:
6023 case RISCVVector::BI__builtin_rvv_sf_vc_v_vvv_se:
6024 case RISCVVector::BI__builtin_rvv_sf_vc_v_xvw_se:
6025 case RISCVVector::BI__builtin_rvv_sf_vc_v_vvw_se:
6026 // bit_27_26, vd, vs2, xs1/vs1
6027 return BuiltinConstantArgRange(TheCall, 0, 0, 3);
6028 case RISCVVector::BI__builtin_rvv_sf_vc_fv_se:
6029 // bit_26, bit_11_7, vs2, fs1
6030 return BuiltinConstantArgRange(TheCall, 0, 0, 1) ||
6031 BuiltinConstantArgRange(TheCall, 1, 0, 31);
6032 case RISCVVector::BI__builtin_rvv_sf_vc_fvv_se:
6033 case RISCVVector::BI__builtin_rvv_sf_vc_fvw_se:
6034 case RISCVVector::BI__builtin_rvv_sf_vc_v_fvv:
6035 case RISCVVector::BI__builtin_rvv_sf_vc_v_fvw:
6036 case RISCVVector::BI__builtin_rvv_sf_vc_v_fvv_se:
6037 case RISCVVector::BI__builtin_rvv_sf_vc_v_fvw_se:
6038 // bit_26, vd, vs2, fs1
6039 case RISCVVector::BI__builtin_rvv_sf_vc_v_fv:
6040 case RISCVVector::BI__builtin_rvv_sf_vc_v_fv_se:
6041 // bit_26, vs2, fs1
6042 return BuiltinConstantArgRange(TheCall, 0, 0, 1);
6043 // Check if byteselect is in [0, 3]
6044 case RISCV::BI__builtin_riscv_aes32dsi:
6045 case RISCV::BI__builtin_riscv_aes32dsmi:
6046 case RISCV::BI__builtin_riscv_aes32esi:
6047 case RISCV::BI__builtin_riscv_aes32esmi:
6048 case RISCV::BI__builtin_riscv_sm4ks:
6049 case RISCV::BI__builtin_riscv_sm4ed:
6050 return BuiltinConstantArgRange(TheCall, 2, 0, 3);
6051 // Check if rnum is in [0, 10]
6052 case RISCV::BI__builtin_riscv_aes64ks1i:
6053 return BuiltinConstantArgRange(TheCall, 1, 0, 10);
6054 // Check if value range for vxrm is in [0, 3]
6055 case RISCVVector::BI__builtin_rvv_vaaddu_vv:
6056 case RISCVVector::BI__builtin_rvv_vaaddu_vx:
6057 case RISCVVector::BI__builtin_rvv_vaadd_vv:
6058 case RISCVVector::BI__builtin_rvv_vaadd_vx:
6059 case RISCVVector::BI__builtin_rvv_vasubu_vv:
6060 case RISCVVector::BI__builtin_rvv_vasubu_vx:
6061 case RISCVVector::BI__builtin_rvv_vasub_vv:
6062 case RISCVVector::BI__builtin_rvv_vasub_vx:
6063 case RISCVVector::BI__builtin_rvv_vsmul_vv:
6064 case RISCVVector::BI__builtin_rvv_vsmul_vx:
6065 case RISCVVector::BI__builtin_rvv_vssra_vv:
6066 case RISCVVector::BI__builtin_rvv_vssra_vx:
6067 case RISCVVector::BI__builtin_rvv_vssrl_vv:
6068 case RISCVVector::BI__builtin_rvv_vssrl_vx:
6069 case RISCVVector::BI__builtin_rvv_vnclip_wv:
6070 case RISCVVector::BI__builtin_rvv_vnclip_wx:
6071 case RISCVVector::BI__builtin_rvv_vnclipu_wv:
6072 case RISCVVector::BI__builtin_rvv_vnclipu_wx:
6073 return BuiltinConstantArgRange(TheCall, 2, 0, 3);
6074 case RISCVVector::BI__builtin_rvv_vaaddu_vv_tu:
6075 case RISCVVector::BI__builtin_rvv_vaaddu_vx_tu:
6076 case RISCVVector::BI__builtin_rvv_vaadd_vv_tu:
6077 case RISCVVector::BI__builtin_rvv_vaadd_vx_tu:
6078 case RISCVVector::BI__builtin_rvv_vasubu_vv_tu:
6079 case RISCVVector::BI__builtin_rvv_vasubu_vx_tu:
6080 case RISCVVector::BI__builtin_rvv_vasub_vv_tu:
6081 case RISCVVector::BI__builtin_rvv_vasub_vx_tu:
6082 case RISCVVector::BI__builtin_rvv_vsmul_vv_tu:
6083 case RISCVVector::BI__builtin_rvv_vsmul_vx_tu:
6084 case RISCVVector::BI__builtin_rvv_vssra_vv_tu:
6085 case RISCVVector::BI__builtin_rvv_vssra_vx_tu:
6086 case RISCVVector::BI__builtin_rvv_vssrl_vv_tu:
6087 case RISCVVector::BI__builtin_rvv_vssrl_vx_tu:
6088 case RISCVVector::BI__builtin_rvv_vnclip_wv_tu:
6089 case RISCVVector::BI__builtin_rvv_vnclip_wx_tu:
6090 case RISCVVector::BI__builtin_rvv_vnclipu_wv_tu:
6091 case RISCVVector::BI__builtin_rvv_vnclipu_wx_tu:
6092 case RISCVVector::BI__builtin_rvv_vaaddu_vv_m:
6093 case RISCVVector::BI__builtin_rvv_vaaddu_vx_m:
6094 case RISCVVector::BI__builtin_rvv_vaadd_vv_m:
6095 case RISCVVector::BI__builtin_rvv_vaadd_vx_m:
6096 case RISCVVector::BI__builtin_rvv_vasubu_vv_m:
6097 case RISCVVector::BI__builtin_rvv_vasubu_vx_m:
6098 case RISCVVector::BI__builtin_rvv_vasub_vv_m:
6099 case RISCVVector::BI__builtin_rvv_vasub_vx_m:
6100 case RISCVVector::BI__builtin_rvv_vsmul_vv_m:
6101 case RISCVVector::BI__builtin_rvv_vsmul_vx_m:
6102 case RISCVVector::BI__builtin_rvv_vssra_vv_m:
6103 case RISCVVector::BI__builtin_rvv_vssra_vx_m:
6104 case RISCVVector::BI__builtin_rvv_vssrl_vv_m:
6105 case RISCVVector::BI__builtin_rvv_vssrl_vx_m:
6106 case RISCVVector::BI__builtin_rvv_vnclip_wv_m:
6107 case RISCVVector::BI__builtin_rvv_vnclip_wx_m:
6108 case RISCVVector::BI__builtin_rvv_vnclipu_wv_m:
6109 case RISCVVector::BI__builtin_rvv_vnclipu_wx_m:
6110 return BuiltinConstantArgRange(TheCall, 3, 0, 3);
6111 case RISCVVector::BI__builtin_rvv_vaaddu_vv_tum:
6112 case RISCVVector::BI__builtin_rvv_vaaddu_vv_tumu:
6113 case RISCVVector::BI__builtin_rvv_vaaddu_vv_mu:
6114 case RISCVVector::BI__builtin_rvv_vaaddu_vx_tum:
6115 case RISCVVector::BI__builtin_rvv_vaaddu_vx_tumu:
6116 case RISCVVector::BI__builtin_rvv_vaaddu_vx_mu:
6117 case RISCVVector::BI__builtin_rvv_vaadd_vv_tum:
6118 case RISCVVector::BI__builtin_rvv_vaadd_vv_tumu:
6119 case RISCVVector::BI__builtin_rvv_vaadd_vv_mu:
6120 case RISCVVector::BI__builtin_rvv_vaadd_vx_tum:
6121 case RISCVVector::BI__builtin_rvv_vaadd_vx_tumu:
6122 case RISCVVector::BI__builtin_rvv_vaadd_vx_mu:
6123 case RISCVVector::BI__builtin_rvv_vasubu_vv_tum:
6124 case RISCVVector::BI__builtin_rvv_vasubu_vv_tumu:
6125 case RISCVVector::BI__builtin_rvv_vasubu_vv_mu:
6126 case RISCVVector::BI__builtin_rvv_vasubu_vx_tum:
6127 case RISCVVector::BI__builtin_rvv_vasubu_vx_tumu:
6128 case RISCVVector::BI__builtin_rvv_vasubu_vx_mu:
6129 case RISCVVector::BI__builtin_rvv_vasub_vv_tum:
6130 case RISCVVector::BI__builtin_rvv_vasub_vv_tumu:
6131 case RISCVVector::BI__builtin_rvv_vasub_vv_mu:
6132 case RISCVVector::BI__builtin_rvv_vasub_vx_tum:
6133 case RISCVVector::BI__builtin_rvv_vasub_vx_tumu:
6134 case RISCVVector::BI__builtin_rvv_vasub_vx_mu:
6135 case RISCVVector::BI__builtin_rvv_vsmul_vv_mu:
6136 case RISCVVector::BI__builtin_rvv_vsmul_vx_mu:
6137 case RISCVVector::BI__builtin_rvv_vssra_vv_mu:
6138 case RISCVVector::BI__builtin_rvv_vssra_vx_mu:
6139 case RISCVVector::BI__builtin_rvv_vssrl_vv_mu:
6140 case RISCVVector::BI__builtin_rvv_vssrl_vx_mu:
6141 case RISCVVector::BI__builtin_rvv_vnclip_wv_mu:
6142 case RISCVVector::BI__builtin_rvv_vnclip_wx_mu:
6143 case RISCVVector::BI__builtin_rvv_vnclipu_wv_mu:
6144 case RISCVVector::BI__builtin_rvv_vnclipu_wx_mu:
6145 case RISCVVector::BI__builtin_rvv_vsmul_vv_tum:
6146 case RISCVVector::BI__builtin_rvv_vsmul_vx_tum:
6147 case RISCVVector::BI__builtin_rvv_vssra_vv_tum:
6148 case RISCVVector::BI__builtin_rvv_vssra_vx_tum:
6149 case RISCVVector::BI__builtin_rvv_vssrl_vv_tum:
6150 case RISCVVector::BI__builtin_rvv_vssrl_vx_tum:
6151 case RISCVVector::BI__builtin_rvv_vnclip_wv_tum:
6152 case RISCVVector::BI__builtin_rvv_vnclip_wx_tum:
6153 case RISCVVector::BI__builtin_rvv_vnclipu_wv_tum:
6154 case RISCVVector::BI__builtin_rvv_vnclipu_wx_tum:
6155 case RISCVVector::BI__builtin_rvv_vsmul_vv_tumu:
6156 case RISCVVector::BI__builtin_rvv_vsmul_vx_tumu:
6157 case RISCVVector::BI__builtin_rvv_vssra_vv_tumu:
6158 case RISCVVector::BI__builtin_rvv_vssra_vx_tumu:
6159 case RISCVVector::BI__builtin_rvv_vssrl_vv_tumu:
6160 case RISCVVector::BI__builtin_rvv_vssrl_vx_tumu:
6161 case RISCVVector::BI__builtin_rvv_vnclip_wv_tumu:
6162 case RISCVVector::BI__builtin_rvv_vnclip_wx_tumu:
6163 case RISCVVector::BI__builtin_rvv_vnclipu_wv_tumu:
6164 case RISCVVector::BI__builtin_rvv_vnclipu_wx_tumu:
6165 return BuiltinConstantArgRange(TheCall, 4, 0, 3);
6166 case RISCVVector::BI__builtin_rvv_vfsqrt_v_rm:
6167 case RISCVVector::BI__builtin_rvv_vfrec7_v_rm:
6168 case RISCVVector::BI__builtin_rvv_vfcvt_x_f_v_rm:
6169 case RISCVVector::BI__builtin_rvv_vfcvt_xu_f_v_rm:
6170 case RISCVVector::BI__builtin_rvv_vfcvt_f_x_v_rm:
6171 case RISCVVector::BI__builtin_rvv_vfcvt_f_xu_v_rm:
6172 case RISCVVector::BI__builtin_rvv_vfwcvt_x_f_v_rm:
6173 case RISCVVector::BI__builtin_rvv_vfwcvt_xu_f_v_rm:
6174 case RISCVVector::BI__builtin_rvv_vfncvt_x_f_w_rm:
6175 case RISCVVector::BI__builtin_rvv_vfncvt_xu_f_w_rm:
6176 case RISCVVector::BI__builtin_rvv_vfncvt_f_x_w_rm:
6177 case RISCVVector::BI__builtin_rvv_vfncvt_f_xu_w_rm:
6178 case RISCVVector::BI__builtin_rvv_vfncvt_f_f_w_rm:
6179 return BuiltinConstantArgRange(TheCall, 1, 0, 4);
6180 case RISCVVector::BI__builtin_rvv_vfadd_vv_rm:
6181 case RISCVVector::BI__builtin_rvv_vfadd_vf_rm:
6182 case RISCVVector::BI__builtin_rvv_vfsub_vv_rm:
6183 case RISCVVector::BI__builtin_rvv_vfsub_vf_rm:
6184 case RISCVVector::BI__builtin_rvv_vfrsub_vf_rm:
6185 case RISCVVector::BI__builtin_rvv_vfwadd_vv_rm:
6186 case RISCVVector::BI__builtin_rvv_vfwadd_vf_rm:
6187 case RISCVVector::BI__builtin_rvv_vfwsub_vv_rm:
6188 case RISCVVector::BI__builtin_rvv_vfwsub_vf_rm:
6189 case RISCVVector::BI__builtin_rvv_vfwadd_wv_rm:
6190 case RISCVVector::BI__builtin_rvv_vfwadd_wf_rm:
6191 case RISCVVector::BI__builtin_rvv_vfwsub_wv_rm:
6192 case RISCVVector::BI__builtin_rvv_vfwsub_wf_rm:
6193 case RISCVVector::BI__builtin_rvv_vfmul_vv_rm:
6194 case RISCVVector::BI__builtin_rvv_vfmul_vf_rm:
6195 case RISCVVector::BI__builtin_rvv_vfdiv_vv_rm:
6196 case RISCVVector::BI__builtin_rvv_vfdiv_vf_rm:
6197 case RISCVVector::BI__builtin_rvv_vfrdiv_vf_rm:
6198 case RISCVVector::BI__builtin_rvv_vfwmul_vv_rm:
6199 case RISCVVector::BI__builtin_rvv_vfwmul_vf_rm:
6200 case RISCVVector::BI__builtin_rvv_vfredosum_vs_rm:
6201 case RISCVVector::BI__builtin_rvv_vfredusum_vs_rm:
6202 case RISCVVector::BI__builtin_rvv_vfwredosum_vs_rm:
6203 case RISCVVector::BI__builtin_rvv_vfwredusum_vs_rm:
6204 case RISCVVector::BI__builtin_rvv_vfsqrt_v_rm_tu:
6205 case RISCVVector::BI__builtin_rvv_vfrec7_v_rm_tu:
6206 case RISCVVector::BI__builtin_rvv_vfcvt_x_f_v_rm_tu:
6207 case RISCVVector::BI__builtin_rvv_vfcvt_xu_f_v_rm_tu:
6208 case RISCVVector::BI__builtin_rvv_vfcvt_f_x_v_rm_tu:
6209 case RISCVVector::BI__builtin_rvv_vfcvt_f_xu_v_rm_tu:
6210 case RISCVVector::BI__builtin_rvv_vfwcvt_x_f_v_rm_tu:
6211 case RISCVVector::BI__builtin_rvv_vfwcvt_xu_f_v_rm_tu:
6212 case RISCVVector::BI__builtin_rvv_vfncvt_x_f_w_rm_tu:
6213 case RISCVVector::BI__builtin_rvv_vfncvt_xu_f_w_rm_tu:
6214 case RISCVVector::BI__builtin_rvv_vfncvt_f_x_w_rm_tu:
6215 case RISCVVector::BI__builtin_rvv_vfncvt_f_xu_w_rm_tu:
6216 case RISCVVector::BI__builtin_rvv_vfncvt_f_f_w_rm_tu:
6217 case RISCVVector::BI__builtin_rvv_vfsqrt_v_rm_m:
6218 case RISCVVector::BI__builtin_rvv_vfrec7_v_rm_m:
6219 case RISCVVector::BI__builtin_rvv_vfcvt_x_f_v_rm_m:
6220 case RISCVVector::BI__builtin_rvv_vfcvt_xu_f_v_rm_m:
6221 case RISCVVector::BI__builtin_rvv_vfcvt_f_x_v_rm_m:
6222 case RISCVVector::BI__builtin_rvv_vfcvt_f_xu_v_rm_m:
6223 case RISCVVector::BI__builtin_rvv_vfwcvt_x_f_v_rm_m:
6224 case RISCVVector::BI__builtin_rvv_vfwcvt_xu_f_v_rm_m:
6225 case RISCVVector::BI__builtin_rvv_vfncvt_x_f_w_rm_m:
6226 case RISCVVector::BI__builtin_rvv_vfncvt_xu_f_w_rm_m:
6227 case RISCVVector::BI__builtin_rvv_vfncvt_f_x_w_rm_m:
6228 case RISCVVector::BI__builtin_rvv_vfncvt_f_xu_w_rm_m:
6229 case RISCVVector::BI__builtin_rvv_vfncvt_f_f_w_rm_m:
6230 return BuiltinConstantArgRange(TheCall, 2, 0, 4);
6231 case RISCVVector::BI__builtin_rvv_vfadd_vv_rm_tu:
6232 case RISCVVector::BI__builtin_rvv_vfadd_vf_rm_tu:
6233 case RISCVVector::BI__builtin_rvv_vfsub_vv_rm_tu:
6234 case RISCVVector::BI__builtin_rvv_vfsub_vf_rm_tu:
6235 case RISCVVector::BI__builtin_rvv_vfrsub_vf_rm_tu:
6236 case RISCVVector::BI__builtin_rvv_vfwadd_vv_rm_tu:
6237 case RISCVVector::BI__builtin_rvv_vfwadd_vf_rm_tu:
6238 case RISCVVector::BI__builtin_rvv_vfwsub_vv_rm_tu:
6239 case RISCVVector::BI__builtin_rvv_vfwsub_vf_rm_tu:
6240 case RISCVVector::BI__builtin_rvv_vfwadd_wv_rm_tu:
6241 case RISCVVector::BI__builtin_rvv_vfwadd_wf_rm_tu:
6242 case RISCVVector::BI__builtin_rvv_vfwsub_wv_rm_tu:
6243 case RISCVVector::BI__builtin_rvv_vfwsub_wf_rm_tu:
6244 case RISCVVector::BI__builtin_rvv_vfmul_vv_rm_tu:
6245 case RISCVVector::BI__builtin_rvv_vfmul_vf_rm_tu:
6246 case RISCVVector::BI__builtin_rvv_vfdiv_vv_rm_tu:
6247 case RISCVVector::BI__builtin_rvv_vfdiv_vf_rm_tu:
6248 case RISCVVector::BI__builtin_rvv_vfrdiv_vf_rm_tu:
6249 case RISCVVector::BI__builtin_rvv_vfwmul_vv_rm_tu:
6250 case RISCVVector::BI__builtin_rvv_vfwmul_vf_rm_tu:
6251 case RISCVVector::BI__builtin_rvv_vfredosum_vs_rm_tu:
6252 case RISCVVector::BI__builtin_rvv_vfredusum_vs_rm_tu:
6253 case RISCVVector::BI__builtin_rvv_vfwredosum_vs_rm_tu:
6254 case RISCVVector::BI__builtin_rvv_vfwredusum_vs_rm_tu:
6255 case RISCVVector::BI__builtin_rvv_vfmacc_vv_rm:
6256 case RISCVVector::BI__builtin_rvv_vfmacc_vf_rm:
6257 case RISCVVector::BI__builtin_rvv_vfnmacc_vv_rm:
6258 case RISCVVector::BI__builtin_rvv_vfnmacc_vf_rm:
6259 case RISCVVector::BI__builtin_rvv_vfmsac_vv_rm:
6260 case RISCVVector::BI__builtin_rvv_vfmsac_vf_rm:
6261 case RISCVVector::BI__builtin_rvv_vfnmsac_vv_rm:
6262 case RISCVVector::BI__builtin_rvv_vfnmsac_vf_rm:
6263 case RISCVVector::BI__builtin_rvv_vfmadd_vv_rm:
6264 case RISCVVector::BI__builtin_rvv_vfmadd_vf_rm:
6265 case RISCVVector::BI__builtin_rvv_vfnmadd_vv_rm:
6266 case RISCVVector::BI__builtin_rvv_vfnmadd_vf_rm:
6267 case RISCVVector::BI__builtin_rvv_vfmsub_vv_rm:
6268 case RISCVVector::BI__builtin_rvv_vfmsub_vf_rm:
6269 case RISCVVector::BI__builtin_rvv_vfnmsub_vv_rm:
6270 case RISCVVector::BI__builtin_rvv_vfnmsub_vf_rm:
6271 case RISCVVector::BI__builtin_rvv_vfwmacc_vv_rm:
6272 case RISCVVector::BI__builtin_rvv_vfwmacc_vf_rm:
6273 case RISCVVector::BI__builtin_rvv_vfwnmacc_vv_rm:
6274 case RISCVVector::BI__builtin_rvv_vfwnmacc_vf_rm:
6275 case RISCVVector::BI__builtin_rvv_vfwmsac_vv_rm:
6276 case RISCVVector::BI__builtin_rvv_vfwmsac_vf_rm:
6277 case RISCVVector::BI__builtin_rvv_vfwnmsac_vv_rm:
6278 case RISCVVector::BI__builtin_rvv_vfwnmsac_vf_rm:
6279 case RISCVVector::BI__builtin_rvv_vfmacc_vv_rm_tu:
6280 case RISCVVector::BI__builtin_rvv_vfmacc_vf_rm_tu:
6281 case RISCVVector::BI__builtin_rvv_vfnmacc_vv_rm_tu:
6282 case RISCVVector::BI__builtin_rvv_vfnmacc_vf_rm_tu:
6283 case RISCVVector::BI__builtin_rvv_vfmsac_vv_rm_tu:
6284 case RISCVVector::BI__builtin_rvv_vfmsac_vf_rm_tu:
6285 case RISCVVector::BI__builtin_rvv_vfnmsac_vv_rm_tu:
6286 case RISCVVector::BI__builtin_rvv_vfnmsac_vf_rm_tu:
6287 case RISCVVector::BI__builtin_rvv_vfmadd_vv_rm_tu:
6288 case RISCVVector::BI__builtin_rvv_vfmadd_vf_rm_tu:
6289 case RISCVVector::BI__builtin_rvv_vfnmadd_vv_rm_tu:
6290 case RISCVVector::BI__builtin_rvv_vfnmadd_vf_rm_tu:
6291 case RISCVVector::BI__builtin_rvv_vfmsub_vv_rm_tu:
6292 case RISCVVector::BI__builtin_rvv_vfmsub_vf_rm_tu:
6293 case RISCVVector::BI__builtin_rvv_vfnmsub_vv_rm_tu:
6294 case RISCVVector::BI__builtin_rvv_vfnmsub_vf_rm_tu:
6295 case RISCVVector::BI__builtin_rvv_vfwmacc_vv_rm_tu:
6296 case RISCVVector::BI__builtin_rvv_vfwmacc_vf_rm_tu:
6297 case RISCVVector::BI__builtin_rvv_vfwnmacc_vv_rm_tu:
6298 case RISCVVector::BI__builtin_rvv_vfwnmacc_vf_rm_tu:
6299 case RISCVVector::BI__builtin_rvv_vfwmsac_vv_rm_tu:
6300 case RISCVVector::BI__builtin_rvv_vfwmsac_vf_rm_tu:
6301 case RISCVVector::BI__builtin_rvv_vfwnmsac_vv_rm_tu:
6302 case RISCVVector::BI__builtin_rvv_vfwnmsac_vf_rm_tu:
6303 case RISCVVector::BI__builtin_rvv_vfadd_vv_rm_m:
6304 case RISCVVector::BI__builtin_rvv_vfadd_vf_rm_m:
6305 case RISCVVector::BI__builtin_rvv_vfsub_vv_rm_m:
6306 case RISCVVector::BI__builtin_rvv_vfsub_vf_rm_m:
6307 case RISCVVector::BI__builtin_rvv_vfrsub_vf_rm_m:
6308 case RISCVVector::BI__builtin_rvv_vfwadd_vv_rm_m:
6309 case RISCVVector::BI__builtin_rvv_vfwadd_vf_rm_m:
6310 case RISCVVector::BI__builtin_rvv_vfwsub_vv_rm_m:
6311 case RISCVVector::BI__builtin_rvv_vfwsub_vf_rm_m:
6312 case RISCVVector::BI__builtin_rvv_vfwadd_wv_rm_m:
6313 case RISCVVector::BI__builtin_rvv_vfwadd_wf_rm_m:
6314 case RISCVVector::BI__builtin_rvv_vfwsub_wv_rm_m:
6315 case RISCVVector::BI__builtin_rvv_vfwsub_wf_rm_m:
6316 case RISCVVector::BI__builtin_rvv_vfmul_vv_rm_m:
6317 case RISCVVector::BI__builtin_rvv_vfmul_vf_rm_m:
6318 case RISCVVector::BI__builtin_rvv_vfdiv_vv_rm_m:
6319 case RISCVVector::BI__builtin_rvv_vfdiv_vf_rm_m:
6320 case RISCVVector::BI__builtin_rvv_vfrdiv_vf_rm_m:
6321 case RISCVVector::BI__builtin_rvv_vfwmul_vv_rm_m:
6322 case RISCVVector::BI__builtin_rvv_vfwmul_vf_rm_m:
6323 case RISCVVector::BI__builtin_rvv_vfredosum_vs_rm_m:
6324 case RISCVVector::BI__builtin_rvv_vfredusum_vs_rm_m:
6325 case RISCVVector::BI__builtin_rvv_vfwredosum_vs_rm_m:
6326 case RISCVVector::BI__builtin_rvv_vfwredusum_vs_rm_m:
6327 case RISCVVector::BI__builtin_rvv_vfsqrt_v_rm_tum:
6328 case RISCVVector::BI__builtin_rvv_vfrec7_v_rm_tum:
6329 case RISCVVector::BI__builtin_rvv_vfcvt_x_f_v_rm_tum:
6330 case RISCVVector::BI__builtin_rvv_vfcvt_xu_f_v_rm_tum:
6331 case RISCVVector::BI__builtin_rvv_vfcvt_f_x_v_rm_tum:
6332 case RISCVVector::BI__builtin_rvv_vfcvt_f_xu_v_rm_tum:
6333 case RISCVVector::BI__builtin_rvv_vfwcvt_x_f_v_rm_tum:
6334 case RISCVVector::BI__builtin_rvv_vfwcvt_xu_f_v_rm_tum:
6335 case RISCVVector::BI__builtin_rvv_vfncvt_x_f_w_rm_tum:
6336 case RISCVVector::BI__builtin_rvv_vfncvt_xu_f_w_rm_tum:
6337 case RISCVVector::BI__builtin_rvv_vfncvt_f_x_w_rm_tum:
6338 case RISCVVector::BI__builtin_rvv_vfncvt_f_xu_w_rm_tum:
6339 case RISCVVector::BI__builtin_rvv_vfncvt_f_f_w_rm_tum:
6340 case RISCVVector::BI__builtin_rvv_vfsqrt_v_rm_tumu:
6341 case RISCVVector::BI__builtin_rvv_vfrec7_v_rm_tumu:
6342 case RISCVVector::BI__builtin_rvv_vfcvt_x_f_v_rm_tumu:
6343 case RISCVVector::BI__builtin_rvv_vfcvt_xu_f_v_rm_tumu:
6344 case RISCVVector::BI__builtin_rvv_vfcvt_f_x_v_rm_tumu:
6345 case RISCVVector::BI__builtin_rvv_vfcvt_f_xu_v_rm_tumu:
6346 case RISCVVector::BI__builtin_rvv_vfwcvt_x_f_v_rm_tumu:
6347 case RISCVVector::BI__builtin_rvv_vfwcvt_xu_f_v_rm_tumu:
6348 case RISCVVector::BI__builtin_rvv_vfncvt_x_f_w_rm_tumu:
6349 case RISCVVector::BI__builtin_rvv_vfncvt_xu_f_w_rm_tumu:
6350 case RISCVVector::BI__builtin_rvv_vfncvt_f_x_w_rm_tumu:
6351 case RISCVVector::BI__builtin_rvv_vfncvt_f_xu_w_rm_tumu:
6352 case RISCVVector::BI__builtin_rvv_vfncvt_f_f_w_rm_tumu:
6353 case RISCVVector::BI__builtin_rvv_vfsqrt_v_rm_mu:
6354 case RISCVVector::BI__builtin_rvv_vfrec7_v_rm_mu:
6355 case RISCVVector::BI__builtin_rvv_vfcvt_x_f_v_rm_mu:
6356 case RISCVVector::BI__builtin_rvv_vfcvt_xu_f_v_rm_mu:
6357 case RISCVVector::BI__builtin_rvv_vfcvt_f_x_v_rm_mu:
6358 case RISCVVector::BI__builtin_rvv_vfcvt_f_xu_v_rm_mu:
6359 case RISCVVector::BI__builtin_rvv_vfwcvt_x_f_v_rm_mu:
6360 case RISCVVector::BI__builtin_rvv_vfwcvt_xu_f_v_rm_mu:
6361 case RISCVVector::BI__builtin_rvv_vfncvt_x_f_w_rm_mu:
6362 case RISCVVector::BI__builtin_rvv_vfncvt_xu_f_w_rm_mu:
6363 case RISCVVector::BI__builtin_rvv_vfncvt_f_x_w_rm_mu:
6364 case RISCVVector::BI__builtin_rvv_vfncvt_f_xu_w_rm_mu:
6365 case RISCVVector::BI__builtin_rvv_vfncvt_f_f_w_rm_mu:
6366 return BuiltinConstantArgRange(TheCall, 3, 0, 4);
6367 case RISCVVector::BI__builtin_rvv_vfmacc_vv_rm_m:
6368 case RISCVVector::BI__builtin_rvv_vfmacc_vf_rm_m:
6369 case RISCVVector::BI__builtin_rvv_vfnmacc_vv_rm_m:
6370 case RISCVVector::BI__builtin_rvv_vfnmacc_vf_rm_m:
6371 case RISCVVector::BI__builtin_rvv_vfmsac_vv_rm_m:
6372 case RISCVVector::BI__builtin_rvv_vfmsac_vf_rm_m:
6373 case RISCVVector::BI__builtin_rvv_vfnmsac_vv_rm_m:
6374 case RISCVVector::BI__builtin_rvv_vfnmsac_vf_rm_m:
6375 case RISCVVector::BI__builtin_rvv_vfmadd_vv_rm_m:
6376 case RISCVVector::BI__builtin_rvv_vfmadd_vf_rm_m:
6377 case RISCVVector::BI__builtin_rvv_vfnmadd_vv_rm_m:
6378 case RISCVVector::BI__builtin_rvv_vfnmadd_vf_rm_m:
6379 case RISCVVector::BI__builtin_rvv_vfmsub_vv_rm_m:
6380 case RISCVVector::BI__builtin_rvv_vfmsub_vf_rm_m:
6381 case RISCVVector::BI__builtin_rvv_vfnmsub_vv_rm_m:
6382 case RISCVVector::BI__builtin_rvv_vfnmsub_vf_rm_m:
6383 case RISCVVector::BI__builtin_rvv_vfwmacc_vv_rm_m:
6384 case RISCVVector::BI__builtin_rvv_vfwmacc_vf_rm_m:
6385 case RISCVVector::BI__builtin_rvv_vfwnmacc_vv_rm_m:
6386 case RISCVVector::BI__builtin_rvv_vfwnmacc_vf_rm_m:
6387 case RISCVVector::BI__builtin_rvv_vfwmsac_vv_rm_m:
6388 case RISCVVector::BI__builtin_rvv_vfwmsac_vf_rm_m:
6389 case RISCVVector::BI__builtin_rvv_vfwnmsac_vv_rm_m:
6390 case RISCVVector::BI__builtin_rvv_vfwnmsac_vf_rm_m:
6391 case RISCVVector::BI__builtin_rvv_vfadd_vv_rm_tum:
6392 case RISCVVector::BI__builtin_rvv_vfadd_vf_rm_tum:
6393 case RISCVVector::BI__builtin_rvv_vfsub_vv_rm_tum:
6394 case RISCVVector::BI__builtin_rvv_vfsub_vf_rm_tum:
6395 case RISCVVector::BI__builtin_rvv_vfrsub_vf_rm_tum:
6396 case RISCVVector::BI__builtin_rvv_vfwadd_vv_rm_tum:
6397 case RISCVVector::BI__builtin_rvv_vfwadd_vf_rm_tum:
6398 case RISCVVector::BI__builtin_rvv_vfwsub_vv_rm_tum:
6399 case RISCVVector::BI__builtin_rvv_vfwsub_vf_rm_tum:
6400 case RISCVVector::BI__builtin_rvv_vfwadd_wv_rm_tum:
6401 case RISCVVector::BI__builtin_rvv_vfwadd_wf_rm_tum:
6402 case RISCVVector::BI__builtin_rvv_vfwsub_wv_rm_tum:
6403 case RISCVVector::BI__builtin_rvv_vfwsub_wf_rm_tum:
6404 case RISCVVector::BI__builtin_rvv_vfmul_vv_rm_tum:
6405 case RISCVVector::BI__builtin_rvv_vfmul_vf_rm_tum:
6406 case RISCVVector::BI__builtin_rvv_vfdiv_vv_rm_tum:
6407 case RISCVVector::BI__builtin_rvv_vfdiv_vf_rm_tum:
6408 case RISCVVector::BI__builtin_rvv_vfrdiv_vf_rm_tum:
6409 case RISCVVector::BI__builtin_rvv_vfwmul_vv_rm_tum:
6410 case RISCVVector::BI__builtin_rvv_vfwmul_vf_rm_tum:
6411 case RISCVVector::BI__builtin_rvv_vfmacc_vv_rm_tum:
6412 case RISCVVector::BI__builtin_rvv_vfmacc_vf_rm_tum:
6413 case RISCVVector::BI__builtin_rvv_vfnmacc_vv_rm_tum:
6414 case RISCVVector::BI__builtin_rvv_vfnmacc_vf_rm_tum:
6415 case RISCVVector::BI__builtin_rvv_vfmsac_vv_rm_tum:
6416 case RISCVVector::BI__builtin_rvv_vfmsac_vf_rm_tum:
6417 case RISCVVector::BI__builtin_rvv_vfnmsac_vv_rm_tum:
6418 case RISCVVector::BI__builtin_rvv_vfnmsac_vf_rm_tum:
6419 case RISCVVector::BI__builtin_rvv_vfmadd_vv_rm_tum:
6420 case RISCVVector::BI__builtin_rvv_vfmadd_vf_rm_tum:
6421 case RISCVVector::BI__builtin_rvv_vfnmadd_vv_rm_tum:
6422 case RISCVVector::BI__builtin_rvv_vfnmadd_vf_rm_tum:
6423 case RISCVVector::BI__builtin_rvv_vfmsub_vv_rm_tum:
6424 case RISCVVector::BI__builtin_rvv_vfmsub_vf_rm_tum:
6425 case RISCVVector::BI__builtin_rvv_vfnmsub_vv_rm_tum:
6426 case RISCVVector::BI__builtin_rvv_vfnmsub_vf_rm_tum:
6427 case RISCVVector::BI__builtin_rvv_vfwmacc_vv_rm_tum:
6428 case RISCVVector::BI__builtin_rvv_vfwmacc_vf_rm_tum:
6429 case RISCVVector::BI__builtin_rvv_vfwnmacc_vv_rm_tum:
6430 case RISCVVector::BI__builtin_rvv_vfwnmacc_vf_rm_tum:
6431 case RISCVVector::BI__builtin_rvv_vfwmsac_vv_rm_tum:
6432 case RISCVVector::BI__builtin_rvv_vfwmsac_vf_rm_tum:
6433 case RISCVVector::BI__builtin_rvv_vfwnmsac_vv_rm_tum:
6434 case RISCVVector::BI__builtin_rvv_vfwnmsac_vf_rm_tum:
6435 case RISCVVector::BI__builtin_rvv_vfredosum_vs_rm_tum:
6436 case RISCVVector::BI__builtin_rvv_vfredusum_vs_rm_tum:
6437 case RISCVVector::BI__builtin_rvv_vfwredosum_vs_rm_tum:
6438 case RISCVVector::BI__builtin_rvv_vfwredusum_vs_rm_tum:
6439 case RISCVVector::BI__builtin_rvv_vfadd_vv_rm_tumu:
6440 case RISCVVector::BI__builtin_rvv_vfadd_vf_rm_tumu:
6441 case RISCVVector::BI__builtin_rvv_vfsub_vv_rm_tumu:
6442 case RISCVVector::BI__builtin_rvv_vfsub_vf_rm_tumu:
6443 case RISCVVector::BI__builtin_rvv_vfrsub_vf_rm_tumu:
6444 case RISCVVector::BI__builtin_rvv_vfwadd_vv_rm_tumu:
6445 case RISCVVector::BI__builtin_rvv_vfwadd_vf_rm_tumu:
6446 case RISCVVector::BI__builtin_rvv_vfwsub_vv_rm_tumu:
6447 case RISCVVector::BI__builtin_rvv_vfwsub_vf_rm_tumu:
6448 case RISCVVector::BI__builtin_rvv_vfwadd_wv_rm_tumu:
6449 case RISCVVector::BI__builtin_rvv_vfwadd_wf_rm_tumu:
6450 case RISCVVector::BI__builtin_rvv_vfwsub_wv_rm_tumu:
6451 case RISCVVector::BI__builtin_rvv_vfwsub_wf_rm_tumu:
6452 case RISCVVector::BI__builtin_rvv_vfmul_vv_rm_tumu:
6453 case RISCVVector::BI__builtin_rvv_vfmul_vf_rm_tumu:
6454 case RISCVVector::BI__builtin_rvv_vfdiv_vv_rm_tumu:
6455 case RISCVVector::BI__builtin_rvv_vfdiv_vf_rm_tumu:
6456 case RISCVVector::BI__builtin_rvv_vfrdiv_vf_rm_tumu:
6457 case RISCVVector::BI__builtin_rvv_vfwmul_vv_rm_tumu:
6458 case RISCVVector::BI__builtin_rvv_vfwmul_vf_rm_tumu:
6459 case RISCVVector::BI__builtin_rvv_vfmacc_vv_rm_tumu:
6460 case RISCVVector::BI__builtin_rvv_vfmacc_vf_rm_tumu:
6461 case RISCVVector::BI__builtin_rvv_vfnmacc_vv_rm_tumu:
6462 case RISCVVector::BI__builtin_rvv_vfnmacc_vf_rm_tumu:
6463 case RISCVVector::BI__builtin_rvv_vfmsac_vv_rm_tumu:
6464 case RISCVVector::BI__builtin_rvv_vfmsac_vf_rm_tumu:
6465 case RISCVVector::BI__builtin_rvv_vfnmsac_vv_rm_tumu:
6466 case RISCVVector::BI__builtin_rvv_vfnmsac_vf_rm_tumu:
6467 case RISCVVector::BI__builtin_rvv_vfmadd_vv_rm_tumu:
6468 case RISCVVector::BI__builtin_rvv_vfmadd_vf_rm_tumu:
6469 case RISCVVector::BI__builtin_rvv_vfnmadd_vv_rm_tumu:
6470 case RISCVVector::BI__builtin_rvv_vfnmadd_vf_rm_tumu:
6471 case RISCVVector::BI__builtin_rvv_vfmsub_vv_rm_tumu:
6472 case RISCVVector::BI__builtin_rvv_vfmsub_vf_rm_tumu:
6473 case RISCVVector::BI__builtin_rvv_vfnmsub_vv_rm_tumu:
6474 case RISCVVector::BI__builtin_rvv_vfnmsub_vf_rm_tumu:
6475 case RISCVVector::BI__builtin_rvv_vfwmacc_vv_rm_tumu:
6476 case RISCVVector::BI__builtin_rvv_vfwmacc_vf_rm_tumu:
6477 case RISCVVector::BI__builtin_rvv_vfwnmacc_vv_rm_tumu:
6478 case RISCVVector::BI__builtin_rvv_vfwnmacc_vf_rm_tumu:
6479 case RISCVVector::BI__builtin_rvv_vfwmsac_vv_rm_tumu:
6480 case RISCVVector::BI__builtin_rvv_vfwmsac_vf_rm_tumu:
6481 case RISCVVector::BI__builtin_rvv_vfwnmsac_vv_rm_tumu:
6482 case RISCVVector::BI__builtin_rvv_vfwnmsac_vf_rm_tumu:
6483 case RISCVVector::BI__builtin_rvv_vfadd_vv_rm_mu:
6484 case RISCVVector::BI__builtin_rvv_vfadd_vf_rm_mu:
6485 case RISCVVector::BI__builtin_rvv_vfsub_vv_rm_mu:
6486 case RISCVVector::BI__builtin_rvv_vfsub_vf_rm_mu:
6487 case RISCVVector::BI__builtin_rvv_vfrsub_vf_rm_mu:
6488 case RISCVVector::BI__builtin_rvv_vfwadd_vv_rm_mu:
6489 case RISCVVector::BI__builtin_rvv_vfwadd_vf_rm_mu:
6490 case RISCVVector::BI__builtin_rvv_vfwsub_vv_rm_mu:
6491 case RISCVVector::BI__builtin_rvv_vfwsub_vf_rm_mu:
6492 case RISCVVector::BI__builtin_rvv_vfwadd_wv_rm_mu:
6493 case RISCVVector::BI__builtin_rvv_vfwadd_wf_rm_mu:
6494 case RISCVVector::BI__builtin_rvv_vfwsub_wv_rm_mu:
6495 case RISCVVector::BI__builtin_rvv_vfwsub_wf_rm_mu:
6496 case RISCVVector::BI__builtin_rvv_vfmul_vv_rm_mu:
6497 case RISCVVector::BI__builtin_rvv_vfmul_vf_rm_mu:
6498 case RISCVVector::BI__builtin_rvv_vfdiv_vv_rm_mu:
6499 case RISCVVector::BI__builtin_rvv_vfdiv_vf_rm_mu:
6500 case RISCVVector::BI__builtin_rvv_vfrdiv_vf_rm_mu:
6501 case RISCVVector::BI__builtin_rvv_vfwmul_vv_rm_mu:
6502 case RISCVVector::BI__builtin_rvv_vfwmul_vf_rm_mu:
6503 case RISCVVector::BI__builtin_rvv_vfmacc_vv_rm_mu:
6504 case RISCVVector::BI__builtin_rvv_vfmacc_vf_rm_mu:
6505 case RISCVVector::BI__builtin_rvv_vfnmacc_vv_rm_mu:
6506 case RISCVVector::BI__builtin_rvv_vfnmacc_vf_rm_mu:
6507 case RISCVVector::BI__builtin_rvv_vfmsac_vv_rm_mu:
6508 case RISCVVector::BI__builtin_rvv_vfmsac_vf_rm_mu:
6509 case RISCVVector::BI__builtin_rvv_vfnmsac_vv_rm_mu:
6510 case RISCVVector::BI__builtin_rvv_vfnmsac_vf_rm_mu:
6511 case RISCVVector::BI__builtin_rvv_vfmadd_vv_rm_mu:
6512 case RISCVVector::BI__builtin_rvv_vfmadd_vf_rm_mu:
6513 case RISCVVector::BI__builtin_rvv_vfnmadd_vv_rm_mu:
6514 case RISCVVector::BI__builtin_rvv_vfnmadd_vf_rm_mu:
6515 case RISCVVector::BI__builtin_rvv_vfmsub_vv_rm_mu:
6516 case RISCVVector::BI__builtin_rvv_vfmsub_vf_rm_mu:
6517 case RISCVVector::BI__builtin_rvv_vfnmsub_vv_rm_mu:
6518 case RISCVVector::BI__builtin_rvv_vfnmsub_vf_rm_mu:
6519 case RISCVVector::BI__builtin_rvv_vfwmacc_vv_rm_mu:
6520 case RISCVVector::BI__builtin_rvv_vfwmacc_vf_rm_mu:
6521 case RISCVVector::BI__builtin_rvv_vfwnmacc_vv_rm_mu:
6522 case RISCVVector::BI__builtin_rvv_vfwnmacc_vf_rm_mu:
6523 case RISCVVector::BI__builtin_rvv_vfwmsac_vv_rm_mu:
6524 case RISCVVector::BI__builtin_rvv_vfwmsac_vf_rm_mu:
6525 case RISCVVector::BI__builtin_rvv_vfwnmsac_vv_rm_mu:
6526 case RISCVVector::BI__builtin_rvv_vfwnmsac_vf_rm_mu:
6527 return BuiltinConstantArgRange(TheCall, 4, 0, 4);
6528 case RISCV::BI__builtin_riscv_ntl_load:
6529 case RISCV::BI__builtin_riscv_ntl_store:
6530 DeclRefExpr *DRE =
6531 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6532 assert((BuiltinID == RISCV::BI__builtin_riscv_ntl_store ||
6533 BuiltinID == RISCV::BI__builtin_riscv_ntl_load) &&
6534 "Unexpected RISC-V nontemporal load/store builtin!");
6535 bool IsStore = BuiltinID == RISCV::BI__builtin_riscv_ntl_store;
6536 unsigned NumArgs = IsStore ? 3 : 2;
6537
6538 if (checkArgCountAtLeast(*this, TheCall, NumArgs - 1))
6539 return true;
6540
6541 if (checkArgCountAtMost(*this, TheCall, NumArgs))
6542 return true;
6543
6544 // Domain value should be compile-time constant.
6545 // 2 <= domain <= 5
6546 if (TheCall->getNumArgs() == NumArgs &&
6547 BuiltinConstantArgRange(TheCall, NumArgs - 1, 2, 5))
6548 return true;
6549
6550 Expr *PointerArg = TheCall->getArg(0);
6551 ExprResult PointerArgResult =
6553
6554 if (PointerArgResult.isInvalid())
6555 return true;
6556 PointerArg = PointerArgResult.get();
6557
6558 const PointerType *PtrType = PointerArg->getType()->getAs<PointerType>();
6559 if (!PtrType) {
6560 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6561 << PointerArg->getType() << PointerArg->getSourceRange();
6562 return true;
6563 }
6564
6565 QualType ValType = PtrType->getPointeeType();
6566 ValType = ValType.getUnqualifiedType();
6567 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6568 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6569 !ValType->isVectorType() && !ValType->isRVVSizelessBuiltinType()) {
6570 Diag(DRE->getBeginLoc(),
6571 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6572 << PointerArg->getType() << PointerArg->getSourceRange();
6573 return true;
6574 }
6575
6576 if (!IsStore) {
6577 TheCall->setType(ValType);
6578 return false;
6579 }
6580
6581 ExprResult ValArg = TheCall->getArg(1);
6583 Context, ValType, /*consume*/ false);
6584 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6585 if (ValArg.isInvalid())
6586 return true;
6587
6588 TheCall->setArg(1, ValArg.get());
6589 TheCall->setType(Context.VoidTy);
6590 return false;
6591 }
6592
6593 return false;
6594}
6595
6596bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
6597 CallExpr *TheCall) {
6598 if (BuiltinID == SystemZ::BI__builtin_tabort) {
6599 Expr *Arg = TheCall->getArg(0);
6600 if (std::optional<llvm::APSInt> AbortCode =
6602 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
6603 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
6604 << Arg->getSourceRange();
6605 }
6606
6607 // For intrinsics which take an immediate value as part of the instruction,
6608 // range check them here.
6609 unsigned i = 0, l = 0, u = 0;
6610 switch (BuiltinID) {
6611 default: return false;
6612 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
6613 case SystemZ::BI__builtin_s390_verimb:
6614 case SystemZ::BI__builtin_s390_verimh:
6615 case SystemZ::BI__builtin_s390_verimf:
6616 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
6617 case SystemZ::BI__builtin_s390_vfaeb:
6618 case SystemZ::BI__builtin_s390_vfaeh:
6619 case SystemZ::BI__builtin_s390_vfaef:
6620 case SystemZ::BI__builtin_s390_vfaebs:
6621 case SystemZ::BI__builtin_s390_vfaehs:
6622 case SystemZ::BI__builtin_s390_vfaefs:
6623 case SystemZ::BI__builtin_s390_vfaezb:
6624 case SystemZ::BI__builtin_s390_vfaezh:
6625 case SystemZ::BI__builtin_s390_vfaezf:
6626 case SystemZ::BI__builtin_s390_vfaezbs:
6627 case SystemZ::BI__builtin_s390_vfaezhs:
6628 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
6629 case SystemZ::BI__builtin_s390_vfisb:
6630 case SystemZ::BI__builtin_s390_vfidb:
6631 return BuiltinConstantArgRange(TheCall, 1, 0, 15) ||
6632 BuiltinConstantArgRange(TheCall, 2, 0, 15);
6633 case SystemZ::BI__builtin_s390_vftcisb:
6634 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
6635 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
6636 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
6637 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
6638 case SystemZ::BI__builtin_s390_vstrcb:
6639 case SystemZ::BI__builtin_s390_vstrch:
6640 case SystemZ::BI__builtin_s390_vstrcf:
6641 case SystemZ::BI__builtin_s390_vstrczb:
6642 case SystemZ::BI__builtin_s390_vstrczh:
6643 case SystemZ::BI__builtin_s390_vstrczf:
6644 case SystemZ::BI__builtin_s390_vstrcbs:
6645 case SystemZ::BI__builtin_s390_vstrchs:
6646 case SystemZ::BI__builtin_s390_vstrcfs:
6647 case SystemZ::BI__builtin_s390_vstrczbs:
6648 case SystemZ::BI__builtin_s390_vstrczhs:
6649 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
6650 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
6651 case SystemZ::BI__builtin_s390_vfminsb:
6652 case SystemZ::BI__builtin_s390_vfmaxsb:
6653 case SystemZ::BI__builtin_s390_vfmindb:
6654 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
6655 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
6656 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
6657 case SystemZ::BI__builtin_s390_vclfnhs:
6658 case SystemZ::BI__builtin_s390_vclfnls:
6659 case SystemZ::BI__builtin_s390_vcfn:
6660 case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
6661 case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
6662 }
6663 return BuiltinConstantArgRange(TheCall, i, l, u);
6664}
6665
6666bool Sema::CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI,
6667 unsigned BuiltinID,
6668 CallExpr *TheCall) {
6669 switch (BuiltinID) {
6670 case WebAssembly::BI__builtin_wasm_ref_null_extern:
6671 return BuiltinWasmRefNullExtern(TheCall);
6672 case WebAssembly::BI__builtin_wasm_ref_null_func:
6673 return BuiltinWasmRefNullFunc(TheCall);
6674 case WebAssembly::BI__builtin_wasm_table_get:
6675 return BuiltinWasmTableGet(TheCall);
6676 case WebAssembly::BI__builtin_wasm_table_set:
6677 return BuiltinWasmTableSet(TheCall);
6678 case WebAssembly::BI__builtin_wasm_table_size:
6679 return BuiltinWasmTableSize(TheCall);
6680 case WebAssembly::BI__builtin_wasm_table_grow:
6681 return BuiltinWasmTableGrow(TheCall);
6682 case WebAssembly::BI__builtin_wasm_table_fill:
6683 return BuiltinWasmTableFill(TheCall);
6684 case WebAssembly::BI__builtin_wasm_table_copy:
6685 return BuiltinWasmTableCopy(TheCall);
6686 }
6687
6688 return false;
6689}
6690
6691void Sema::checkRVVTypeSupport(QualType Ty, SourceLocation Loc, Decl *D,
6692 const llvm::StringMap<bool> &FeatureMap) {
6695 unsigned EltSize = Context.getTypeSize(Info.ElementType);
6696 unsigned MinElts = Info.EC.getKnownMinValue();
6697
6698 if (Info.ElementType->isSpecificBuiltinType(BuiltinType::Double) &&
6699 !FeatureMap.lookup("zve64d"))
6700 Diag(Loc, diag::err_riscv_type_requires_extension, D) << Ty << "zve64d";
6701 // (ELEN, LMUL) pairs of (8, mf8), (16, mf4), (32, mf2), (64, m1) requires at
6702 // least zve64x
6703 else if (((EltSize == 64 && Info.ElementType->isIntegerType()) ||
6704 MinElts == 1) &&
6705 !FeatureMap.lookup("zve64x"))
6706 Diag(Loc, diag::err_riscv_type_requires_extension, D) << Ty << "zve64x";
6707 else if (Info.ElementType->isFloat16Type() && !FeatureMap.lookup("zvfh") &&
6708 !FeatureMap.lookup("zvfhmin"))
6709 Diag(Loc, diag::err_riscv_type_requires_extension, D)
6710 << Ty << "zvfh or zvfhmin";
6711 else if (Info.ElementType->isBFloat16Type() &&
6712 !FeatureMap.lookup("experimental-zvfbfmin"))
6713 Diag(Loc, diag::err_riscv_type_requires_extension, D) << Ty << "zvfbfmin";
6714 else if (Info.ElementType->isSpecificBuiltinType(BuiltinType::Float) &&
6715 !FeatureMap.lookup("zve32f"))
6716 Diag(Loc, diag::err_riscv_type_requires_extension, D) << Ty << "zve32f";
6717 // Given that caller already checked isRVVType() before calling this function,
6718 // if we don't have at least zve32x supported, then we need to emit error.
6719 else if (!FeatureMap.lookup("zve32x"))
6720 Diag(Loc, diag::err_riscv_type_requires_extension, D) << Ty << "zve32x";
6721}
6722
6723bool Sema::CheckNVPTXBuiltinFunctionCall(const TargetInfo &TI,
6724 unsigned BuiltinID,
6725 CallExpr *TheCall) {
6726 switch (BuiltinID) {
6727 case NVPTX::BI__nvvm_cp_async_ca_shared_global_4:
6728 case NVPTX::BI__nvvm_cp_async_ca_shared_global_8:
6729 case NVPTX::BI__nvvm_cp_async_ca_shared_global_16:
6730 case NVPTX::BI__nvvm_cp_async_cg_shared_global_16:
6731 return checkArgCountAtMost(*this, TheCall, 3);
6732 }
6733
6734 return false;
6735}
6736
6737// Check if the rounding mode is legal.
6738bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
6739 // Indicates if this instruction has rounding control or just SAE.
6740 bool HasRC = false;
6741
6742 unsigned ArgNum = 0;
6743 switch (BuiltinID) {
6744 default:
6745 return false;
6746 case X86::BI__builtin_ia32_vcvttsd2si32:
6747 case X86::BI__builtin_ia32_vcvttsd2si64:
6748 case X86::BI__builtin_ia32_vcvttsd2usi32:
6749 case X86::BI__builtin_ia32_vcvttsd2usi64:
6750 case X86::BI__builtin_ia32_vcvttss2si32:
6751 case X86::BI__builtin_ia32_vcvttss2si64:
6752 case X86::BI__builtin_ia32_vcvttss2usi32:
6753 case X86::BI__builtin_ia32_vcvttss2usi64:
6754 case X86::BI__builtin_ia32_vcvttsh2si32:
6755 case X86::BI__builtin_ia32_vcvttsh2si64:
6756 case X86::BI__builtin_ia32_vcvttsh2usi32:
6757 case X86::BI__builtin_ia32_vcvttsh2usi64:
6758 ArgNum = 1;
6759 break;
6760 case X86::BI__builtin_ia32_maxpd512:
6761 case X86::BI__builtin_ia32_maxps512:
6762 case X86::BI__builtin_ia32_minpd512:
6763 case X86::BI__builtin_ia32_minps512:
6764 case X86::BI__builtin_ia32_maxph512:
6765 case X86::BI__builtin_ia32_minph512:
6766 ArgNum = 2;
6767 break;
6768 case X86::BI__builtin_ia32_vcvtph2pd512_mask:
6769 case X86::BI__builtin_ia32_vcvtph2psx512_mask:
6770 case X86::BI__builtin_ia32_cvtps2pd512_mask:
6771 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
6772 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
6773 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
6774 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
6775 case X86::BI__builtin_ia32_cvttps2dq512_mask:
6776 case X86::BI__builtin_ia32_cvttps2qq512_mask:
6777 case X86::BI__builtin_ia32_cvttps2udq512_mask:
6778 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
6779 case X86::BI__builtin_ia32_vcvttph2w512_mask:
6780 case X86::BI__builtin_ia32_vcvttph2uw512_mask:
6781 case X86::BI__builtin_ia32_vcvttph2dq512_mask:
6782 case X86::BI__builtin_ia32_vcvttph2udq512_mask:
6783 case X86::BI__builtin_ia32_vcvttph2qq512_mask:
6784 case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
6785 case X86::BI__builtin_ia32_exp2pd_mask:
6786 case X86::BI__builtin_ia32_exp2ps_mask:
6787 case X86::BI__builtin_ia32_getexppd512_mask:
6788 case X86::BI__builtin_ia32_getexpps512_mask:
6789 case X86::BI__builtin_ia32_getexpph512_mask:
6790 case X86::BI__builtin_ia32_rcp28pd_mask:
6791 case X86::BI__builtin_ia32_rcp28ps_mask:
6792 case X86::BI__builtin_ia32_rsqrt28pd_mask:
6793 case X86::BI__builtin_ia32_rsqrt28ps_mask:
6794 case X86::BI__builtin_ia32_vcomisd:
6795 case X86::BI__builtin_ia32_vcomiss:
6796 case X86::BI__builtin_ia32_vcomish:
6797 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
6798 ArgNum = 3;
6799 break;
6800 case X86::BI__builtin_ia32_cmppd512_mask:
6801 case X86::BI__builtin_ia32_cmpps512_mask:
6802 case X86::BI__builtin_ia32_cmpsd_mask:
6803 case X86::BI__builtin_ia32_cmpss_mask:
6804 case X86::BI__builtin_ia32_cmpsh_mask:
6805 case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
6806 case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
6807 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
6808 case X86::BI__builtin_ia32_getexpsd128_round_mask:
6809 case X86::BI__builtin_ia32_getexpss128_round_mask:
6810 case X86::BI__builtin_ia32_getexpsh128_round_mask:
6811 case X86::BI__builtin_ia32_getmantpd512_mask:
6812 case X86::BI__builtin_ia32_getmantps512_mask:
6813 case X86::BI__builtin_ia32_getmantph512_mask:
6814 case X86::BI__builtin_ia32_maxsd_round_mask:
6815 case X86::BI__builtin_ia32_maxss_round_mask:
6816 case X86::BI__builtin_ia32_maxsh_round_mask:
6817 case X86::BI__builtin_ia32_minsd_round_mask:
6818 case X86::BI__builtin_ia32_minss_round_mask:
6819 case X86::BI__builtin_ia32_minsh_round_mask:
6820 case X86::BI__builtin_ia32_rcp28sd_round_mask:
6821 case X86::BI__builtin_ia32_rcp28ss_round_mask:
6822 case X86::BI__builtin_ia32_reducepd512_mask:
6823 case X86::BI__builtin_ia32_reduceps512_mask:
6824 case X86::BI__builtin_ia32_reduceph512_mask:
6825 case X86::BI__builtin_ia32_rndscalepd_mask:
6826 case X86::BI__builtin_ia32_rndscaleps_mask:
6827 case X86::BI__builtin_ia32_rndscaleph_mask:
6828 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
6829 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
6830 ArgNum = 4;
6831 break;
6832 case X86::BI__builtin_ia32_fixupimmpd512_mask:
6833 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
6834 case X86::BI__builtin_ia32_fixupimmps512_mask:
6835 case X86::BI__builtin_ia32_fixupimmps512_maskz:
6836 case X86::BI__builtin_ia32_fixupimmsd_mask:
6837 case X86::BI__builtin_ia32_fixupimmsd_maskz:
6838 case X86::BI__builtin_ia32_fixupimmss_mask:
6839 case X86::BI__builtin_ia32_fixupimmss_maskz:
6840 case X86::BI__builtin_ia32_getmantsd_round_mask:
6841 case X86::BI__builtin_ia32_getmantss_round_mask:
6842 case X86::BI__builtin_ia32_getmantsh_round_mask:
6843 case X86::BI__builtin_ia32_rangepd512_mask:
6844 case X86::BI__builtin_ia32_rangeps512_mask:
6845 case X86::BI__builtin_ia32_rangesd128_round_mask:
6846 case X86::BI__builtin_ia32_rangess128_round_mask:
6847 case X86::BI__builtin_ia32_reducesd_mask:
6848 case X86::BI__builtin_ia32_reducess_mask:
6849 case X86::BI__builtin_ia32_reducesh_mask:
6850 case X86::BI__builtin_ia32_rndscalesd_round_mask:
6851 case X86::BI__builtin_ia32_rndscaless_round_mask:
6852 case X86::BI__builtin_ia32_rndscalesh_round_mask:
6853 ArgNum = 5;
6854 break;
6855 case X86::BI__builtin_ia32_vcvtsd2si64:
6856 case X86::BI__builtin_ia32_vcvtsd2si32:
6857 case X86::BI__builtin_ia32_vcvtsd2usi32:
6858 case X86::BI__builtin_ia32_vcvtsd2usi64:
6859 case X86::BI__builtin_ia32_vcvtss2si32:
6860 case X86::BI__builtin_ia32_vcvtss2si64:
6861 case X86::BI__builtin_ia32_vcvtss2usi32:
6862 case X86::BI__builtin_ia32_vcvtss2usi64:
6863 case X86::BI__builtin_ia32_vcvtsh2si32:
6864 case X86::BI__builtin_ia32_vcvtsh2si64:
6865 case X86::BI__builtin_ia32_vcvtsh2usi32:
6866 case X86::BI__builtin_ia32_vcvtsh2usi64:
6867 case X86::BI__builtin_ia32_sqrtpd512:
6868 case X86::BI__builtin_ia32_sqrtps512:
6869 case X86::BI__builtin_ia32_sqrtph512:
6870 ArgNum = 1;
6871 HasRC = true;
6872 break;
6873 case X86::BI__builtin_ia32_addph512:
6874 case X86::BI__builtin_ia32_divph512:
6875 case X86::BI__builtin_ia32_mulph512:
6876 case X86::BI__builtin_ia32_subph512:
6877 case X86::BI__builtin_ia32_addpd512:
6878 case X86::BI__builtin_ia32_addps512:
6879 case X86::BI__builtin_ia32_divpd512:
6880 case X86::BI__builtin_ia32_divps512:
6881 case X86::BI__builtin_ia32_mulpd512:
6882 case X86::BI__builtin_ia32_mulps512:
6883 case X86::BI__builtin_ia32_subpd512:
6884 case X86::BI__builtin_ia32_subps512:
6885 case X86::BI__builtin_ia32_cvtsi2sd64:
6886 case X86::BI__builtin_ia32_cvtsi2ss32:
6887 case X86::BI__builtin_ia32_cvtsi2ss64:
6888 case X86::BI__builtin_ia32_cvtusi2sd64:
6889 case X86::BI__builtin_ia32_cvtusi2ss32:
6890 case X86::BI__builtin_ia32_cvtusi2ss64:
6891 case X86::BI__builtin_ia32_vcvtusi2sh:
6892 case X86::BI__builtin_ia32_vcvtusi642sh:
6893 case X86::BI__builtin_ia32_vcvtsi2sh:
6894 case X86::BI__builtin_ia32_vcvtsi642sh:
6895 ArgNum = 2;
6896 HasRC = true;
6897 break;
6898 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
6899 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
6900 case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
6901 case X86::BI__builtin_ia32_vcvtps2phx512_mask:
6902 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
6903 case X86::BI__builtin_ia32_cvtpd2dq512_mask:
6904 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
6905 case X86::BI__builtin_ia32_cvtpd2udq512_mask:
6906 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
6907 case X86::BI__builtin_ia32_cvtps2dq512_mask:
6908 case X86::BI__builtin_ia32_cvtps2qq512_mask:
6909 case X86::BI__builtin_ia32_cvtps2udq512_mask:
6910 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
6911 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
6912 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
6913 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
6914 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
6915 case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
6916 case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
6917 case X86::BI__builtin_ia32_vcvtw2ph512_mask:
6918 case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
6919 case X86::BI__builtin_ia32_vcvtph2w512_mask:
6920 case X86::BI__builtin_ia32_vcvtph2uw512_mask:
6921 case X86::BI__builtin_ia32_vcvtph2dq512_mask:
6922 case X86::BI__builtin_ia32_vcvtph2udq512_mask:
6923 case X86::BI__builtin_ia32_vcvtph2qq512_mask:
6924 case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
6925 case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
6926 case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
6927 ArgNum = 3;
6928 HasRC = true;
6929 break;
6930 case X86::BI__builtin_ia32_addsh_round_mask:
6931 case X86::BI__builtin_ia32_addss_round_mask:
6932 case X86::BI__builtin_ia32_addsd_round_mask:
6933 case X86::BI__builtin_ia32_divsh_round_mask:
6934 case X86::BI__builtin_ia32_divss_round_mask:
6935 case X86::BI__builtin_ia32_divsd_round_mask:
6936 case X86::BI__builtin_ia32_mulsh_round_mask:
6937 case X86::BI__builtin_ia32_mulss_round_mask:
6938 case X86::BI__builtin_ia32_mulsd_round_mask:
6939 case X86::BI__builtin_ia32_subsh_round_mask:
6940 case X86::BI__builtin_ia32_subss_round_mask:
6941 case X86::BI__builtin_ia32_subsd_round_mask:
6942 case X86::BI__builtin_ia32_scalefph512_mask:
6943 case X86::BI__builtin_ia32_scalefpd512_mask:
6944 case X86::BI__builtin_ia32_scalefps512_mask:
6945 case X86::BI__builtin_ia32_scalefsd_round_mask:
6946 case X86::BI__builtin_ia32_scalefss_round_mask:
6947 case X86::BI__builtin_ia32_scalefsh_round_mask:
6948 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
6949 case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
6950 case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
6951 case X86::BI__builtin_ia32_sqrtsd_round_mask:
6952 case X86::BI__builtin_ia32_sqrtss_round_mask:
6953 case X86::BI__builtin_ia32_sqrtsh_round_mask:
6954 case X86::BI__builtin_ia32_vfmaddsd3_mask:
6955 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
6956 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
6957 case X86::BI__builtin_ia32_vfmaddss3_mask:
6958 case X86::BI__builtin_ia32_vfmaddss3_maskz:
6959 case X86::BI__builtin_ia32_vfmaddss3_mask3:
6960 case X86::BI__builtin_ia32_vfmaddsh3_mask:
6961 case X86::BI__builtin_ia32_vfmaddsh3_maskz:
6962 case X86::BI__builtin_ia32_vfmaddsh3_mask3:
6963 case X86::BI__builtin_ia32_vfmaddpd512_mask:
6964 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
6965 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
6966 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
6967 case X86::BI__builtin_ia32_vfmaddps512_mask:
6968 case X86::BI__builtin_ia32_vfmaddps512_maskz:
6969 case X86::BI__builtin_ia32_vfmaddps512_mask3:
6970 case X86::BI__builtin_ia32_vfmsubps512_mask3:
6971 case X86::BI__builtin_ia32_vfmaddph512_mask:
6972 case X86::BI__builtin_ia32_vfmaddph512_maskz:
6973 case X86::BI__builtin_ia32_vfmaddph512_mask3:
6974 case X86::BI__builtin_ia32_vfmsubph512_mask3:
6975 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
6976 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
6977 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
6978 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
6979 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
6980 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
6981 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
6982 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
6983 case X86::BI__builtin_ia32_vfmaddsubph512_mask:
6984 case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
6985 case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
6986 case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
6987 case X86::BI__builtin_ia32_vfmaddcsh_mask:
6988 case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
6989 case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
6990 case X86::BI__builtin_ia32_vfmaddcph512_mask:
6991 case X86::BI__builtin_ia32_vfmaddcph512_maskz:
6992 case X86::BI__builtin_ia32_vfmaddcph512_mask3:
6993 case X86::BI__builtin_ia32_vfcmaddcsh_mask:
6994 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
6995 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
6996 case X86::BI__builtin_ia32_vfcmaddcph512_mask:
6997 case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
6998 case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
6999 case X86::BI__builtin_ia32_vfmulcsh_mask:
7000 case X86::BI__builtin_ia32_vfmulcph512_mask:
7001 case X86::BI__builtin_ia32_vfcmulcsh_mask:
7002 case X86::BI__builtin_ia32_vfcmulcph512_mask:
7003 ArgNum = 4;
7004 HasRC = true;
7005 break;
7006 }
7007
7008 llvm::APSInt Result;
7009
7010 // We can't check the value of a dependent argument.
7011 Expr *Arg = TheCall->getArg(ArgNum);
7012 if (Arg->isTypeDependent() || Arg->isValueDependent())
7013 return false;
7014
7015 // Check constant-ness first.
7016 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7017 return true;
7018
7019 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
7020 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
7021 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
7022 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
7023 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
7024 Result == 8/*ROUND_NO_EXC*/ ||
7025 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
7026 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
7027 return false;
7028
7029 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
7030 << Arg->getSourceRange();
7031}
7032
7033// Check if the gather/scatter scale is legal.
7034bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
7035 CallExpr *TheCall) {
7036 unsigned ArgNum = 0;
7037 switch (BuiltinID) {
7038 default:
7039 return false;
7040 case X86::BI__builtin_ia32_gatherpfdpd:
7041 case X86::BI__builtin_ia32_gatherpfdps:
7042 case X86::BI__builtin_ia32_gatherpfqpd:
7043 case X86::BI__builtin_ia32_gatherpfqps:
7044 case X86::BI__builtin_ia32_scatterpfdpd:
7045 case X86::BI__builtin_ia32_scatterpfdps:
7046 case X86::BI__builtin_ia32_scatterpfqpd:
7047 case X86::BI__builtin_ia32_scatterpfqps:
7048 ArgNum = 3;
7049 break;
7050 case X86::BI__builtin_ia32_gatherd_pd:
7051 case X86::BI__builtin_ia32_gatherd_pd256:
7052 case X86::BI__builtin_ia32_gatherq_pd:
7053 case X86::BI__builtin_ia32_gatherq_pd256:
7054 case X86::BI__builtin_ia32_gatherd_ps:
7055 case X86::BI__builtin_ia32_gatherd_ps256:
7056 case X86::BI__builtin_ia32_gatherq_ps:
7057 case X86::BI__builtin_ia32_gatherq_ps256:
7058 case X86::BI__builtin_ia32_gatherd_q:
7059 case X86::BI__builtin_ia32_gatherd_q256:
7060 case X86::BI__builtin_ia32_gatherq_q:
7061 case X86::BI__builtin_ia32_gatherq_q256:
7062 case X86::BI__builtin_ia32_gatherd_d:
7063 case X86::BI__builtin_ia32_gatherd_d256:
7064 case X86::BI__builtin_ia32_gatherq_d:
7065 case X86::BI__builtin_ia32_gatherq_d256:
7066 case X86::BI__builtin_ia32_gather3div2df:
7067 case X86::BI__builtin_ia32_gather3div2di:
7068 case X86::BI__builtin_ia32_gather3div4df:
7069 case X86::BI__builtin_ia32_gather3div4di:
7070 case X86::BI__builtin_ia32_gather3div4sf:
7071 case X86::BI__builtin_ia32_gather3div4si:
7072 case X86::BI__builtin_ia32_gather3div8sf:
7073 case X86::BI__builtin_ia32_gather3div8si:
7074 case X86::BI__builtin_ia32_gather3siv2df:
7075 case X86::BI__builtin_ia32_gather3siv2di:
7076 case X86::BI__builtin_ia32_gather3siv4df:
7077 case X86::BI__builtin_ia32_gather3siv4di:
7078 case X86::BI__builtin_ia32_gather3siv4sf:
7079 case X86::BI__builtin_ia32_gather3siv4si:
7080 case X86::BI__builtin_ia32_gather3siv8sf:
7081 case X86::BI__builtin_ia32_gather3siv8si:
7082 case X86::BI__builtin_ia32_gathersiv8df:
7083 case X86::BI__builtin_ia32_gathersiv16sf:
7084 case X86::BI__builtin_ia32_gatherdiv8df:
7085 case X86::BI__builtin_ia32_gatherdiv16sf:
7086 case X86::BI__builtin_ia32_gathersiv8di:
7087 case X86::BI__builtin_ia32_gathersiv16si:
7088 case X86::BI__builtin_ia32_gatherdiv8di:
7089 case X86::BI__builtin_ia32_gatherdiv16si:
7090 case X86::BI__builtin_ia32_scatterdiv2df:
7091 case X86::BI__builtin_ia32_scatterdiv2di:
7092 case X86::BI__builtin_ia32_scatterdiv4df:
7093 case X86::BI__builtin_ia32_scatterdiv4di:
7094 case X86::BI__builtin_ia32_scatterdiv4sf:
7095 case X86::BI__builtin_ia32_scatterdiv4si:
7096 case X86::BI__builtin_ia32_scatterdiv8sf:
7097 case X86::BI__builtin_ia32_scatterdiv8si:
7098 case X86::BI__builtin_ia32_scattersiv2df:
7099 case X86::BI__builtin_ia32_scattersiv2di:
7100 case X86::BI__builtin_ia32_scattersiv4df:
7101 case X86::BI__builtin_ia32_scattersiv4di:
7102 case X86::BI__builtin_ia32_scattersiv4sf:
7103 case X86::BI__builtin_ia32_scattersiv4si:
7104 case X86::BI__builtin_ia32_scattersiv8sf:
7105 case X86::BI__builtin_ia32_scattersiv8si:
7106 case X86::BI__builtin_ia32_scattersiv8df:
7107 case X86::BI__builtin_ia32_scattersiv16sf:
7108 case X86::BI__builtin_ia32_scatterdiv8df:
7109 case X86::BI__builtin_ia32_scatterdiv16sf:
7110 case X86::BI__builtin_ia32_scattersiv8di:
7111 case X86::BI__builtin_ia32_scattersiv16si:
7112 case X86::BI__builtin_ia32_scatterdiv8di:
7113 case X86::BI__builtin_ia32_scatterdiv16si:
7114 ArgNum = 4;
7115 break;
7116 }
7117
7118 llvm::APSInt Result;
7119
7120 // We can't check the value of a dependent argument.
7121 Expr *Arg = TheCall->getArg(ArgNum);
7122 if (Arg->isTypeDependent() || Arg->isValueDependent())
7123 return false;
7124
7125 // Check constant-ness first.
7126 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7127 return true;
7128
7129 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
7130 return false;
7131
7132 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
7133 << Arg->getSourceRange();
7134}
7135
7136enum { TileRegLow = 0, TileRegHigh = 7 };
7137
7138bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
7139 ArrayRef<int> ArgNums) {
7140 for (int ArgNum : ArgNums) {
7141 if (BuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
7142 return true;
7143 }
7144 return false;
7145}
7146
7147bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
7148 ArrayRef<int> ArgNums) {
7149 // Because the max number of tile register is TileRegHigh + 1, so here we use
7150 // each bit to represent the usage of them in bitset.
7151 std::bitset<TileRegHigh + 1> ArgValues;
7152 for (int ArgNum : ArgNums) {
7153 Expr *Arg = TheCall->getArg(ArgNum);
7154 if (Arg->isTypeDependent() || Arg->isValueDependent())
7155 continue;
7156
7157 llvm::APSInt Result;
7158 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7159 return true;
7160 int ArgExtValue = Result.getExtValue();
7161 assert((ArgExtValue >= TileRegLow && ArgExtValue <= TileRegHigh) &&
7162 "Incorrect tile register num.");
7163 if (ArgValues.test(ArgExtValue))
7164 return Diag(TheCall->getBeginLoc(),
7165 diag::err_x86_builtin_tile_arg_duplicate)
7166 << TheCall->getArg(ArgNum)->getSourceRange();
7167 ArgValues.set(ArgExtValue);
7168 }
7169 return false;
7170}
7171
7172bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
7173 ArrayRef<int> ArgNums) {
7174 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
7175 CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
7176}
7177
7178bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
7179 switch (BuiltinID) {
7180 default:
7181 return false;
7182 case X86::BI__builtin_ia32_tileloadd64:
7183 case X86::BI__builtin_ia32_tileloaddt164:
7184 case X86::BI__builtin_ia32_tilestored64:
7185 case X86::BI__builtin_ia32_tilezero:
7186 return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
7187 case X86::BI__builtin_ia32_tdpbssd:
7188 case X86::BI__builtin_ia32_tdpbsud:
7189 case X86::BI__builtin_ia32_tdpbusd:
7190 case X86::BI__builtin_ia32_tdpbuud:
7191 case X86::BI__builtin_ia32_tdpbf16ps:
7192 case X86::BI__builtin_ia32_tdpfp16ps:
7193 case X86::BI__builtin_ia32_tcmmimfp16ps:
7194 case X86::BI__builtin_ia32_tcmmrlfp16ps:
7195 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
7196 }
7197}
7198static bool isX86_32Builtin(unsigned BuiltinID) {
7199 // These builtins only work on x86-32 targets.
7200 switch (BuiltinID) {
7201 case X86::BI__builtin_ia32_readeflags_u32:
7202 case X86::BI__builtin_ia32_writeeflags_u32:
7203 return true;
7204 }
7205
7206 return false;
7207}
7208
7209bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
7210 CallExpr *TheCall) {
7211 // Check for 32-bit only builtins on a 64-bit target.
7212 const llvm::Triple &TT = TI.getTriple();
7213 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
7214 return Diag(TheCall->getCallee()->getBeginLoc(),
7215 diag::err_32_bit_builtin_64_bit_tgt);
7216
7217 // If the intrinsic has rounding or SAE make sure its valid.
7218 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
7219 return true;
7220
7221 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
7222 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
7223 return true;
7224
7225 // If the intrinsic has a tile arguments, make sure they are valid.
7226 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
7227 return true;
7228
7229 // For intrinsics which take an immediate value as part of the instruction,
7230 // range check them here.
7231 int i = 0, l = 0, u = 0;
7232 switch (BuiltinID) {
7233 default:
7234 return false;
7235 case X86::BI__builtin_ia32_vec_ext_v2si:
7236 case X86::BI__builtin_ia32_vec_ext_v2di:
7237 case X86::BI__builtin_ia32_vextractf128_pd256:
7238 case X86::BI__builtin_ia32_vextractf128_ps256:
7239 case X86::BI__builtin_ia32_vextractf128_si256:
7240 case X86::BI__builtin_ia32_extract128i256:
7241 case X86::BI__builtin_ia32_extractf64x4_mask:
7242 case X86::BI__builtin_ia32_extracti64x4_mask:
7243 case X86::BI__builtin_ia32_extractf32x8_mask:
7244 case X86::BI__builtin_ia32_extracti32x8_mask:
7245 case X86::BI__builtin_ia32_extractf64x2_256_mask:
7246 case X86::BI__builtin_ia32_extracti64x2_256_mask:
7247 case X86::BI__builtin_ia32_extractf32x4_256_mask:
7248 case X86::BI__builtin_ia32_extracti32x4_256_mask:
7249 i = 1; l = 0; u = 1;
7250 break;
7251 case X86::BI__builtin_ia32_vec_set_v2di:
7252 case X86::BI__builtin_ia32_vinsertf128_pd256:
7253 case X86::BI__builtin_ia32_vinsertf128_ps256:
7254 case X86::BI__builtin_ia32_vinsertf128_si256:
7255 case X86::BI__builtin_ia32_insert128i256:
7256 case X86::BI__builtin_ia32_insertf32x8:
7257 case X86::BI__builtin_ia32_inserti32x8:
7258 case X86::BI__builtin_ia32_insertf64x4:
7259 case X86::BI__builtin_ia32_inserti64x4:
7260 case X86::BI__builtin_ia32_insertf64x2_256:
7261 case X86::BI__builtin_ia32_inserti64x2_256:
7262 case X86::BI__builtin_ia32_insertf32x4_256:
7263 case X86::BI__builtin_ia32_inserti32x4_256:
7264 i = 2; l = 0; u = 1;
7265 break;
7266 case X86::BI__builtin_ia32_vpermilpd:
7267 case X86::BI__builtin_ia32_vec_ext_v4hi:
7268 case X86::BI__builtin_ia32_vec_ext_v4si:
7269 case X86::BI__builtin_ia32_vec_ext_v4sf:
7270 case X86::BI__builtin_ia32_vec_ext_v4di:
7271 case X86::BI__builtin_ia32_extractf32x4_mask:
7272 case X86::BI__builtin_ia32_extracti32x4_mask:
7273 case X86::BI__builtin_ia32_extractf64x2_512_mask:
7274 case X86::BI__builtin_ia32_extracti64x2_512_mask:
7275 i = 1; l = 0; u = 3;
7276 break;
7277 case X86::BI_mm_prefetch:
7278 case X86::BI__builtin_ia32_vec_ext_v8hi:
7279 case X86::BI__builtin_ia32_vec_ext_v8si:
7280 i = 1; l = 0; u = 7;
7281 break;
7282 case X86::BI__builtin_ia32_sha1rnds4:
7283 case X86::BI__builtin_ia32_blendpd:
7284 case X86::BI__builtin_ia32_shufpd:
7285 case X86::BI__builtin_ia32_vec_set_v4hi:
7286 case X86::BI__builtin_ia32_vec_set_v4si:
7287 case X86::BI__builtin_ia32_vec_set_v4di:
7288 case X86::BI__builtin_ia32_shuf_f32x4_256:
7289 case X86::BI__builtin_ia32_shuf_f64x2_256:
7290 case X86::BI__builtin_ia32_shuf_i32x4_256:
7291 case X86::BI__builtin_ia32_shuf_i64x2_256:
7292 case X86::BI__builtin_ia32_insertf64x2_512:
7293 case X86::BI__builtin_ia32_inserti64x2_512:
7294 case X86::BI__builtin_ia32_insertf32x4:
7295 case X86::BI__builtin_ia32_inserti32x4:
7296 i = 2; l = 0; u = 3;
7297 break;
7298 case X86::BI__builtin_ia32_vpermil2pd:
7299 case X86::BI__builtin_ia32_vpermil2pd256:
7300 case X86::BI__builtin_ia32_vpermil2ps:
7301 case X86::BI__builtin_ia32_vpermil2ps256:
7302 i = 3; l = 0; u = 3;
7303 break;
7304 case X86::BI__builtin_ia32_cmpb128_mask:
7305 case X86::BI__builtin_ia32_cmpw128_mask:
7306 case X86::BI__builtin_ia32_cmpd128_mask:
7307 case X86::BI__builtin_ia32_cmpq128_mask:
7308 case X86::BI__builtin_ia32_cmpb256_mask:
7309 case X86::BI__builtin_ia32_cmpw256_mask:
7310 case X86::BI__builtin_ia32_cmpd256_mask:
7311 case X86::BI__builtin_ia32_cmpq256_mask:
7312 case X86::BI__builtin_ia32_cmpb512_mask:
7313 case X86::BI__builtin_ia32_cmpw512_mask:
7314 case X86::BI__builtin_ia32_cmpd512_mask:
7315 case X86::BI__builtin_ia32_cmpq512_mask:
7316 case X86::BI__builtin_ia32_ucmpb128_mask:
7317 case X86::BI__builtin_ia32_ucmpw128_mask:
7318 case X86::BI__builtin_ia32_ucmpd128_mask:
7319 case X86::BI__builtin_ia32_ucmpq128_mask:
7320 case X86::BI__builtin_ia32_ucmpb256_mask:
7321 case X86::BI__builtin_ia32_ucmpw256_mask:
7322 case X86::BI__builtin_ia32_ucmpd256_mask:
7323 case X86::BI__builtin_ia32_ucmpq256_mask:
7324 case X86::BI__builtin_ia32_ucmpb512_mask:
7325 case X86::BI__builtin_ia32_ucmpw512_mask:
7326 case X86::BI__builtin_ia32_ucmpd512_mask:
7327 case X86::BI__builtin_ia32_ucmpq512_mask:
7328 case X86::BI__builtin_ia32_vpcomub:
7329 case X86::BI__builtin_ia32_vpcomuw:
7330 case X86::BI__builtin_ia32_vpcomud:
7331 case X86::BI__builtin_ia32_vpcomuq:
7332 case X86::BI__builtin_ia32_vpcomb:
7333 case X86::BI__builtin_ia32_vpcomw:
7334 case X86::BI__builtin_ia32_vpcomd:
7335 case X86::BI__builtin_ia32_vpcomq:
7336 case X86::BI__builtin_ia32_vec_set_v8hi:
7337 case X86::BI__builtin_ia32_vec_set_v8si:
7338 i = 2; l = 0; u = 7;
7339 break;
7340 case X86::BI__builtin_ia32_vpermilpd256:
7341 case X86::BI__builtin_ia32_roundps:
7342 case X86::BI__builtin_ia32_roundpd:
7343 case X86::BI__builtin_ia32_roundps256:
7344 case X86::BI__builtin_ia32_roundpd256:
7345 case X86::BI__builtin_ia32_getmantpd128_mask:
7346 case X86::BI__builtin_ia32_getmantpd256_mask:
7347 case X86::BI__builtin_ia32_getmantps128_mask:
7348 case X86::BI__builtin_ia32_getmantps256_mask:
7349 case X86::BI__builtin_ia32_getmantpd512_mask:
7350 case X86::BI__builtin_ia32_getmantps512_mask:
7351 case X86::BI__builtin_ia32_getmantph128_mask:
7352 case X86::BI__builtin_ia32_getmantph256_mask:
7353 case X86::BI__builtin_ia32_getmantph512_mask:
7354 case X86::BI__builtin_ia32_vec_ext_v16qi:
7355 case X86::BI__builtin_ia32_vec_ext_v16hi:
7356 i = 1; l = 0; u = 15;
7357 break;
7358 case X86::BI__builtin_ia32_pblendd128:
7359 case X86::BI__builtin_ia32_blendps:
7360 case X86::BI__builtin_ia32_blendpd256:
7361 case X86::BI__builtin_ia32_shufpd256:
7362 case X86::BI__builtin_ia32_roundss:
7363 case X86::BI__builtin_ia32_roundsd:
7364 case X86::BI__builtin_ia32_rangepd128_mask:
7365 case X86::BI__builtin_ia32_rangepd256_mask:
7366 case X86::BI__builtin_ia32_rangepd512_mask:
7367 case X86::BI__builtin_ia32_rangeps128_mask:
7368 case X86::BI__builtin_ia32_rangeps256_mask:
7369 case X86::BI__builtin_ia32_rangeps512_mask:
7370 case X86::BI__builtin_ia32_getmantsd_round_mask:
7371 case X86::BI__builtin_ia32_getmantss_round_mask:
7372 case X86::BI__builtin_ia32_getmantsh_round_mask:
7373 case X86::BI__builtin_ia32_vec_set_v16qi:
7374 case X86::BI__builtin_ia32_vec_set_v16hi:
7375 i = 2; l = 0; u = 15;
7376 break;
7377 case X86::BI__builtin_ia32_vec_ext_v32qi:
7378 i = 1; l = 0; u = 31;
7379 break;
7380 case X86::BI__builtin_ia32_cmpps:
7381 case X86::BI__builtin_ia32_cmpss:
7382 case X86::BI__builtin_ia32_cmppd:
7383 case X86::BI__builtin_ia32_cmpsd:
7384 case X86::BI__builtin_ia32_cmpps256:
7385 case X86::BI__builtin_ia32_cmppd256:
7386 case X86::BI__builtin_ia32_cmpps128_mask:
7387 case X86::BI__builtin_ia32_cmppd128_mask:
7388 case X86::BI__builtin_ia32_cmpps256_mask:
7389 case X86::BI__builtin_ia32_cmppd256_mask:
7390 case X86::BI__builtin_ia32_cmpps512_mask:
7391 case X86::BI__builtin_ia32_cmppd512_mask:
7392 case X86::BI__builtin_ia32_cmpsd_mask:
7393 case X86::BI__builtin_ia32_cmpss_mask:
7394 case X86::BI__builtin_ia32_vec_set_v32qi:
7395 i = 2; l = 0; u = 31;
7396 break;
7397 case X86::BI__builtin_ia32_permdf256:
7398 case X86::BI__builtin_ia32_permdi256:
7399 case X86::BI__builtin_ia32_permdf512:
7400 case X86::BI__builtin_ia32_permdi512:
7401 case X86::BI__builtin_ia32_vpermilps:
7402 case X86::BI__builtin_ia32_vpermilps256:
7403 case X86::BI__builtin_ia32_vpermilpd512:
7404 case X86::BI__builtin_ia32_vpermilps512:
7405 case X86::BI__builtin_ia32_pshufd:
7406 case X86::BI__builtin_ia32_pshufd256:
7407 case X86::BI__builtin_ia32_pshufd512:
7408 case X86::BI__builtin_ia32_pshufhw:
7409 case X86::BI__builtin_ia32_pshufhw256:
7410 case X86::BI__builtin_ia32_pshufhw512:
7411 case X86::BI__builtin_ia32_pshuflw:
7412 case X86::BI__builtin_ia32_pshuflw256:
7413 case X86::BI__builtin_ia32_pshuflw512:
7414 case X86::BI__builtin_ia32_vcvtps2ph:
7415 case X86::BI__builtin_ia32_vcvtps2ph_mask:
7416 case X86::BI__builtin_ia32_vcvtps2ph256:
7417 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
7418 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
7419 case X86::BI__builtin_ia32_rndscaleps_128_mask:
7420 case X86::BI__builtin_ia32_rndscalepd_128_mask:
7421 case X86::BI__builtin_ia32_rndscaleps_256_mask:
7422 case X86::BI__builtin_ia32_rndscalepd_256_mask:
7423 case X86::BI__builtin_ia32_rndscaleps_mask:
7424 case X86::BI__builtin_ia32_rndscalepd_mask:
7425 case X86::BI__builtin_ia32_rndscaleph_mask:
7426 case X86::BI__builtin_ia32_reducepd128_mask:
7427 case X86::BI__builtin_ia32_reducepd256_mask:
7428 case X86::BI__builtin_ia32_reducepd512_mask:
7429 case X86::BI__builtin_ia32_reduceps128_mask:
7430 case X86::BI__builtin_ia32_reduceps256_mask:
7431 case X86::BI__builtin_ia32_reduceps512_mask:
7432 case X86::BI__builtin_ia32_reduceph128_mask:
7433 case X86::BI__builtin_ia32_reduceph256_mask:
7434 case X86::BI__builtin_ia32_reduceph512_mask:
7435 case X86::BI__builtin_ia32_prold512:
7436 case X86::BI__builtin_ia32_prolq512:
7437 case X86::BI__builtin_ia32_prold128:
7438 case X86::BI__builtin_ia32_prold256:
7439 case X86::BI__builtin_ia32_prolq128:
7440 case X86::BI__builtin_ia32_prolq256:
7441 case X86::BI__builtin_ia32_prord512:
7442 case X86::BI__builtin_ia32_prorq512:
7443 case X86::BI__builtin_ia32_prord128:
7444 case X86::BI__builtin_ia32_prord256:
7445 case X86::BI__builtin_ia32_prorq128:
7446 case X86::BI__builtin_ia32_prorq256:
7447 case X86::BI__builtin_ia32_fpclasspd128_mask:
7448 case X86::BI__builtin_ia32_fpclasspd256_mask:
7449 case X86::BI__builtin_ia32_fpclassps128_mask:
7450 case X86::BI__builtin_ia32_fpclassps256_mask:
7451 case X86::BI__builtin_ia32_fpclassps512_mask:
7452 case X86::BI__builtin_ia32_fpclasspd512_mask:
7453 case X86::BI__builtin_ia32_fpclassph128_mask:
7454 case X86::BI__builtin_ia32_fpclassph256_mask:
7455 case X86::BI__builtin_ia32_fpclassph512_mask:
7456 case X86::BI__builtin_ia32_fpclasssd_mask:
7457 case X86::BI__builtin_ia32_fpclassss_mask:
7458 case X86::BI__builtin_ia32_fpclasssh_mask:
7459 case X86::BI__builtin_ia32_pslldqi128_byteshift:
7460 case X86::BI__builtin_ia32_pslldqi256_byteshift:
7461 case X86::BI__builtin_ia32_pslldqi512_byteshift:
7462 case X86::BI__builtin_ia32_psrldqi128_byteshift:
7463 case X86::BI__builtin_ia32_psrldqi256_byteshift:
7464 case X86::BI__builtin_ia32_psrldqi512_byteshift:
7465 case X86::BI__builtin_ia32_kshiftliqi:
7466 case X86::BI__builtin_ia32_kshiftlihi:
7467 case X86::BI__builtin_ia32_kshiftlisi:
7468 case X86::BI__builtin_ia32_kshiftlidi:
7469 case X86::BI__builtin_ia32_kshiftriqi:
7470 case X86::BI__builtin_ia32_kshiftrihi:
7471 case X86::BI__builtin_ia32_kshiftrisi:
7472 case X86::BI__builtin_ia32_kshiftridi:
7473 i = 1; l = 0; u = 255;
7474 break;
7475 case X86::BI__builtin_ia32_vperm2f128_pd256:
7476 case X86::BI__builtin_ia32_vperm2f128_ps256:
7477 case X86::BI__builtin_ia32_vperm2f128_si256:
7478 case X86::BI__builtin_ia32_permti256:
7479 case X86::BI__builtin_ia32_pblendw128:
7480 case X86::BI__builtin_ia32_pblendw256:
7481 case X86::BI__builtin_ia32_blendps256:
7482 case X86::BI__builtin_ia32_pblendd256:
7483 case X86::BI__builtin_ia32_palignr128:
7484 case X86::BI__builtin_ia32_palignr256:
7485 case X86::BI__builtin_ia32_palignr512:
7486 case X86::BI__builtin_ia32_alignq512:
7487 case X86::BI__builtin_ia32_alignd512:
7488 case X86::BI__builtin_ia32_alignd128:
7489 case X86::BI__builtin_ia32_alignd256:
7490 case X86::BI__builtin_ia32_alignq128:
7491 case X86::BI__builtin_ia32_alignq256:
7492 case X86::BI__builtin_ia32_vcomisd:
7493 case X86::BI__builtin_ia32_vcomiss:
7494 case X86::BI__builtin_ia32_shuf_f32x4:
7495 case X86::BI__builtin_ia32_shuf_f64x2:
7496 case X86::BI__builtin_ia32_shuf_i32x4:
7497 case X86::BI__builtin_ia32_shuf_i64x2:
7498 case X86::BI__builtin_ia32_shufpd512:
7499 case X86::BI__builtin_ia32_shufps:
7500 case X86::BI__builtin_ia32_shufps256:
7501 case X86::BI__builtin_ia32_shufps512:
7502 case X86::BI__builtin_ia32_dbpsadbw128:
7503 case X86::BI__builtin_ia32_dbpsadbw256:
7504 case X86::BI__builtin_ia32_dbpsadbw512:
7505 case X86::BI__builtin_ia32_vpshldd128:
7506 case X86::BI__builtin_ia32_vpshldd256:
7507 case X86::BI__builtin_ia32_vpshldd512:
7508 case X86::BI__builtin_ia32_vpshldq128:
7509 case X86::BI__builtin_ia32_vpshldq256:
7510 case X86::BI__builtin_ia32_vpshldq512:
7511 case X86::BI__builtin_ia32_vpshldw128:
7512 case X86::BI__builtin_ia32_vpshldw256:
7513 case X86::BI__builtin_ia32_vpshldw512:
7514 case X86::BI__builtin_ia32_vpshrdd128:
7515 case X86::BI__builtin_ia32_vpshrdd256:
7516 case X86::BI__builtin_ia32_vpshrdd512:
7517 case X86::BI__builtin_ia32_vpshrdq128:
7518 case X86::BI__builtin_ia32_vpshrdq256:
7519 case X86::BI__builtin_ia32_vpshrdq512:
7520 case X86::BI__builtin_ia32_vpshrdw128:
7521 case X86::BI__builtin_ia32_vpshrdw256:
7522 case X86::BI__builtin_ia32_vpshrdw512:
7523 i = 2; l = 0; u = 255;
7524 break;
7525 case X86::BI__builtin_ia32_fixupimmpd512_mask:
7526 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
7527 case X86::BI__builtin_ia32_fixupimmps512_mask:
7528 case X86::BI__builtin_ia32_fixupimmps512_maskz:
7529 case X86::BI__builtin_ia32_fixupimmsd_mask:
7530 case X86::BI__builtin_ia32_fixupimmsd_maskz:
7531 case X86::BI__builtin_ia32_fixupimmss_mask:
7532 case X86::BI__builtin_ia32_fixupimmss_maskz:
7533 case X86::BI__builtin_ia32_fixupimmpd128_mask:
7534 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
7535 case X86::BI__builtin_ia32_fixupimmpd256_mask:
7536 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
7537 case X86::BI__builtin_ia32_fixupimmps128_mask:
7538 case X86::BI__builtin_ia32_fixupimmps128_maskz:
7539 case X86::BI__builtin_ia32_fixupimmps256_mask:
7540 case X86::BI__builtin_ia32_fixupimmps256_maskz:
7541 case X86::BI__builtin_ia32_pternlogd512_mask:
7542 case X86::BI__builtin_ia32_pternlogd512_maskz:
7543 case X86::BI__builtin_ia32_pternlogq512_mask:
7544 case X86::BI__builtin_ia32_pternlogq512_maskz:
7545 case X86::BI__builtin_ia32_pternlogd128_mask:
7546 case X86::BI__builtin_ia32_pternlogd128_maskz:
7547 case X86::BI__builtin_ia32_pternlogd256_mask:
7548 case X86::BI__builtin_ia32_pternlogd256_maskz:
7549 case X86::BI__builtin_ia32_pternlogq128_mask:
7550 case X86::BI__builtin_ia32_pternlogq128_maskz:
7551 case X86::BI__builtin_ia32_pternlogq256_mask:
7552 case X86::BI__builtin_ia32_pternlogq256_maskz:
7553 case X86::BI__builtin_ia32_vsm3rnds2:
7554 i = 3; l = 0; u = 255;
7555 break;
7556 case X86::BI__builtin_ia32_gatherpfdpd:
7557 case X86::BI__builtin_ia32_gatherpfdps:
7558 case X86::BI__builtin_ia32_gatherpfqpd:
7559 case X86::BI__builtin_ia32_gatherpfqps:
7560 case X86::BI__builtin_ia32_scatterpfdpd:
7561 case X86::BI__builtin_ia32_scatterpfdps:
7562 case X86::BI__builtin_ia32_scatterpfqpd:
7563 case X86::BI__builtin_ia32_scatterpfqps:
7564 i = 4; l = 2; u = 3;
7565 break;
7566 case X86::BI__builtin_ia32_reducesd_mask:
7567 case X86::BI__builtin_ia32_reducess_mask:
7568 case X86::BI__builtin_ia32_rndscalesd_round_mask:
7569 case X86::BI__builtin_ia32_rndscaless_round_mask:
7570 case X86::BI__builtin_ia32_rndscalesh_round_mask:
7571 case X86::BI__builtin_ia32_reducesh_mask:
7572 i = 4; l = 0; u = 255;
7573 break;
7574 case X86::BI__builtin_ia32_cmpccxadd32:
7575 case X86::BI__builtin_ia32_cmpccxadd64:
7576 i = 3; l = 0; u = 15;
7577 break;
7578 }
7579
7580 // Note that we don't force a hard error on the range check here, allowing
7581 // template-generated or macro-generated dead code to potentially have out-of-
7582 // range values. These need to code generate, but don't need to necessarily
7583 // make any sense. We use a warning that defaults to an error.
7584 return BuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
7585}
7586
7587/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
7588/// parameter with the FormatAttr's correct format_idx and firstDataArg.
7589/// Returns true when the format fits the function and the FormatStringInfo has
7590/// been populated.
7591bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
7592 bool IsVariadic, FormatStringInfo *FSI) {
7593 if (Format->getFirstArg() == 0)
7595 else if (IsVariadic)
7597 else
7599 FSI->FormatIdx = Format->getFormatIdx() - 1;
7600 FSI->FirstDataArg =
7601 FSI->ArgPassingKind == FAPK_VAList ? 0 : Format->getFirstArg() - 1;
7602
7603 // The way the format attribute works in GCC, the implicit this argument
7604 // of member functions is counted. However, it doesn't appear in our own
7605 // lists, so decrement format_idx in that case.
7606 if (IsCXXMember) {
7607 if(FSI->FormatIdx == 0)
7608 return false;
7609 --FSI->FormatIdx;
7610 if (FSI->FirstDataArg != 0)
7611 --FSI->FirstDataArg;
7612 }
7613 return true;
7614}
7615
7616/// Checks if a the given expression evaluates to null.
7617///
7618/// Returns true if the value evaluates to null.
7619static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
7620 // Treat (smart) pointers constructed from nullptr as null, whether we can
7621 // const-evaluate them or not.
7622 // This must happen first: the smart pointer expr might have _Nonnull type!
7623 if (isa<CXXNullPtrLiteralExpr>(
7626 return true;
7627
7628 // If the expression has non-null type, it doesn't evaluate to null.
7629 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
7630 if (*nullability == NullabilityKind::NonNull)
7631 return false;
7632 }
7633
7634 // As a special case, transparent unions initialized with zero are
7635 // considered null for the purposes of the nonnull attribute.
7636 if (const RecordType *UT = Expr->getType()->getAsUnionType();
7637 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
7638 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
7639 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
7640 Expr = ILE->getInit(0);
7641 }
7642
7643 bool Result;
7644 return (!Expr->isValueDependent() &&
7646 !Result);
7647}
7648
7650 const Expr *ArgExpr,
7651 SourceLocation CallSiteLoc) {
7652 if (CheckNonNullExpr(S, ArgExpr))
7653 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
7654 S.PDiag(diag::warn_null_arg)
7655 << ArgExpr->getSourceRange());
7656}
7657
7658bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
7659 FormatStringInfo FSI;
7660 if ((GetFormatStringType(Format) == FST_NSString) &&
7661 getFormatStringInfo(Format, false, true, &FSI)) {
7662 Idx = FSI.FormatIdx;
7663 return true;
7664 }
7665 return false;
7666}
7667
7668/// Diagnose use of %s directive in an NSString which is being passed
7669/// as formatting string to formatting method.
7670static void
7672 const NamedDecl *FDecl,
7673 Expr **Args,
7674 unsigned NumArgs) {
7675 unsigned Idx = 0;
7676 bool Format = false;
7678 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
7679 Idx = 2;
7680 Format = true;
7681 }
7682 else
7683 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
7684 if (S.GetFormatNSStringIdx(I, Idx)) {
7685 Format = true;
7686 break;
7687 }
7688 }
7689 if (!Format || NumArgs <= Idx)
7690 return;
7691 const Expr *FormatExpr = Args[Idx];
7692 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
7693 FormatExpr = CSCE->getSubExpr();
7694 const StringLiteral *FormatString;
7695 if (const ObjCStringLiteral *OSL =
7696 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
7697 FormatString = OSL->getString();
7698 else
7699 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
7700 if (!FormatString)
7701 return;
7702 if (S.FormatStringHasSArg(FormatString)) {
7703 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
7704 << "%s" << 1 << 1;
7705 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
7706 << FDecl->getDeclName();
7707 }
7708}
7709
7710/// Determine whether the given type has a non-null nullability annotation.
7712 if (auto nullability = type->getNullability())
7713 return *nullability == NullabilityKind::NonNull;
7714
7715 return false;
7716}
7717
7719 const NamedDecl *FDecl,
7720 const FunctionProtoType *Proto,
7722 SourceLocation CallSiteLoc) {
7723 assert((FDecl || Proto) && "Need a function declaration or prototype");
7724
7725 // Already checked by constant evaluator.
7727 return;
7728 // Check the attributes attached to the method/function itself.
7729 llvm::SmallBitVector NonNullArgs;
7730 if (FDecl) {
7731 // Handle the nonnull attribute on the function/method declaration itself.
7732 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
7733 if (!NonNull->args_size()) {
7734 // Easy case: all pointer arguments are nonnull.
7735 for (const auto *Arg : Args)
7736 if (S.isValidPointerAttrType(Arg->getType()))
7737 CheckNonNullArgument(S, Arg, CallSiteLoc);
7738 return;
7739 }
7740
7741 for (const ParamIdx &Idx : NonNull->args()) {
7742 unsigned IdxAST = Idx.getASTIndex();
7743 if (IdxAST >= Args.size())
7744 continue;
7745 if (NonNullArgs.empty())
7746 NonNullArgs.resize(Args.size());
7747 NonNullArgs.set(IdxAST);
7748 }
7749 }
7750 }
7751
7752 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
7753 // Handle the nonnull attribute on the parameters of the
7754 // function/method.
7756 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
7757 parms = FD->parameters();
7758 else
7759 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
7760
7761 unsigned ParamIndex = 0;
7762 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
7763 I != E; ++I, ++ParamIndex) {
7764 const ParmVarDecl *PVD = *I;
7765 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
7766 if (NonNullArgs.empty())
7767 NonNullArgs.resize(Args.size());
7768
7769 NonNullArgs.set(ParamIndex);
7770 }
7771 }
7772 } else {
7773 // If we have a non-function, non-method declaration but no
7774 // function prototype, try to dig out the function prototype.
7775 if (!Proto) {
7776 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
7777 QualType type = VD->getType().getNonReferenceType();
7778 if (auto pointerType = type->getAs<PointerType>())
7779 type = pointerType->getPointeeType();
7780 else if (auto blockType = type->getAs<BlockPointerType>())
7781 type = blockType->getPointeeType();
7782 // FIXME: data member pointers?
7783
7784 // Dig out the function prototype, if there is one.
7785 Proto = type->getAs<FunctionProtoType>();
7786 }
7787 }
7788
7789 // Fill in non-null argument information from the nullability
7790 // information on the parameter types (if we have them).
7791 if (Proto) {
7792 unsigned Index = 0;
7793 for (auto paramType : Proto->getParamTypes()) {
7794 if (isNonNullType(paramType)) {
7795 if (NonNullArgs.empty())
7796 NonNullArgs.resize(Args.size());
7797
7798 NonNullArgs.set(Index);
7799 }
7800
7801 ++Index;
7802 }
7803 }
7804 }
7805
7806 // Check for non-null arguments.
7807 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
7808 ArgIndex != ArgIndexEnd; ++ArgIndex) {
7809 if (NonNullArgs[ArgIndex])
7810 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
7811 }
7812}
7813
7814// 16 byte ByVal alignment not due to a vector member is not honoured by XL
7815// on AIX. Emit a warning here that users are generating binary incompatible
7816// code to be safe.
7817// Here we try to get information about the alignment of the struct member
7818// from the struct passed to the caller function. We only warn when the struct
7819// is passed byval, hence the series of checks and early returns if we are a not
7820// passing a struct byval.
7821void Sema::checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg) {
7822 const auto *ICE = dyn_cast<ImplicitCastExpr>(Arg->IgnoreParens());
7823 if (!ICE)
7824 return;
7825
7826 const auto *DR = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
7827 if (!DR)
7828 return;
7829
7830 const auto *PD = dyn_cast<ParmVarDecl>(DR->getDecl());
7831 if (!PD || !PD->getType()->isRecordType())
7832 return;
7833
7834 QualType ArgType = Arg->getType();
7835 for (const FieldDecl *FD :
7836 ArgType->castAs<RecordType>()->getDecl()->fields()) {
7837 if (const auto *AA = FD->getAttr<AlignedAttr>()) {
7838 CharUnits Alignment =
7839 Context.toCharUnitsFromBits(AA->getAlignment(Context));
7840 if (Alignment.getQuantity() == 16) {
7841 Diag(FD->getLocation(), diag::warn_not_xl_compatible) << FD;
7842 Diag(Loc, diag::note_misaligned_member_used_here) << PD;
7843 }
7844 }
7845 }
7846}
7847
7848/// Warn if a pointer or reference argument passed to a function points to an
7849/// object that is less aligned than the parameter. This can happen when
7850/// creating a typedef with a lower alignment than the original type and then
7851/// calling functions defined in terms of the original type.
7852void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
7853 StringRef ParamName, QualType ArgTy,
7854 QualType ParamTy) {
7855
7856 // If a function accepts a pointer or reference type
7857 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
7858 return;
7859
7860 // If the parameter is a pointer type, get the pointee type for the
7861 // argument too. If the parameter is a reference type, don't try to get
7862 // the pointee type for the argument.
7863 if (ParamTy->isPointerType())
7864 ArgTy = ArgTy->getPointeeType();
7865
7866 // Remove reference or pointer
7867 ParamTy = ParamTy->getPointeeType();
7868
7869 // Find expected alignment, and the actual alignment of the passed object.
7870 // getTypeAlignInChars requires complete types
7871 if (ArgTy.isNull() || ParamTy->isDependentType() ||
7872 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
7873 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
7874 return;
7875
7876 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
7877 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
7878
7879 // If the argument is less aligned than the parameter, there is a
7880 // potential alignment issue.
7881 if (ArgAlign < ParamAlign)
7882 Diag(Loc, diag::warn_param_mismatched_alignment)
7883 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
7884 << ParamName << (FDecl != nullptr) << FDecl;
7885}
7886
7887/// Handles the checks for format strings, non-POD arguments to vararg
7888/// functions, NULL arguments passed to non-NULL parameters, diagnose_if
7889/// attributes and AArch64 SME attributes.
7890void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
7891 const Expr *ThisArg, ArrayRef<const Expr *> Args,
7892 bool IsMemberFunction, SourceLocation Loc,
7893 SourceRange Range, VariadicCallType CallType) {
7894 // FIXME: We should check as much as we can in the template definition.
7896 return;
7897
7898 // Printf and scanf checking.
7899 llvm::SmallBitVector CheckedVarArgs;
7900 if (FDecl) {
7901 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
7902 // Only create vector if there are format attributes.
7903 CheckedVarArgs.resize(Args.size());
7904
7905 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
7906 CheckedVarArgs);
7907 }
7908 }
7909
7910 // Refuse POD arguments that weren't caught by the format string
7911 // checks above.
7912 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
7913 if (CallType != VariadicDoesNotApply &&
7914 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
7915 unsigned NumParams = Proto ? Proto->getNumParams()
7916 : FDecl && isa<FunctionDecl>(FDecl)
7917 ? cast<FunctionDecl>(FDecl)->getNumParams()
7918 : FDecl && isa<ObjCMethodDecl>(FDecl)
7919 ? cast<ObjCMethodDecl>(FDecl)->param_size()
7920 : 0;
7921
7922 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
7923 // Args[ArgIdx] can be null in malformed code.
7924 if (const Expr *Arg = Args[ArgIdx]) {
7925 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
7926 checkVariadicArgument(Arg, CallType);
7927 }
7928 }
7929 }
7930
7931 if (FDecl || Proto) {
7932 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
7933
7934 // Type safety checking.
7935 if (FDecl) {
7936 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
7937 CheckArgumentWithTypeTag(I, Args, Loc);
7938 }
7939 }
7940
7941 // Check that passed arguments match the alignment of original arguments.
7942 // Try to get the missing prototype from the declaration.
7943 if (!Proto && FDecl) {
7944 const auto *FT = FDecl->getFunctionType();
7945 if (isa_and_nonnull<FunctionProtoType>(FT))
7946 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
7947 }
7948 if (Proto) {
7949 // For variadic functions, we may have more args than parameters.
7950 // For some K&R functions, we may have less args than parameters.
7951 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
7952 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
7953 // Args[ArgIdx] can be null in malformed code.
7954 if (const Expr *Arg = Args[ArgIdx]) {
7955 if (Arg->containsErrors())
7956 continue;
7957
7958 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
7959 FDecl->hasLinkage() &&
7960 FDecl->getFormalLinkage() != Linkage::Internal &&
7961 CallType == VariadicDoesNotApply)
7962 checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
7963
7964 QualType ParamTy = Proto->getParamType(ArgIdx);
7965 QualType ArgTy = Arg->getType();
7966 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
7967 ArgTy, ParamTy);
7968 }
7969 }
7970
7971 // If the callee has an AArch64 SME attribute to indicate that it is an
7972 // __arm_streaming function, then the caller requires SME to be available.
7975 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
7976 llvm::StringMap<bool> CallerFeatureMap;
7977 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
7978 if (!CallerFeatureMap.contains("sme"))
7979 Diag(Loc, diag::err_sme_call_in_non_sme_target);
7980 } else if (!Context.getTargetInfo().hasFeature("sme")) {
7981 Diag(Loc, diag::err_sme_call_in_non_sme_target);
7982 }
7983 }
7984
7985 FunctionType::ArmStateValue CalleeArmZAState =
7987 FunctionType::ArmStateValue CalleeArmZT0State =
7989 if (CalleeArmZAState != FunctionType::ARM_None ||
7990 CalleeArmZT0State != FunctionType::ARM_None) {
7991 bool CallerHasZAState = false;
7992 bool CallerHasZT0State = false;
7993 if (const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
7994 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
7995 if (Attr && Attr->isNewZA())
7996 CallerHasZAState = true;
7997 if (Attr && Attr->isNewZT0())
7998 CallerHasZT0State = true;
7999 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
8000 CallerHasZAState |=
8002 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
8004 CallerHasZT0State |=
8006 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
8008 }
8009 }
8010
8011 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
8012 Diag(Loc, diag::err_sme_za_call_no_za_state);
8013
8014 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
8015 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
8016
8017 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
8018 CalleeArmZT0State != FunctionType::ARM_None) {
8019 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
8020 Diag(Loc, diag::note_sme_use_preserves_za);
8021 }
8022 }
8023 }
8024
8025 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
8026 auto *AA = FDecl->getAttr<AllocAlignAttr>();
8027 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
8028 if (!Arg->isValueDependent()) {
8029 Expr::EvalResult Align;
8030 if (Arg->EvaluateAsInt(Align, Context)) {
8031 const llvm::APSInt &I = Align.Val.getInt();
8032 if (!I.isPowerOf2())
8033 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
8034 << Arg->getSourceRange();
8035
8036 if (I > Sema::MaximumAlignment)
8037 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
8038 << Arg->getSourceRange() << Sema::MaximumAlignment;
8039 }
8040 }
8041 }
8042
8043 if (FD)
8044 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
8045}
8046
8047/// CheckConstructorCall - Check a constructor call for correctness and safety
8048/// properties not enforced by the C type system.
8049void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
8051 const FunctionProtoType *Proto,
8052 SourceLocation Loc) {
8053 VariadicCallType CallType =
8055
8056 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
8057 CheckArgAlignment(
8058 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
8059 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
8060
8061 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
8062 Loc, SourceRange(), CallType);
8063}
8064
8065/// CheckFunctionCall - Check a direct function call for various correctness
8066/// and safety properties not strictly enforced by the C type system.
8068 const FunctionProtoType *Proto) {
8069 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
8070 isa<CXXMethodDecl>(FDecl);
8071 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
8072 IsMemberOperatorCall;
8073 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
8074 TheCall->getCallee());
8075 Expr** Args = TheCall->getArgs();
8076 unsigned NumArgs = TheCall->getNumArgs();
8077
8078 Expr *ImplicitThis = nullptr;
8079 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
8080 // If this is a call to a member operator, hide the first
8081 // argument from checkCall.
8082 // FIXME: Our choice of AST representation here is less than ideal.
8083 ImplicitThis = Args[0];
8084 ++Args;
8085 --NumArgs;
8086 } else if (IsMemberFunction && !FDecl->isStatic() &&
8088 ImplicitThis =
8089 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
8090
8091 if (ImplicitThis) {
8092 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
8093 // used.
8094 QualType ThisType = ImplicitThis->getType();
8095 if (!ThisType->isPointerType()) {
8096 assert(!ThisType->isReferenceType());
8097 ThisType = Context.getPointerType(ThisType);
8098 }
8099
8100 QualType ThisTypeFromDecl = Context.getPointerType(
8101 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
8102
8103 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
8104 ThisTypeFromDecl);
8105 }
8106
8107 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
8108 IsMemberFunction, TheCall->getRParenLoc(),
8109 TheCall->getCallee()->getSourceRange(), CallType);
8110
8111 IdentifierInfo *FnInfo = FDecl->getIdentifier();
8112 // None of the checks below are needed for functions that don't have
8113 // simple names (e.g., C++ conversion functions).
8114 if (!FnInfo)
8115 return false;
8116
8117 // Enforce TCB except for builtin calls, which are always allowed.
8118 if (FDecl->getBuiltinID() == 0)
8119 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
8120
8121 CheckAbsoluteValueFunction(TheCall, FDecl);
8122 CheckMaxUnsignedZero(TheCall, FDecl);
8123 CheckInfNaNFunction(TheCall, FDecl);
8124
8125 if (getLangOpts().ObjC)
8126 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
8127
8128 unsigned CMId = FDecl->getMemoryFunctionKind();
8129
8130 // Handle memory setting and copying functions.
8131 switch (CMId) {
8132 case 0:
8133 return false;
8134 case Builtin::BIstrlcpy: // fallthrough
8135 case Builtin::BIstrlcat:
8136 CheckStrlcpycatArguments(TheCall, FnInfo);
8137 break;
8138 case Builtin::BIstrncat:
8139 CheckStrncatArguments(TheCall, FnInfo);
8140 break;
8141 case Builtin::BIfree:
8142 CheckFreeArguments(TheCall);
8143 break;
8144 default:
8145 CheckMemaccessArguments(TheCall, CMId, FnInfo);
8146 }
8147
8148 return false;
8149}
8150
8151bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
8153 VariadicCallType CallType =
8155
8156 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
8157 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
8158 CallType);
8159
8160 CheckTCBEnforcement(lbrac, Method);
8161
8162 return false;
8163}
8164
8165bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
8166 const FunctionProtoType *Proto) {
8167 QualType Ty;
8168 if (const auto *V = dyn_cast<VarDecl>(NDecl))
8169 Ty = V->getType().getNonReferenceType();
8170 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
8171 Ty = F->getType().getNonReferenceType();
8172 else
8173 return false;
8174
8175 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
8176 !Ty->isFunctionProtoType())
8177 return false;
8178
8179 VariadicCallType CallType;
8180 if (!Proto || !Proto->isVariadic()) {
8181 CallType = VariadicDoesNotApply;
8182 } else if (Ty->isBlockPointerType()) {
8183 CallType = VariadicBlock;
8184 } else { // Ty->isFunctionPointerType()
8185 CallType = VariadicFunction;
8186 }
8187
8188 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
8189 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
8190 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
8191 TheCall->getCallee()->getSourceRange(), CallType);
8192
8193 return false;
8194}
8195
8196/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
8197/// such as function pointers returned from functions.
8198bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
8199 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
8200 TheCall->getCallee());
8201 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
8202 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
8203 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
8204 TheCall->getCallee()->getSourceRange(), CallType);
8205
8206 return false;
8207}
8208
8209static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
8210 if (!llvm::isValidAtomicOrderingCABI(Ordering))
8211 return false;
8212
8213 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
8214 switch (Op) {
8215 case AtomicExpr::AO__c11_atomic_init:
8216 case AtomicExpr::AO__opencl_atomic_init:
8217 llvm_unreachable("There is no ordering argument for an init");
8218
8219 case AtomicExpr::AO__c11_atomic_load:
8220 case AtomicExpr::AO__opencl_atomic_load:
8221 case AtomicExpr::AO__hip_atomic_load:
8222 case AtomicExpr::AO__atomic_load_n:
8223 case AtomicExpr::AO__atomic_load:
8224 case AtomicExpr::AO__scoped_atomic_load_n:
8225 case AtomicExpr::AO__scoped_atomic_load:
8226 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
8227 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
8228
8229 case AtomicExpr::AO__c11_atomic_store:
8230 case AtomicExpr::AO__opencl_atomic_store:
8231 case AtomicExpr::AO__hip_atomic_store:
8232 case AtomicExpr::AO__atomic_store:
8233 case AtomicExpr::AO__atomic_store_n:
8234 case AtomicExpr::AO__scoped_atomic_store:
8235 case AtomicExpr::AO__scoped_atomic_store_n:
8236 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
8237 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
8238 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
8239
8240 default:
8241 return true;
8242 }
8243}
8244
8245ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
8247 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
8248 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
8249 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
8250 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
8251 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
8252 Op);
8253}
8254
8256 SourceLocation RParenLoc, MultiExprArg Args,
8258 AtomicArgumentOrder ArgOrder) {
8259 // All the non-OpenCL operations take one of the following forms.
8260 // The OpenCL operations take the __c11 forms with one extra argument for
8261 // synchronization scope.
8262 enum {
8263 // C __c11_atomic_init(A *, C)
8264 Init,
8265
8266 // C __c11_atomic_load(A *, int)
8267 Load,
8268
8269 // void __atomic_load(A *, CP, int)
8270 LoadCopy,
8271
8272 // void __atomic_store(A *, CP, int)
8273 Copy,
8274
8275 // C __c11_atomic_add(A *, M, int)
8276 Arithmetic,
8277
8278 // C __atomic_exchange_n(A *, CP, int)
8279 Xchg,
8280
8281 // void __atomic_exchange(A *, C *, CP, int)
8282 GNUXchg,
8283
8284 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
8285 C11CmpXchg,
8286
8287 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
8288 GNUCmpXchg
8289 } Form = Init;
8290
8291 const unsigned NumForm = GNUCmpXchg + 1;
8292 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
8293 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
8294 // where:
8295 // C is an appropriate type,
8296 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
8297 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
8298 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
8299 // the int parameters are for orderings.
8300
8301 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
8302 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
8303 "need to update code for modified forms");
8304 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
8305 AtomicExpr::AO__atomic_xor_fetch + 1 ==
8306 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
8307 "need to update code for modified C11 atomics");
8308 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
8309 Op <= AtomicExpr::AO__opencl_atomic_store;
8310 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
8311 Op <= AtomicExpr::AO__hip_atomic_store;
8312 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
8313 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
8314 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
8315 Op <= AtomicExpr::AO__c11_atomic_store) ||
8316 IsOpenCL;
8317 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
8318 Op == AtomicExpr::AO__atomic_store_n ||
8319 Op == AtomicExpr::AO__atomic_exchange_n ||
8320 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
8321 Op == AtomicExpr::AO__scoped_atomic_load_n ||
8322 Op == AtomicExpr::AO__scoped_atomic_store_n ||
8323 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
8324 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
8325 // Bit mask for extra allowed value types other than integers for atomic
8326 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
8327 // allow floating point.
8328 enum ArithOpExtraValueType {
8329 AOEVT_None = 0,
8330 AOEVT_Pointer = 1,
8331 AOEVT_FP = 2,
8332 };
8333 unsigned ArithAllows = AOEVT_None;
8334
8335 switch (Op) {
8336 case AtomicExpr::AO__c11_atomic_init:
8337 case AtomicExpr::AO__opencl_atomic_init:
8338 Form = Init;
8339 break;
8340
8341 case AtomicExpr::AO__c11_atomic_load:
8342 case AtomicExpr::AO__opencl_atomic_load:
8343 case AtomicExpr::AO__hip_atomic_load:
8344 case AtomicExpr::AO__atomic_load_n:
8345 case AtomicExpr::AO__scoped_atomic_load_n:
8346 Form = Load;
8347 break;
8348
8349 case AtomicExpr::AO__atomic_load:
8350 case AtomicExpr::AO__scoped_atomic_load:
8351 Form = LoadCopy;
8352 break;
8353
8354 case AtomicExpr::AO__c11_atomic_store:
8355 case AtomicExpr::AO__opencl_atomic_store:
8356 case AtomicExpr::AO__hip_atomic_store:
8357 case AtomicExpr::AO__atomic_store:
8358 case AtomicExpr::AO__atomic_store_n:
8359 case AtomicExpr::AO__scoped_atomic_store:
8360 case AtomicExpr::AO__scoped_atomic_store_n:
8361 Form = Copy;
8362 break;
8363 case AtomicExpr::AO__atomic_fetch_add:
8364 case AtomicExpr::AO__atomic_fetch_sub:
8365 case AtomicExpr::AO__atomic_add_fetch:
8366 case AtomicExpr::AO__atomic_sub_fetch:
8367 case AtomicExpr::AO__scoped_atomic_fetch_add:
8368 case AtomicExpr::AO__scoped_atomic_fetch_sub:
8369 case AtomicExpr::AO__scoped_atomic_add_fetch:
8370 case AtomicExpr::AO__scoped_atomic_sub_fetch:
8371 case AtomicExpr::AO__c11_atomic_fetch_add:
8372 case AtomicExpr::AO__c11_atomic_fetch_sub:
8373 case AtomicExpr::AO__opencl_atomic_fetch_add:
8374 case AtomicExpr::AO__opencl_atomic_fetch_sub:
8375 case AtomicExpr::AO__hip_atomic_fetch_add:
8376 case AtomicExpr::AO__hip_atomic_fetch_sub:
8377 ArithAllows = AOEVT_Pointer | AOEVT_FP;
8378 Form = Arithmetic;
8379 break;
8380 case AtomicExpr::AO__atomic_fetch_max:
8381 case AtomicExpr::AO__atomic_fetch_min:
8382 case AtomicExpr::AO__atomic_max_fetch:
8383 case AtomicExpr::AO__atomic_min_fetch:
8384 case AtomicExpr::AO__scoped_atomic_fetch_max:
8385 case AtomicExpr::AO__scoped_atomic_fetch_min:
8386 case AtomicExpr::AO__scoped_atomic_max_fetch:
8387 case AtomicExpr::AO__scoped_atomic_min_fetch:
8388 case AtomicExpr::AO__c11_atomic_fetch_max:
8389 case AtomicExpr::AO__c11_atomic_fetch_min:
8390 case AtomicExpr::AO__opencl_atomic_fetch_max:
8391 case AtomicExpr::AO__opencl_atomic_fetch_min:
8392 case AtomicExpr::AO__hip_atomic_fetch_max:
8393 case AtomicExpr::AO__hip_atomic_fetch_min:
8394 ArithAllows = AOEVT_FP;
8395 Form = Arithmetic;
8396 break;
8397 case AtomicExpr::AO__c11_atomic_fetch_and:
8398 case AtomicExpr::AO__c11_atomic_fetch_or:
8399 case AtomicExpr::AO__c11_atomic_fetch_xor:
8400 case AtomicExpr::AO__hip_atomic_fetch_and:
8401 case AtomicExpr::AO__hip_atomic_fetch_or:
8402 case AtomicExpr::AO__hip_atomic_fetch_xor:
8403 case AtomicExpr::AO__c11_atomic_fetch_nand:
8404 case AtomicExpr::AO__opencl_atomic_fetch_and:
8405 case AtomicExpr::AO__opencl_atomic_fetch_or:
8406 case AtomicExpr::AO__opencl_atomic_fetch_xor:
8407 case AtomicExpr::AO__atomic_fetch_and:
8408 case AtomicExpr::AO__atomic_fetch_or:
8409 case AtomicExpr::AO__atomic_fetch_xor:
8410 case AtomicExpr::AO__atomic_fetch_nand:
8411 case AtomicExpr::AO__atomic_and_fetch:
8412 case AtomicExpr::AO__atomic_or_fetch:
8413 case AtomicExpr::AO__atomic_xor_fetch:
8414 case AtomicExpr::AO__atomic_nand_fetch:
8415 case AtomicExpr::AO__scoped_atomic_fetch_and:
8416 case AtomicExpr::AO__scoped_atomic_fetch_or:
8417 case AtomicExpr::AO__scoped_atomic_fetch_xor:
8418 case AtomicExpr::AO__scoped_atomic_fetch_nand:
8419 case AtomicExpr::AO__scoped_atomic_and_fetch:
8420 case AtomicExpr::AO__scoped_atomic_or_fetch:
8421 case AtomicExpr::AO__scoped_atomic_xor_fetch:
8422 case AtomicExpr::AO__scoped_atomic_nand_fetch:
8423 Form = Arithmetic;
8424 break;
8425
8426 case AtomicExpr::AO__c11_atomic_exchange:
8427 case AtomicExpr::AO__hip_atomic_exchange:
8428 case AtomicExpr::AO__opencl_atomic_exchange:
8429 case AtomicExpr::AO__atomic_exchange_n:
8430 case AtomicExpr::AO__scoped_atomic_exchange_n:
8431 Form = Xchg;
8432 break;
8433
8434 case AtomicExpr::AO__atomic_exchange:
8435 case AtomicExpr::AO__scoped_atomic_exchange:
8436 Form = GNUXchg;
8437 break;
8438
8439 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
8440 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
8441 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
8442 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
8443 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
8444 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
8445 Form = C11CmpXchg;
8446 break;
8447
8448 case AtomicExpr::AO__atomic_compare_exchange:
8449 case AtomicExpr::AO__atomic_compare_exchange_n:
8450 case AtomicExpr::AO__scoped_atomic_compare_exchange:
8451 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
8452 Form = GNUCmpXchg;
8453 break;
8454 }
8455
8456 unsigned AdjustedNumArgs = NumArgs[Form];
8457 if ((IsOpenCL || IsHIP || IsScoped) &&
8458 Op != AtomicExpr::AO__opencl_atomic_init)
8459 ++AdjustedNumArgs;
8460 // Check we have the right number of arguments.
8461 if (Args.size() < AdjustedNumArgs) {
8462 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
8463 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
8464 << /*is non object*/ 0 << ExprRange;
8465 return ExprError();
8466 } else if (Args.size() > AdjustedNumArgs) {
8467 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
8468 diag::err_typecheck_call_too_many_args)
8469 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
8470 << /*is non object*/ 0 << ExprRange;
8471 return ExprError();
8472 }
8473
8474 // Inspect the first argument of the atomic operation.
8475 Expr *Ptr = Args[0];
8477 if (ConvertedPtr.isInvalid())
8478 return ExprError();
8479
8480 Ptr = ConvertedPtr.get();
8481 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
8482 if (!pointerType) {
8483 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
8484 << Ptr->getType() << Ptr->getSourceRange();
8485 return ExprError();
8486 }
8487
8488 // For a __c11 builtin, this should be a pointer to an _Atomic type.
8489 QualType AtomTy = pointerType->getPointeeType(); // 'A'
8490 QualType ValType = AtomTy; // 'C'
8491 if (IsC11) {
8492 if (!AtomTy->isAtomicType()) {
8493 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
8494 << Ptr->getType() << Ptr->getSourceRange();
8495 return ExprError();
8496 }
8497 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
8499 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
8500 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
8501 << Ptr->getSourceRange();
8502 return ExprError();
8503 }
8504 ValType = AtomTy->castAs<AtomicType>()->getValueType();
8505 } else if (Form != Load && Form != LoadCopy) {
8506 if (ValType.isConstQualified()) {
8507 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
8508 << Ptr->getType() << Ptr->getSourceRange();
8509 return ExprError();
8510 }
8511 }
8512
8513 // For an arithmetic operation, the implied arithmetic must be well-formed.
8514 if (Form == Arithmetic) {
8515 // GCC does not enforce these rules for GNU atomics, but we do to help catch
8516 // trivial type errors.
8517 auto IsAllowedValueType = [&](QualType ValType,
8518 unsigned AllowedType) -> bool {
8519 if (ValType->isIntegerType())
8520 return true;
8521 if (ValType->isPointerType())
8522 return AllowedType & AOEVT_Pointer;
8523 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
8524 return false;
8525 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
8526 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
8528 &llvm::APFloat::x87DoubleExtended())
8529 return false;
8530 return true;
8531 };
8532 if (!IsAllowedValueType(ValType, ArithAllows)) {
8533 auto DID = ArithAllows & AOEVT_FP
8534 ? (ArithAllows & AOEVT_Pointer
8535 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
8536 : diag::err_atomic_op_needs_atomic_int_or_fp)
8537 : diag::err_atomic_op_needs_atomic_int;
8538 Diag(ExprRange.getBegin(), DID)
8539 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
8540 return ExprError();
8541 }
8542 if (IsC11 && ValType->isPointerType() &&
8544 diag::err_incomplete_type)) {
8545 return ExprError();
8546 }
8547 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
8548 // For __atomic_*_n operations, the value type must be a scalar integral or
8549 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
8550 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
8551 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
8552 return ExprError();
8553 }
8554
8555 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
8556 !AtomTy->isScalarType()) {
8557 // For GNU atomics, require a trivially-copyable type. This is not part of
8558 // the GNU atomics specification but we enforce it for consistency with
8559 // other atomics which generally all require a trivially-copyable type. This
8560 // is because atomics just copy bits.
8561 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
8562 << Ptr->getType() << Ptr->getSourceRange();
8563 return ExprError();
8564 }
8565
8566 switch (ValType.getObjCLifetime()) {
8569 // okay
8570 break;
8571
8575 // FIXME: Can this happen? By this point, ValType should be known
8576 // to be trivially copyable.
8577 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
8578 << ValType << Ptr->getSourceRange();
8579 return ExprError();
8580 }
8581
8582 // All atomic operations have an overload which takes a pointer to a volatile
8583 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
8584 // into the result or the other operands. Similarly atomic_load takes a
8585 // pointer to a const 'A'.
8586 ValType.removeLocalVolatile();
8587 ValType.removeLocalConst();
8588 QualType ResultType = ValType;
8589 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
8590 Form == Init)
8591 ResultType = Context.VoidTy;
8592 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
8593 ResultType = Context.BoolTy;
8594
8595 // The type of a parameter passed 'by value'. In the GNU atomics, such
8596 // arguments are actually passed as pointers.
8597 QualType ByValType = ValType; // 'CP'
8598 bool IsPassedByAddress = false;
8599 if (!IsC11 && !IsHIP && !IsN) {
8600 ByValType = Ptr->getType();
8601 IsPassedByAddress = true;
8602 }
8603
8604 SmallVector<Expr *, 5> APIOrderedArgs;
8605 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
8606 APIOrderedArgs.push_back(Args[0]);
8607 switch (Form) {
8608 case Init:
8609 case Load:
8610 APIOrderedArgs.push_back(Args[1]); // Val1/Order
8611 break;
8612 case LoadCopy:
8613 case Copy:
8614 case Arithmetic:
8615 case Xchg:
8616 APIOrderedArgs.push_back(Args[2]); // Val1
8617 APIOrderedArgs.push_back(Args[1]); // Order
8618 break;
8619 case GNUXchg:
8620 APIOrderedArgs.push_back(Args[2]); // Val1
8621 APIOrderedArgs.push_back(Args[3]); // Val2
8622 APIOrderedArgs.push_back(Args[1]); // Order
8623 break;
8624 case C11CmpXchg:
8625 APIOrderedArgs.push_back(Args[2]); // Val1
8626 APIOrderedArgs.push_back(Args[4]); // Val2
8627 APIOrderedArgs.push_back(Args[1]); // Order
8628 APIOrderedArgs.push_back(Args[3]); // OrderFail
8629 break;
8630 case GNUCmpXchg:
8631 APIOrderedArgs.push_back(Args[2]); // Val1
8632 APIOrderedArgs.push_back(Args[4]); // Val2
8633 APIOrderedArgs.push_back(Args[5]); // Weak
8634 APIOrderedArgs.push_back(Args[1]); // Order
8635 APIOrderedArgs.push_back(Args[3]); // OrderFail
8636 break;
8637 }
8638 } else
8639 APIOrderedArgs.append(Args.begin(), Args.end());
8640
8641 // The first argument's non-CV pointer type is used to deduce the type of
8642 // subsequent arguments, except for:
8643 // - weak flag (always converted to bool)
8644 // - memory order (always converted to int)
8645 // - scope (always converted to int)
8646 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
8647 QualType Ty;
8648 if (i < NumVals[Form] + 1) {
8649 switch (i) {
8650 case 0:
8651 // The first argument is always a pointer. It has a fixed type.
8652 // It is always dereferenced, a nullptr is undefined.
8653 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
8654 // Nothing else to do: we already know all we want about this pointer.
8655 continue;
8656 case 1:
8657 // The second argument is the non-atomic operand. For arithmetic, this
8658 // is always passed by value, and for a compare_exchange it is always
8659 // passed by address. For the rest, GNU uses by-address and C11 uses
8660 // by-value.
8661 assert(Form != Load);
8662 if (Form == Arithmetic && ValType->isPointerType())
8664 else if (Form == Init || Form == Arithmetic)
8665 Ty = ValType;
8666 else if (Form == Copy || Form == Xchg) {
8667 if (IsPassedByAddress) {
8668 // The value pointer is always dereferenced, a nullptr is undefined.
8669 CheckNonNullArgument(*this, APIOrderedArgs[i],
8670 ExprRange.getBegin());
8671 }
8672 Ty = ByValType;
8673 } else {
8674 Expr *ValArg = APIOrderedArgs[i];
8675 // The value pointer is always dereferenced, a nullptr is undefined.
8676 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
8678 // Keep address space of non-atomic pointer type.
8679 if (const PointerType *PtrTy =
8680 ValArg->getType()->getAs<PointerType>()) {
8681 AS = PtrTy->getPointeeType().getAddressSpace();
8682 }
8685 }
8686 break;
8687 case 2:
8688 // The third argument to compare_exchange / GNU exchange is the desired
8689 // value, either by-value (for the C11 and *_n variant) or as a pointer.
8690 if (IsPassedByAddress)
8691 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
8692 Ty = ByValType;
8693 break;
8694 case 3:
8695 // The fourth argument to GNU compare_exchange is a 'weak' flag.
8696 Ty = Context.BoolTy;
8697 break;
8698 }
8699 } else {
8700 // The order(s) and scope are always converted to int.
8701 Ty = Context.IntTy;
8702 }
8703
8704 InitializedEntity Entity =
8706 ExprResult Arg = APIOrderedArgs[i];
8707 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
8708 if (Arg.isInvalid())
8709 return true;
8710 APIOrderedArgs[i] = Arg.get();
8711 }
8712
8713 // Permute the arguments into a 'consistent' order.
8714 SmallVector<Expr*, 5> SubExprs;
8715 SubExprs.push_back(Ptr);
8716 switch (Form) {
8717 case Init:
8718 // Note, AtomicExpr::getVal1() has a special case for this atomic.
8719 SubExprs.push_back(APIOrderedArgs[1]); // Val1
8720 break;
8721 case Load:
8722 SubExprs.push_back(APIOrderedArgs[1]); // Order
8723 break;
8724 case LoadCopy:
8725 case Copy:
8726 case Arithmetic:
8727 case Xchg:
8728 SubExprs.push_back(APIOrderedArgs[2]); // Order
8729 SubExprs.push_back(APIOrderedArgs[1]); // Val1
8730 break;
8731 case GNUXchg:
8732 // Note, AtomicExpr::getVal2() has a special case for this atomic.
8733 SubExprs.push_back(APIOrderedArgs[3]); // Order
8734 SubExprs.push_back(APIOrderedArgs[1]); // Val1
8735 SubExprs.push_back(APIOrderedArgs[2]); // Val2
8736 break;
8737 case C11CmpXchg:
8738 SubExprs.push_back(APIOrderedArgs[3]); // Order
8739 SubExprs.push_back(APIOrderedArgs[1]); // Val1
8740 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
8741 SubExprs.push_back(APIOrderedArgs[2]); // Val2
8742 break;
8743 case GNUCmpXchg:
8744 SubExprs.push_back(APIOrderedArgs[4]); // Order
8745 SubExprs.push_back(APIOrderedArgs[1]); // Val1
8746 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
8747 SubExprs.push_back(APIOrderedArgs[2]); // Val2
8748 SubExprs.push_back(APIOrderedArgs[3]); // Weak
8749 break;
8750 }
8751
8752 // If the memory orders are constants, check they are valid.
8753 if (SubExprs.size() >= 2 && Form != Init) {
8754 std::optional<llvm::APSInt> Success =
8755 SubExprs[1]->getIntegerConstantExpr(Context);
8756 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
8757 Diag(SubExprs[1]->getBeginLoc(),
8758 diag::warn_atomic_op_has_invalid_memory_order)
8759 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
8760 << SubExprs[1]->getSourceRange();
8761 }
8762 if (SubExprs.size() >= 5) {
8763 if (std::optional<llvm::APSInt> Failure =
8764 SubExprs[3]->getIntegerConstantExpr(Context)) {
8765 if (!llvm::is_contained(
8766 {llvm::AtomicOrderingCABI::relaxed,
8767 llvm::AtomicOrderingCABI::consume,
8768 llvm::AtomicOrderingCABI::acquire,
8769 llvm::AtomicOrderingCABI::seq_cst},
8770 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
8771 Diag(SubExprs[3]->getBeginLoc(),
8772 diag::warn_atomic_op_has_invalid_memory_order)
8773 << /*failure=*/2 << SubExprs[3]->getSourceRange();
8774 }
8775 }
8776 }
8777 }
8778
8779 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
8780 auto *Scope = Args[Args.size() - 1];
8781 if (std::optional<llvm::APSInt> Result =
8782 Scope->getIntegerConstantExpr(Context)) {
8783 if (!ScopeModel->isValid(Result->getZExtValue()))
8784 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
8785 << Scope->getSourceRange();
8786 }
8787 SubExprs.push_back(Scope);
8788 }
8789
8790 AtomicExpr *AE = new (Context)
8791 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
8792
8793 if ((Op == AtomicExpr::AO__c11_atomic_load ||
8794 Op == AtomicExpr::AO__c11_atomic_store ||
8795 Op == AtomicExpr::AO__opencl_atomic_load ||
8796 Op == AtomicExpr::AO__hip_atomic_load ||
8797 Op == AtomicExpr::AO__opencl_atomic_store ||
8798 Op == AtomicExpr::AO__hip_atomic_store) &&
8800 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
8801 << ((Op == AtomicExpr::AO__c11_atomic_load ||
8802 Op == AtomicExpr::AO__opencl_atomic_load ||
8803 Op == AtomicExpr::AO__hip_atomic_load)
8804 ? 0
8805 : 1);
8806
8807 if (ValType->isBitIntType()) {
8808 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
8809 return ExprError();
8810 }
8811
8812 return AE;
8813}
8814
8815/// checkBuiltinArgument - Given a call to a builtin function, perform
8816/// normal type-checking on the given argument, updating the call in
8817/// place. This is useful when a builtin function requires custom
8818/// type-checking for some of its arguments but not necessarily all of
8819/// them.
8820///
8821/// Returns true on error.
8822static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
8823 FunctionDecl *Fn = E->getDirectCallee();
8824 assert(Fn && "builtin call without direct callee!");
8825
8826 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
8827 InitializedEntity Entity =
8829
8830 ExprResult Arg = E->getArg(ArgIndex);
8831 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
8832 if (Arg.isInvalid())
8833 return true;
8834
8835 E->setArg(ArgIndex, Arg.get());
8836 return false;
8837}
8838
8839bool Sema::BuiltinWasmRefNullExtern(CallExpr *TheCall) {
8840 if (TheCall->getNumArgs() != 0)
8841 return true;
8842
8844
8845 return false;
8846}
8847
8848bool Sema::BuiltinWasmRefNullFunc(CallExpr *TheCall) {
8849 if (TheCall->getNumArgs() != 0) {
8850 Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_many_args)
8851 << 0 /*function call*/ << /*expected*/ 0 << TheCall->getNumArgs()
8852 << /*is non object*/ 0;
8853 return true;
8854 }
8855
8856 // This custom type checking code ensures that the nodes are as expected
8857 // in order to later on generate the necessary builtin.
8858 QualType Pointee = Context.getFunctionType(Context.VoidTy, {}, {});
8861 Type = Context.getAttributedType(attr::WebAssemblyFuncref, Type,
8862 Context.getPointerType(Pointee));
8863 TheCall->setType(Type);
8864
8865 return false;
8866}
8867
8868/// We have a call to a function like __sync_fetch_and_add, which is an
8869/// overloaded function based on the pointer type of its first argument.
8870/// The main BuildCallExpr routines have already promoted the types of
8871/// arguments because all of these calls are prototyped as void(...).
8872///
8873/// This function goes through and does final semantic checking for these
8874/// builtins, as well as generating any warnings.
8875ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
8876 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
8877 Expr *Callee = TheCall->getCallee();
8878 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
8879 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
8880
8881 // Ensure that we have at least one argument to do type inference from.
8882 if (TheCall->getNumArgs() < 1) {
8883 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
8884 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
8885 << Callee->getSourceRange();
8886 return ExprError();
8887 }
8888
8889 // Inspect the first argument of the atomic builtin. This should always be
8890 // a pointer type, whose element is an integral scalar or pointer type.
8891 // Because it is a pointer type, we don't have to worry about any implicit
8892 // casts here.
8893 // FIXME: We don't allow floating point scalars as input.
8894 Expr *FirstArg = TheCall->getArg(0);
8895 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
8896 if (FirstArgResult.isInvalid())
8897 return ExprError();
8898 FirstArg = FirstArgResult.get();
8899 TheCall->setArg(0, FirstArg);
8900
8901 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
8902 if (!pointerType) {
8903 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
8904 << FirstArg->getType() << FirstArg->getSourceRange();
8905 return ExprError();
8906 }
8907
8908 QualType ValType = pointerType->getPointeeType();
8909 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
8910 !ValType->isBlockPointerType()) {
8911 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
8912 << FirstArg->getType() << FirstArg->getSourceRange();
8913 return ExprError();
8914 }
8915
8916 if (ValType.isConstQualified()) {
8917 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
8918 << FirstArg->getType() << FirstArg->getSourceRange();
8919 return ExprError();
8920 }
8921
8922 switch (ValType.getObjCLifetime()) {
8925 // okay
8926 break;
8927
8931 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
8932 << ValType << FirstArg->getSourceRange();
8933 return ExprError();
8934 }
8935
8936 // Strip any qualifiers off ValType.
8937 ValType = ValType.getUnqualifiedType();
8938
8939 // The majority of builtins return a value, but a few have special return
8940 // types, so allow them to override appropriately below.
8941 QualType ResultType = ValType;
8942
8943 // We need to figure out which concrete builtin this maps onto. For example,
8944 // __sync_fetch_and_add with a 2 byte object turns into
8945 // __sync_fetch_and_add_2.
8946#define BUILTIN_ROW(x) \
8947 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
8948 Builtin::BI##x##_8, Builtin::BI##x##_16 }
8949
8950 static const unsigned BuiltinIndices[][5] = {
8951 BUILTIN_ROW(__sync_fetch_and_add),
8952 BUILTIN_ROW(__sync_fetch_and_sub),
8953 BUILTIN_ROW(__sync_fetch_and_or),
8954 BUILTIN_ROW(__sync_fetch_and_and),
8955 BUILTIN_ROW(__sync_fetch_and_xor),
8956 BUILTIN_ROW(__sync_fetch_and_nand),
8957
8958 BUILTIN_ROW(__sync_add_and_fetch),
8959 BUILTIN_ROW(__sync_sub_and_fetch),
8960 BUILTIN_ROW(__sync_and_and_fetch),
8961 BUILTIN_ROW(__sync_or_and_fetch),
8962 BUILTIN_ROW(__sync_xor_and_fetch),
8963 BUILTIN_ROW(__sync_nand_and_fetch),
8964
8965 BUILTIN_ROW(__sync_val_compare_and_swap),
8966 BUILTIN_ROW(__sync_bool_compare_and_swap),
8967 BUILTIN_ROW(__sync_lock_test_and_set),
8968 BUILTIN_ROW(__sync_lock_release),
8969 BUILTIN_ROW(__sync_swap)
8970 };
8971#undef BUILTIN_ROW
8972
8973 // Determine the index of the size.
8974 unsigned SizeIndex;
8975 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
8976 case 1: SizeIndex = 0; break;
8977 case 2: SizeIndex = 1; break;
8978 case 4: SizeIndex = 2; break;
8979 case 8: SizeIndex = 3; break;
8980 case 16: SizeIndex = 4; break;
8981 default:
8982 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
8983 << FirstArg->getType() << FirstArg->getSourceRange();
8984 return ExprError();
8985 }
8986
8987 // Each of these builtins has one pointer argument, followed by some number of
8988 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
8989 // that we ignore. Find out which row of BuiltinIndices to read from as well
8990 // as the number of fixed args.
8991 unsigned BuiltinID = FDecl->getBuiltinID();
8992 unsigned BuiltinIndex, NumFixed = 1;
8993 bool WarnAboutSemanticsChange = false;
8994 switch (BuiltinID) {
8995 default: llvm_unreachable("Unknown overloaded atomic builtin!");
8996 case Builtin::BI__sync_fetch_and_add:
8997 case Builtin::BI__sync_fetch_and_add_1:
8998 case Builtin::BI__sync_fetch_and_add_2:
8999 case Builtin::BI__sync_fetch_and_add_4:
9000 case Builtin::BI__sync_fetch_and_add_8:
9001 case Builtin::BI__sync_fetch_and_add_16:
9002 BuiltinIndex = 0;
9003 break;
9004
9005 case Builtin::BI__sync_fetch_and_sub:
9006 case Builtin::BI__sync_fetch_and_sub_1:
9007 case Builtin::BI__sync_fetch_and_sub_2:
9008 case Builtin::BI__sync_fetch_and_sub_4:
9009 case Builtin::BI__sync_fetch_and_sub_8:
9010 case Builtin::BI__sync_fetch_and_sub_16:
9011 BuiltinIndex = 1;
9012 break;
9013
9014 case Builtin::BI__sync_fetch_and_or:
9015 case Builtin::BI__sync_fetch_and_or_1:
9016 case Builtin::BI__sync_fetch_and_or_2:
9017 case Builtin::BI__sync_fetch_and_or_4:
9018 case Builtin::BI__sync_fetch_and_or_8:
9019 case Builtin::BI__sync_fetch_and_or_16:
9020 BuiltinIndex = 2;
9021 break;
9022
9023 case Builtin::BI__sync_fetch_and_and:
9024 case Builtin::BI__sync_fetch_and_and_1:
9025 case Builtin::BI__sync_fetch_and_and_2:
9026 case Builtin::BI__sync_fetch_and_and_4:
9027 case Builtin::BI__sync_fetch_and_and_8:
9028 case Builtin::BI__sync_fetch_and_and_16:
9029 BuiltinIndex = 3;
9030 break;
9031
9032 case Builtin::BI__sync_fetch_and_xor:
9033 case Builtin::BI__sync_fetch_and_xor_1:
9034 case Builtin::BI__sync_fetch_and_xor_2:
9035 case Builtin::BI__sync_fetch_and_xor_4:
9036 case Builtin::BI__sync_fetch_and_xor_8:
9037 case Builtin::BI__sync_fetch_and_xor_16:
9038 BuiltinIndex = 4;
9039 break;
9040
9041 case Builtin::BI__sync_fetch_and_nand:
9042 case Builtin::BI__sync_fetch_and_nand_1:
9043 case Builtin::BI__sync_fetch_and_nand_2:
9044 case Builtin::BI__sync_fetch_and_nand_4:
9045 case Builtin::BI__sync_fetch_and_nand_8:
9046 case Builtin::BI__sync_fetch_and_nand_16:
9047 BuiltinIndex = 5;
9048 WarnAboutSemanticsChange = true;
9049 break;
9050
9051 case Builtin::BI__sync_add_and_fetch:
9052 case Builtin::BI__sync_add_and_fetch_1:
9053 case Builtin::BI__sync_add_and_fetch_2:
9054 case Builtin::BI__sync_add_and_fetch_4:
9055 case Builtin::BI__sync_add_and_fetch_8:
9056 case Builtin::BI__sync_add_and_fetch_16:
9057 BuiltinIndex = 6;
9058 break;
9059
9060 case Builtin::BI__sync_sub_and_fetch:
9061 case Builtin::BI__sync_sub_and_fetch_1:
9062 case Builtin::BI__sync_sub_and_fetch_2:
9063 case Builtin::BI__sync_sub_and_fetch_4:
9064 case Builtin::BI__sync_sub_and_fetch_8:
9065 case Builtin::BI__sync_sub_and_fetch_16:
9066 BuiltinIndex = 7;
9067 break;
9068
9069 case Builtin::BI__sync_and_and_fetch:
9070 case Builtin::BI__sync_and_and_fetch_1:
9071 case Builtin::BI__sync_and_and_fetch_2:
9072 case Builtin::BI__sync_and_and_fetch_4:
9073 case Builtin::BI__sync_and_and_fetch_8:
9074 case Builtin::BI__sync_and_and_fetch_16:
9075 BuiltinIndex = 8;
9076 break;
9077
9078 case Builtin::BI__sync_or_and_fetch:
9079 case Builtin::BI__sync_or_and_fetch_1:
9080 case Builtin::BI__sync_or_and_fetch_2:
9081 case Builtin::BI__sync_or_and_fetch_4:
9082 case Builtin::BI__sync_or_and_fetch_8:
9083 case Builtin::BI__sync_or_and_fetch_16:
9084 BuiltinIndex = 9;
9085 break;
9086
9087 case Builtin::BI__sync_xor_and_fetch:
9088 case Builtin::BI__sync_xor_and_fetch_1:
9089 case Builtin::BI__sync_xor_and_fetch_2:
9090 case Builtin::BI__sync_xor_and_fetch_4:
9091 case Builtin::BI__sync_xor_and_fetch_8:
9092 case Builtin::BI__sync_xor_and_fetch_16:
9093 BuiltinIndex = 10;
9094 break;
9095
9096 case Builtin::BI__sync_nand_and_fetch:
9097 case Builtin::BI__sync_nand_and_fetch_1:
9098 case Builtin::BI__sync_nand_and_fetch_2:
9099 case Builtin::BI__sync_nand_and_fetch_4:
9100 case Builtin::BI__sync_nand_and_fetch_8:
9101 case Builtin::BI__sync_nand_and_fetch_16:
9102 BuiltinIndex = 11;
9103 WarnAboutSemanticsChange = true;
9104 break;
9105
9106 case Builtin::BI__sync_val_compare_and_swap:
9107 case Builtin::BI__sync_val_compare_and_swap_1:
9108 case Builtin::BI__sync_val_compare_and_swap_2:
9109 case Builtin::BI__sync_val_compare_and_swap_4:
9110 case Builtin::BI__sync_val_compare_and_swap_8:
9111 case Builtin::BI__sync_val_compare_and_swap_16:
9112 BuiltinIndex = 12;
9113 NumFixed = 2;
9114 break;
9115
9116 case Builtin::BI__sync_bool_compare_and_swap:
9117 case Builtin::BI__sync_bool_compare_and_swap_1:
9118 case Builtin::BI__sync_bool_compare_and_swap_2:
9119 case Builtin::BI__sync_bool_compare_and_swap_4:
9120 case Builtin::BI__sync_bool_compare_and_swap_8:
9121 case Builtin::BI__sync_bool_compare_and_swap_16:
9122 BuiltinIndex = 13;
9123 NumFixed = 2;
9124 ResultType = Context.BoolTy;
9125 break;
9126
9127 case Builtin::BI__sync_lock_test_and_set:
9128 case Builtin::BI__sync_lock_test_and_set_1:
9129 case Builtin::BI__sync_lock_test_and_set_2:
9130 case Builtin::BI__sync_lock_test_and_set_4:
9131 case Builtin::BI__sync_lock_test_and_set_8:
9132 case Builtin::BI__sync_lock_test_and_set_16:
9133 BuiltinIndex = 14;
9134 break;
9135
9136 case Builtin::BI__sync_lock_release:
9137 case Builtin::BI__sync_lock_release_1:
9138 case Builtin::BI__sync_lock_release_2:
9139 case Builtin::BI__sync_lock_release_4:
9140 case Builtin::BI__sync_lock_release_8:
9141 case Builtin::BI__sync_lock_release_16:
9142 BuiltinIndex = 15;
9143 NumFixed = 0;
9144 ResultType = Context.VoidTy;
9145 break;
9146
9147 case Builtin::BI__sync_swap:
9148 case Builtin::BI__sync_swap_1:
9149 case Builtin::BI__sync_swap_2:
9150 case Builtin::BI__sync_swap_4:
9151 case Builtin::BI__sync_swap_8:
9152 case Builtin::BI__sync_swap_16:
9153 BuiltinIndex = 16;
9154 break;
9155 }
9156
9157 // Now that we know how many fixed arguments we expect, first check that we
9158 // have at least that many.
9159 if (TheCall->getNumArgs() < 1+NumFixed) {
9160 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
9161 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
9162 << Callee->getSourceRange();
9163 return ExprError();
9164 }
9165
9166 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
9167 << Callee->getSourceRange();
9168
9169 if (WarnAboutSemanticsChange) {
9170 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
9171 << Callee->getSourceRange();
9172 }
9173
9174 // Get the decl for the concrete builtin from this, we can tell what the
9175 // concrete integer type we should convert to is.
9176 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
9177 StringRef NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
9178 FunctionDecl *NewBuiltinDecl;
9179 if (NewBuiltinID == BuiltinID)
9180 NewBuiltinDecl = FDecl;
9181 else {
9182 // Perform builtin lookup to avoid redeclaring it.
9183 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
9184 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
9185 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
9186 assert(Res.getFoundDecl());
9187 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
9188 if (!NewBuiltinDecl)
9189 return ExprError();
9190 }
9191
9192 // The first argument --- the pointer --- has a fixed type; we
9193 // deduce the types of the rest of the arguments accordingly. Walk
9194 // the remaining arguments, converting them to the deduced value type.
9195 for (unsigned i = 0; i != NumFixed; ++i) {
9196 ExprResult Arg = TheCall->getArg(i+1);
9197
9198 // GCC does an implicit conversion to the pointer or integer ValType. This
9199 // can fail in some cases (1i -> int**), check for this error case now.
9200 // Initialize the argument.
9202 ValType, /*consume*/ false);
9203 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
9204 if (Arg.isInvalid())
9205 return ExprError();
9206
9207 // Okay, we have something that *can* be converted to the right type. Check
9208 // to see if there is a potentially weird extension going on here. This can
9209 // happen when you do an atomic operation on something like an char* and
9210 // pass in 42. The 42 gets converted to char. This is even more strange
9211 // for things like 45.123 -> char, etc.
9212 // FIXME: Do this check.
9213 TheCall->setArg(i+1, Arg.get());
9214 }
9215
9216 // Create a new DeclRefExpr to refer to the new decl.
9218 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
9219 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
9220 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
9221
9222 // Set the callee in the CallExpr.
9223 // FIXME: This loses syntactic information.
9224 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
9225 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
9226 CK_BuiltinFnToFnPtr);
9227 TheCall->setCallee(PromotedCall.get());
9228
9229 // Change the result type of the call to match the original value type. This
9230 // is arbitrary, but the codegen for these builtins ins design to handle it
9231 // gracefully.
9232 TheCall->setType(ResultType);
9233
9234 // Prohibit problematic uses of bit-precise integer types with atomic
9235 // builtins. The arguments would have already been converted to the first
9236 // argument's type, so only need to check the first argument.
9237 const auto *BitIntValType = ValType->getAs<BitIntType>();
9238 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
9239 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
9240 return ExprError();
9241 }
9242
9243 return TheCallResult;
9244}
9245
9246/// BuiltinNontemporalOverloaded - We have a call to
9247/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
9248/// overloaded function based on the pointer type of its last argument.
9249///
9250/// This function goes through and does final semantic checking for these
9251/// builtins.
9252ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
9253 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
9254 DeclRefExpr *DRE =
9255 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
9256 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
9257 unsigned BuiltinID = FDecl->getBuiltinID();
9258 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
9259 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
9260 "Unexpected nontemporal load/store builtin!");
9261 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
9262 unsigned numArgs = isStore ? 2 : 1;
9263
9264 // Ensure that we have the proper number of arguments.
9265 if (checkArgCount(*this, TheCall, numArgs))
9266 return ExprError();
9267
9268 // Inspect the last argument of the nontemporal builtin. This should always
9269 // be a pointer type, from which we imply the type of the memory access.
9270 // Because it is a pointer type, we don't have to worry about any implicit
9271 // casts here.
9272 Expr *PointerArg = TheCall->getArg(numArgs - 1);
9273 ExprResult PointerArgResult =
9275
9276 if (PointerArgResult.isInvalid())
9277 return ExprError();
9278 PointerArg = PointerArgResult.get();
9279 TheCall->setArg(numArgs - 1, PointerArg);
9280
9281 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
9282 if (!pointerType) {
9283 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
9284 << PointerArg->getType() << PointerArg->getSourceRange();
9285 return ExprError();
9286 }
9287
9288 QualType ValType = pointerType->getPointeeType();
9289
9290 // Strip any qualifiers off ValType.
9291 ValType = ValType.getUnqualifiedType();
9292 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
9293 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
9294 !ValType->isVectorType()) {
9295 Diag(DRE->getBeginLoc(),
9296 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
9297 << PointerArg->getType() << PointerArg->getSourceRange();
9298 return ExprError();
9299 }
9300
9301 if (!isStore) {
9302 TheCall->setType(ValType);
9303 return TheCallResult;
9304 }
9305
9306 ExprResult ValArg = TheCall->getArg(0);
9308 Context, ValType, /*consume*/ false);
9309 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
9310 if (ValArg.isInvalid())
9311 return ExprError();
9312
9313 TheCall->setArg(0, ValArg.get());
9314 TheCall->setType(Context.VoidTy);
9315 return TheCallResult;
9316}
9317
9318/// CheckObjCString - Checks that the argument to the builtin
9319/// CFString constructor is correct
9320/// Note: It might also make sense to do the UTF-16 conversion here (would
9321/// simplify the backend).
9322bool Sema::CheckObjCString(Expr *Arg) {
9323 Arg = Arg->IgnoreParenCasts();
9324 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
9325
9326 if (!Literal || !Literal->isOrdinary()) {
9327 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
9328 << Arg->getSourceRange();
9329 return true;
9330 }
9331
9332 if (Literal->containsNonAsciiOrNull()) {
9333 StringRef String = Literal->getString();
9334 unsigned NumBytes = String.size();
9335 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
9336 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
9337 llvm::UTF16 *ToPtr = &ToBuf[0];
9338
9339 llvm::ConversionResult Result =
9340 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
9341 ToPtr + NumBytes, llvm::strictConversion);
9342 // Check for conversion failure.
9343 if (Result != llvm::conversionOK)
9344 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
9345 << Arg->getSourceRange();
9346 }
9347 return false;
9348}
9349
9350/// CheckObjCString - Checks that the format string argument to the os_log()
9351/// and os_trace() functions is correct, and converts it to const char *.
9352ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
9353 Arg = Arg->IgnoreParenCasts();
9354 auto *Literal = dyn_cast<StringLiteral>(Arg);
9355 if (!Literal) {
9356 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
9357 Literal = ObjcLiteral->getString();
9358 }
9359 }
9360
9361 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
9362 return ExprError(
9363 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
9364 << Arg->getSourceRange());
9365 }
9366
9367 ExprResult Result(Literal);
9369 InitializedEntity Entity =
9372 return Result;
9373}
9374
9375/// Check that the user is calling the appropriate va_start builtin for the
9376/// target and calling convention.
9377static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
9378 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
9379 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
9380 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
9381 TT.getArch() == llvm::Triple::aarch64_32);
9382 bool IsWindows = TT.isOSWindows();
9383 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
9384 if (IsX64 || IsAArch64) {
9385 CallingConv CC = CC_C;
9386 if (const FunctionDecl *FD = S.getCurFunctionDecl())
9387 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
9388 if (IsMSVAStart) {
9389 // Don't allow this in System V ABI functions.
9390 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
9391 return S.Diag(Fn->getBeginLoc(),
9392 diag::err_ms_va_start_used_in_sysv_function);
9393 } else {
9394 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
9395 // On x64 Windows, don't allow this in System V ABI functions.
9396 // (Yes, that means there's no corresponding way to support variadic
9397 // System V ABI functions on Windows.)
9398 if ((IsWindows && CC == CC_X86_64SysV) ||
9399 (!IsWindows && CC == CC_Win64))
9400 return S.Diag(Fn->getBeginLoc(),
9401 diag::err_va_start_used_in_wrong_abi_function)
9402 << !IsWindows;
9403 }
9404 return false;
9405 }
9406
9407 if (IsMSVAStart)
9408 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
9409 return false;
9410}
9411
9413 ParmVarDecl **LastParam = nullptr) {
9414 // Determine whether the current function, block, or obj-c method is variadic
9415 // and get its parameter list.
9416 bool IsVariadic = false;
9418 DeclContext *Caller = S.CurContext;
9419 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
9420 IsVariadic = Block->isVariadic();
9421 Params = Block->parameters();
9422 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
9423 IsVariadic = FD->isVariadic();
9424 Params = FD->parameters();
9425 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
9426 IsVariadic = MD->isVariadic();
9427 // FIXME: This isn't correct for methods (results in bogus warning).
9428 Params = MD->parameters();
9429 } else if (isa<CapturedDecl>(Caller)) {
9430 // We don't support va_start in a CapturedDecl.
9431 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
9432 return true;
9433 } else {
9434 // This must be some other declcontext that parses exprs.
9435 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
9436 return true;
9437 }
9438
9439 if (!IsVariadic) {
9440 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
9441 return true;
9442 }
9443
9444 if (LastParam)
9445 *LastParam = Params.empty() ? nullptr : Params.back();
9446
9447 return false;
9448}
9449
9450/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
9451/// for validity. Emit an error and return true on failure; return false
9452/// on success.
9453bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
9454 Expr *Fn = TheCall->getCallee();
9455
9456 if (checkVAStartABI(*this, BuiltinID, Fn))
9457 return true;
9458
9459 // In C23 mode, va_start only needs one argument. However, the builtin still
9460 // requires two arguments (which matches the behavior of the GCC builtin),
9461 // <stdarg.h> passes `0` as the second argument in C23 mode.
9462 if (checkArgCount(*this, TheCall, 2))
9463 return true;
9464
9465 // Type-check the first argument normally.
9466 if (checkBuiltinArgument(*this, TheCall, 0))
9467 return true;
9468
9469 // Check that the current function is variadic, and get its last parameter.
9470 ParmVarDecl *LastParam;
9471 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
9472 return true;
9473
9474 // Verify that the second argument to the builtin is the last argument of the
9475 // current function or method. In C23 mode, if the second argument is an
9476 // integer constant expression with value 0, then we don't bother with this
9477 // check.
9478 bool SecondArgIsLastNamedArgument = false;
9479 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
9480 if (std::optional<llvm::APSInt> Val =
9482 Val && LangOpts.C23 && *Val == 0)
9483 return false;
9484
9485 // These are valid if SecondArgIsLastNamedArgument is false after the next
9486 // block.
9487 QualType Type;
9488 SourceLocation ParamLoc;
9489 bool IsCRegister = false;
9490
9491 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
9492 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
9493 SecondArgIsLastNamedArgument = PV == LastParam;
9494
9495 Type = PV->getType();
9496 ParamLoc = PV->getLocation();
9497 IsCRegister =
9498 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
9499 }
9500 }
9501
9502 if (!SecondArgIsLastNamedArgument)
9503 Diag(TheCall->getArg(1)->getBeginLoc(),
9504 diag::warn_second_arg_of_va_start_not_last_named_param);
9505 else if (IsCRegister || Type->isReferenceType() ||
9506 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
9507 // Promotable integers are UB, but enumerations need a bit of
9508 // extra checking to see what their promotable type actually is.
9509 if (!Context.isPromotableIntegerType(Type))
9510 return false;
9511 if (!Type->isEnumeralType())
9512 return true;
9513 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
9514 return !(ED &&
9515 Context.typesAreCompatible(ED->getPromotionType(), Type));
9516 }()) {
9517 unsigned Reason = 0;
9518 if (Type->isReferenceType()) Reason = 1;
9519 else if (IsCRegister) Reason = 2;
9520 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
9521 Diag(ParamLoc, diag::note_parameter_type) << Type;
9522 }
9523
9524 return false;
9525}
9526
9527bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
9528 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
9529 const LangOptions &LO = getLangOpts();
9530
9531 if (LO.CPlusPlus)
9532 return Arg->getType()
9534 .getTypePtr()
9535 ->getPointeeType()
9537
9538 // In C, allow aliasing through `char *`, this is required for AArch64 at
9539 // least.
9540 return true;
9541 };
9542
9543 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
9544 // const char *named_addr);
9545
9546 Expr *Func = Call->getCallee();
9547
9548 if (Call->getNumArgs() < 3)
9549 return Diag(Call->getEndLoc(),
9550 diag::err_typecheck_call_too_few_args_at_least)
9551 << 0 /*function call*/ << 3 << Call->getNumArgs()
9552 << /*is non object*/ 0;
9553
9554 // Type-check the first argument normally.
9555 if (checkBuiltinArgument(*this, Call, 0))
9556 return true;
9557
9558 // Check that the current function is variadic.
9560 return true;
9561
9562 // __va_start on Windows does not validate the parameter qualifiers
9563
9564 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
9565 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
9566
9567 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
9568 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
9569
9570 const QualType &ConstCharPtrTy =
9572 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
9573 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
9574 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
9575 << 0 /* qualifier difference */
9576 << 3 /* parameter mismatch */
9577 << 2 << Arg1->getType() << ConstCharPtrTy;
9578
9579 const QualType SizeTy = Context.getSizeType();
9580 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
9581 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
9582 << Arg2->getType() << SizeTy << 1 /* different class */
9583 << 0 /* qualifier difference */
9584 << 3 /* parameter mismatch */
9585 << 3 << Arg2->getType() << SizeTy;
9586
9587 return false;
9588}
9589
9590/// BuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
9591/// friends. This is declared to take (...), so we have to check everything.
9592bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
9593 if (checkArgCount(*this, TheCall, 2))
9594 return true;
9595
9596 if (BuiltinID == Builtin::BI__builtin_isunordered &&
9597 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
9598 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9599 << 1 << 0 << TheCall->getSourceRange();
9600
9601 ExprResult OrigArg0 = TheCall->getArg(0);
9602 ExprResult OrigArg1 = TheCall->getArg(1);
9603
9604 // Do standard promotions between the two arguments, returning their common
9605 // type.
9607 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
9608 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
9609 return true;
9610
9611 // Make sure any conversions are pushed back into the call; this is
9612 // type safe since unordered compare builtins are declared as "_Bool
9613 // foo(...)".
9614 TheCall->setArg(0, OrigArg0.get());
9615 TheCall->setArg(1, OrigArg1.get());
9616
9617 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
9618 return false;
9619
9620 // If the common type isn't a real floating type, then the arguments were
9621 // invalid for this operation.
9622 if (Res.isNull() || !Res->isRealFloatingType())
9623 return Diag(OrigArg0.get()->getBeginLoc(),
9624 diag::err_typecheck_call_invalid_ordered_compare)
9625 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
9626 << SourceRange(OrigArg0.get()->getBeginLoc(),
9627 OrigArg1.get()->getEndLoc());
9628
9629 return false;
9630}
9631
9632/// BuiltinSemaBuiltinFPClassification - Handle functions like
9633/// __builtin_isnan and friends. This is declared to take (...), so we have
9634/// to check everything.
9635bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
9636 unsigned BuiltinID) {
9637 if (checkArgCount(*this, TheCall, NumArgs))
9638 return true;
9639
9641 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
9642 BuiltinID == Builtin::BI__builtin_isinf ||
9643 BuiltinID == Builtin::BI__builtin_isinf_sign))
9644 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9645 << 0 << 0 << TheCall->getSourceRange();
9646
9647 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
9648 BuiltinID == Builtin::BI__builtin_isunordered))
9649 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9650 << 1 << 0 << TheCall->getSourceRange();
9651
9652 bool IsFPClass = NumArgs == 2;
9653
9654 // Find out position of floating-point argument.
9655 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
9656
9657 // We can count on all parameters preceding the floating-point just being int.
9658 // Try all of those.
9659 for (unsigned i = 0; i < FPArgNo; ++i) {
9660 Expr *Arg = TheCall->getArg(i);
9661
9662 if (Arg->isTypeDependent())
9663 return false;
9664
9666
9667 if (Res.isInvalid())
9668 return true;
9669 TheCall->setArg(i, Res.get());
9670 }
9671
9672 Expr *OrigArg = TheCall->getArg(FPArgNo);
9673
9674 if (OrigArg->isTypeDependent())
9675 return false;
9676
9677 // Usual Unary Conversions will convert half to float, which we want for
9678 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
9679 // type how it is, but do normal L->Rvalue conversions.
9681 OrigArg = UsualUnaryConversions(OrigArg).get();
9682 else
9683 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
9684 TheCall->setArg(FPArgNo, OrigArg);
9685
9686 QualType VectorResultTy;
9687 QualType ElementTy = OrigArg->getType();
9688 // TODO: When all classification function are implemented with is_fpclass,
9689 // vector argument can be supported in all of them.
9690 if (ElementTy->isVectorType() && IsFPClass) {
9691 VectorResultTy = GetSignedVectorType(ElementTy);
9692 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
9693 }
9694
9695 // This operation requires a non-_Complex floating-point number.
9696 if (!ElementTy->isRealFloatingType())
9697 return Diag(OrigArg->getBeginLoc(),
9698 diag::err_typecheck_call_invalid_unary_fp)
9699 << OrigArg->getType() << OrigArg->getSourceRange();
9700
9701 // __builtin_isfpclass has integer parameter that specify test mask. It is
9702 // passed in (...), so it should be analyzed completely here.
9703 if (IsFPClass)
9704 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
9705 return true;
9706
9707 // TODO: enable this code to all classification functions.
9708 if (IsFPClass) {
9709 QualType ResultTy;
9710 if (!VectorResultTy.isNull())
9711 ResultTy = VectorResultTy;
9712 else
9713 ResultTy = Context.IntTy;
9714 TheCall->setType(ResultTy);
9715 }
9716
9717 return false;
9718}
9719
9720/// Perform semantic analysis for a call to __builtin_complex.
9721bool Sema::BuiltinComplex(CallExpr *TheCall) {
9722 if (checkArgCount(*this, TheCall, 2))
9723 return true;
9724
9725 bool Dependent = false;
9726 for (unsigned I = 0; I != 2; ++I) {
9727 Expr *Arg = TheCall->getArg(I);
9728 QualType T = Arg->getType();
9729 if (T->isDependentType()) {
9730 Dependent = true;
9731 continue;
9732 }
9733
9734 // Despite supporting _Complex int, GCC requires a real floating point type
9735 // for the operands of __builtin_complex.
9736 if (!T->isRealFloatingType()) {
9737 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
9738 << Arg->getType() << Arg->getSourceRange();
9739 }
9740
9741 ExprResult Converted = DefaultLvalueConversion(Arg);
9742 if (Converted.isInvalid())
9743 return true;
9744 TheCall->setArg(I, Converted.get());
9745 }
9746
9747 if (Dependent) {
9748 TheCall->setType(Context.DependentTy);
9749 return false;
9750 }
9751
9752 Expr *Real = TheCall->getArg(0);
9753 Expr *Imag = TheCall->getArg(1);
9754 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
9755 return Diag(Real->getBeginLoc(),
9756 diag::err_typecheck_call_different_arg_types)
9757 << Real->getType() << Imag->getType()
9758 << Real->getSourceRange() << Imag->getSourceRange();
9759 }
9760
9761 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
9762 // don't allow this builtin to form those types either.
9763 // FIXME: Should we allow these types?
9764 if (Real->getType()->isFloat16Type())
9765 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
9766 << "_Float16";
9767 if (Real->getType()->isHalfType())
9768 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
9769 << "half";
9770
9771 TheCall->setType(Context.getComplexType(Real->getType()));
9772 return false;
9773}
9774
9775// Customized Sema Checking for VSX builtins that have the following signature:
9776// vector [...] builtinName(vector [...], vector [...], const int);
9777// Which takes the same type of vectors (any legal vector type) for the first
9778// two arguments and takes compile time constant for the third argument.
9779// Example builtins are :
9780// vector double vec_xxpermdi(vector double, vector double, int);
9781// vector short vec_xxsldwi(vector short, vector short, int);
9782bool Sema::BuiltinVSX(CallExpr *TheCall) {
9783 unsigned ExpectedNumArgs = 3;
9784 if (checkArgCount(*this, TheCall, ExpectedNumArgs))
9785 return true;
9786
9787 // Check the third argument is a compile time constant
9788 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
9789 return Diag(TheCall->getBeginLoc(),
9790 diag::err_vsx_builtin_nonconstant_argument)
9791 << 3 /* argument index */ << TheCall->getDirectCallee()
9792 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
9793 TheCall->getArg(2)->getEndLoc());
9794
9795 QualType Arg1Ty = TheCall->getArg(0)->getType();
9796 QualType Arg2Ty = TheCall->getArg(1)->getType();
9797
9798 // Check the type of argument 1 and argument 2 are vectors.
9799 SourceLocation BuiltinLoc = TheCall->getBeginLoc();
9800 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
9801 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
9802 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
9803 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ false
9804 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
9805 TheCall->getArg(1)->getEndLoc());
9806 }
9807
9808 // Check the first two arguments are the same type.
9809 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
9810 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
9811 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ false
9812 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
9813 TheCall->getArg(1)->getEndLoc());
9814 }
9815
9816 // When default clang type checking is turned off and the customized type
9817 // checking is used, the returning type of the function must be explicitly
9818 // set. Otherwise it is _Bool by default.
9819 TheCall->setType(Arg1Ty);
9820
9821 return false;
9822}
9823
9824/// BuiltinShuffleVector - Handle __builtin_shufflevector.
9825// This is declared to take (...), so we have to check everything.
9827 if (TheCall->getNumArgs() < 2)
9828 return ExprError(Diag(TheCall->getEndLoc(),
9829 diag::err_typecheck_call_too_few_args_at_least)
9830 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
9831 << /*is non object*/ 0 << TheCall->getSourceRange());
9832
9833 // Determine which of the following types of shufflevector we're checking:
9834 // 1) unary, vector mask: (lhs, mask)
9835 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
9836 QualType resType = TheCall->getArg(0)->getType();
9837 unsigned numElements = 0;
9838
9839 if (!TheCall->getArg(0)->isTypeDependent() &&
9840 !TheCall->getArg(1)->isTypeDependent()) {
9841 QualType LHSType = TheCall->getArg(0)->getType();
9842 QualType RHSType = TheCall->getArg(1)->getType();
9843
9844 if (!LHSType->isVectorType() || !RHSType->isVectorType())
9845 return ExprError(
9846 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
9847 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ false
9848 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
9849 TheCall->getArg(1)->getEndLoc()));
9850
9851 numElements = LHSType->castAs<VectorType>()->getNumElements();
9852 unsigned numResElements = TheCall->getNumArgs() - 2;
9853
9854 // Check to see if we have a call with 2 vector arguments, the unary shuffle
9855 // with mask. If so, verify that RHS is an integer vector type with the
9856 // same number of elts as lhs.
9857 if (TheCall->getNumArgs() == 2) {
9858 if (!RHSType->hasIntegerRepresentation() ||
9859 RHSType->castAs<VectorType>()->getNumElements() != numElements)
9860 return ExprError(Diag(TheCall->getBeginLoc(),
9861 diag::err_vec_builtin_incompatible_vector)
9862 << TheCall->getDirectCallee()
9863 << /*isMorethantwoArgs*/ false
9864 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
9865 TheCall->getArg(1)->getEndLoc()));
9866 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
9867 return ExprError(Diag(TheCall->getBeginLoc(),
9868 diag::err_vec_builtin_incompatible_vector)
9869 << TheCall->getDirectCallee()
9870 << /*isMorethantwoArgs*/ false
9871 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
9872 TheCall->getArg(1)->getEndLoc()));
9873 } else if (numElements != numResElements) {
9874 QualType eltType = LHSType->castAs<VectorType>()->getElementType();
9875 resType =
9876 Context.getVectorType(eltType, numResElements, VectorKind::Generic);
9877 }
9878 }
9879
9880 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
9881 if (TheCall->getArg(i)->isTypeDependent() ||
9882 TheCall->getArg(i)->isValueDependent())
9883 continue;
9884
9885 std::optional<llvm::APSInt> Result;
9886 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
9887 return ExprError(Diag(TheCall->getBeginLoc(),
9888 diag::err_shufflevector_nonconstant_argument)
9889 << TheCall->getArg(i)->getSourceRange());
9890
9891 // Allow -1 which will be translated to undef in the IR.
9892 if (Result->isSigned() && Result->isAllOnes())
9893 continue;
9894
9895 if (Result->getActiveBits() > 64 ||
9896 Result->getZExtValue() >= numElements * 2)
9897 return ExprError(Diag(TheCall->getBeginLoc(),
9898 diag::err_shufflevector_argument_too_large)
9899 << TheCall->getArg(i)->getSourceRange());
9900 }
9901
9903
9904 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
9905 exprs.push_back(TheCall->getArg(i));
9906 TheCall->setArg(i, nullptr);
9907 }
9908
9909 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
9910 TheCall->getCallee()->getBeginLoc(),
9911 TheCall->getRParenLoc());
9912}
9913
9914/// ConvertVectorExpr - Handle __builtin_convertvector
9916 SourceLocation BuiltinLoc,
9917 SourceLocation RParenLoc) {
9920 QualType DstTy = TInfo->getType();
9921 QualType SrcTy = E->getType();
9922
9923 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
9924 return ExprError(Diag(BuiltinLoc,
9925 diag::err_convertvector_non_vector)
9926 << E->getSourceRange());
9927 if (!DstTy->isVectorType() && !DstTy->isDependentType())
9928 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
9929 << "second"
9930 << "__builtin_convertvector");
9931
9932 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
9933 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
9934 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
9935 if (SrcElts != DstElts)
9936 return ExprError(Diag(BuiltinLoc,
9937 diag::err_convertvector_incompatible_vector)
9938 << E->getSourceRange());
9939 }
9940
9941 return new (Context) class ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
9942 BuiltinLoc, RParenLoc);
9943}
9944
9945/// BuiltinPrefetch - Handle __builtin_prefetch.
9946// This is declared to take (const void*, ...) and can take two
9947// optional constant int args.
9948bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
9949 unsigned NumArgs = TheCall->getNumArgs();
9950
9951 if (NumArgs > 3)
9952 return Diag(TheCall->getEndLoc(),
9953 diag::err_typecheck_call_too_many_args_at_most)
9954 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
9955 << TheCall->getSourceRange();
9956
9957 // Argument 0 is checked for us and the remaining arguments must be
9958 // constant integers.
9959 for (unsigned i = 1; i != NumArgs; ++i)
9960 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
9961 return true;
9962
9963 return false;
9964}
9965
9966/// BuiltinArithmeticFence - Handle __arithmetic_fence.
9967bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
9969 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
9970 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
9971 if (checkArgCount(*this, TheCall, 1))
9972 return true;
9973 Expr *Arg = TheCall->getArg(0);
9974 if (Arg->isInstantiationDependent())
9975 return false;
9976
9977 QualType ArgTy = Arg->getType();
9978 if (!ArgTy->hasFloatingRepresentation())
9979 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
9980 << ArgTy;
9981 if (Arg->isLValue()) {
9982 ExprResult FirstArg = DefaultLvalueConversion(Arg);
9983 TheCall->setArg(0, FirstArg.get());
9984 }
9985 TheCall->setType(TheCall->getArg(0)->getType());
9986 return false;
9987}
9988
9989/// BuiltinAssume - Handle __assume (MS Extension).
9990// __assume does not evaluate its arguments, and should warn if its argument
9991// has side effects.
9992bool Sema::BuiltinAssume(CallExpr *TheCall) {
9993 Expr *Arg = TheCall->getArg(0);
9994 if (Arg->isInstantiationDependent()) return false;
9995
9996 if (Arg->HasSideEffects(Context))
9997 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
9998 << Arg->getSourceRange()
9999 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
10000
10001 return false;
10002}
10003
10004/// Handle __builtin_alloca_with_align. This is declared
10005/// as (size_t, size_t) where the second size_t must be a power of 2 greater
10006/// than 8.
10007bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
10008 // The alignment must be a constant integer.
10009 Expr *Arg = TheCall->getArg(1);
10010
10011 // We can't check the value of a dependent argument.
10012 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
10013 if (const auto *UE =
10014 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
10015 if (UE->getKind() == UETT_AlignOf ||
10016 UE->getKind() == UETT_PreferredAlignOf)
10017 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
10018 << Arg->getSourceRange();
10019
10020 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
10021
10022 if (!Result.isPowerOf2())
10023 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
10024 << Arg->getSourceRange();
10025
10026 if (Result < Context.getCharWidth())
10027 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
10029
10030 if (Result > std::numeric_limits<int32_t>::max())
10031 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
10032 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
10033 }
10034
10035 return false;
10036}
10037
10038/// Handle __builtin_assume_aligned. This is declared
10039/// as (const void*, size_t, ...) and can take one optional constant int arg.
10040bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
10041 if (checkArgCountRange(*this, TheCall, 2, 3))
10042 return true;
10043
10044 unsigned NumArgs = TheCall->getNumArgs();
10045 Expr *FirstArg = TheCall->getArg(0);
10046
10047 {
10048 ExprResult FirstArgResult =
10050 if (checkBuiltinArgument(*this, TheCall, 0))
10051 return true;
10052 /// In-place updation of FirstArg by checkBuiltinArgument is ignored.
10053 TheCall->setArg(0, FirstArgResult.get());
10054 }
10055
10056 // The alignment must be a constant integer.
10057 Expr *SecondArg = TheCall->getArg(1);
10058
10059 // We can't check the value of a dependent argument.
10060 if (!SecondArg->isValueDependent()) {
10061 llvm::APSInt Result;
10062 if (BuiltinConstantArg(TheCall, 1, Result))
10063 return true;
10064
10065 if (!Result.isPowerOf2())
10066 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
10067 << SecondArg->getSourceRange();
10068
10070 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
10071 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
10072 }
10073
10074 if (NumArgs > 2) {
10075 Expr *ThirdArg = TheCall->getArg(2);
10076 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
10077 return true;
10078 TheCall->setArg(2, ThirdArg);
10079 }
10080
10081 return false;
10082}
10083
10084bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
10085 unsigned BuiltinID =
10086 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
10087 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
10088
10089 unsigned NumArgs = TheCall->getNumArgs();
10090 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
10091 if (NumArgs < NumRequiredArgs) {
10092 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
10093 << 0 /* function call */ << NumRequiredArgs << NumArgs
10094 << /*is non object*/ 0 << TheCall->getSourceRange();
10095 }
10096 if (NumArgs >= NumRequiredArgs + 0x100) {
10097 return Diag(TheCall->getEndLoc(),
10098 diag::err_typecheck_call_too_many_args_at_most)
10099 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
10100 << /*is non object*/ 0 << TheCall->getSourceRange();
10101 }
10102 unsigned i = 0;
10103
10104 // For formatting call, check buffer arg.
10105 if (!IsSizeCall) {
10106 ExprResult Arg(TheCall->getArg(i));
10108 Context, Context.VoidPtrTy, false);
10109 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
10110 if (Arg.isInvalid())
10111 return true;
10112 TheCall->setArg(i, Arg.get());
10113 i++;
10114 }
10115
10116 // Check string literal arg.
10117 unsigned FormatIdx = i;
10118 {
10119 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
10120 if (Arg.isInvalid())
10121 return true;
10122 TheCall->setArg(i, Arg.get());
10123 i++;
10124 }
10125
10126 // Make sure variadic args are scalar.
10127 unsigned FirstDataArg = i;
10128 while (i < NumArgs) {
10130 TheCall->getArg(i), VariadicFunction, nullptr);
10131 if (Arg.isInvalid())
10132 return true;
10133 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
10134 if (ArgSize.getQuantity() >= 0x100) {
10135 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
10136 << i << (int)ArgSize.getQuantity() << 0xff
10137 << TheCall->getSourceRange();
10138 }
10139 TheCall->setArg(i, Arg.get());
10140 i++;
10141 }
10142
10143 // Check formatting specifiers. NOTE: We're only doing this for the non-size
10144 // call to avoid duplicate diagnostics.
10145 if (!IsSizeCall) {
10146 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
10147 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
10148 bool Success = CheckFormatArguments(
10149 Args, FAPK_Variadic, FormatIdx, FirstDataArg, FST_OSLog,
10151 CheckedVarArgs);
10152 if (!Success)
10153 return true;
10154 }
10155
10156 if (IsSizeCall) {
10157 TheCall->setType(Context.getSizeType());
10158 } else {
10159 TheCall->setType(Context.VoidPtrTy);
10160 }
10161 return false;
10162}
10163
10164/// BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
10165/// TheCall is a constant expression.
10166bool Sema::BuiltinConstantArg(CallExpr *TheCall, int ArgNum,
10167 llvm::APSInt &Result) {
10168 Expr *Arg = TheCall->getArg(ArgNum);
10169 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
10170 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
10171
10172 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
10173
10174 std::optional<llvm::APSInt> R;
10175 if (!(R = Arg->getIntegerConstantExpr(Context)))
10176 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
10177 << FDecl->getDeclName() << Arg->getSourceRange();
10178 Result = *R;
10179 return false;
10180}
10181
10182/// BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
10183/// TheCall is a constant expression in the range [Low, High].
10184bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
10185 int High, bool RangeIsError) {
10187 return false;
10188 llvm::APSInt Result;
10189
10190 // We can't check the value of a dependent argument.
10191 Expr *Arg = TheCall->getArg(ArgNum);
10192 if (Arg->isTypeDependent() || Arg->isValueDependent())
10193 return false;
10194
10195 // Check constant-ness first.
10196 if (BuiltinConstantArg(TheCall, ArgNum, Result))
10197 return true;
10198
10199 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
10200 if (RangeIsError)
10201 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
10202 << toString(Result, 10) << Low << High << Arg->getSourceRange();
10203 else
10204 // Defer the warning until we know if the code will be emitted so that
10205 // dead code can ignore this.
10206 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
10207 PDiag(diag::warn_argument_invalid_range)
10208 << toString(Result, 10) << Low << High
10209 << Arg->getSourceRange());
10210 }
10211
10212 return false;
10213}
10214
10215/// BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
10216/// TheCall is a constant expression is a multiple of Num..
10217bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
10218 unsigned Num) {
10219 llvm::APSInt Result;
10220
10221 // We can't check the value of a dependent argument.
10222 Expr *Arg = TheCall->getArg(ArgNum);
10223 if (Arg->isTypeDependent() || Arg->isValueDependent())
10224 return false;
10225
10226 // Check constant-ness first.
10227 if (BuiltinConstantArg(TheCall, ArgNum, Result))
10228 return true;
10229
10230 if (Result.getSExtValue() % Num != 0)
10231 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
10232 << Num << Arg->getSourceRange();
10233
10234 return false;
10235}
10236
10237/// BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
10238/// constant expression representing a power of 2.
10239bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
10240 llvm::APSInt Result;
10241
10242 // We can't check the value of a dependent argument.
10243 Expr *Arg = TheCall->getArg(ArgNum);
10244 if (Arg->isTypeDependent() || Arg->isValueDependent())
10245 return false;
10246
10247 // Check constant-ness first.
10248 if (BuiltinConstantArg(TheCall, ArgNum, Result))
10249 return true;
10250
10251 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
10252 // and only if x is a power of 2.
10253 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
10254 return false;
10255
10256 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
10257 << Arg->getSourceRange();
10258}
10259
10260static bool IsShiftedByte(llvm::APSInt Value) {
10261 if (Value.isNegative())
10262 return false;
10263
10264 // Check if it's a shifted byte, by shifting it down
10265 while (true) {
10266 // If the value fits in the bottom byte, the check passes.
10267 if (Value < 0x100)
10268 return true;
10269
10270 // Otherwise, if the value has _any_ bits in the bottom byte, the check
10271 // fails.
10272 if ((Value & 0xFF) != 0)
10273 return false;
10274
10275 // If the bottom 8 bits are all 0, but something above that is nonzero,
10276 // then shifting the value right by 8 bits won't affect whether it's a
10277 // shifted byte or not. So do that, and go round again.
10278 Value >>= 8;
10279 }
10280}
10281
10282/// BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
10283/// a constant expression representing an arbitrary byte value shifted left by
10284/// a multiple of 8 bits.
10285bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
10286 unsigned ArgBits) {
10287 llvm::APSInt Result;
10288
10289 // We can't check the value of a dependent argument.
10290 Expr *Arg = TheCall->getArg(ArgNum);
10291 if (Arg->isTypeDependent() || Arg->isValueDependent())
10292 return false;
10293
10294 // Check constant-ness first.
10295 if (BuiltinConstantArg(TheCall, ArgNum, Result))
10296 return true;
10297
10298 // Truncate to the given size.
10299 Result = Result.getLoBits(ArgBits);
10300 Result.setIsUnsigned(true);
10301
10302 if (IsShiftedByte(Result))
10303 return false;
10304
10305 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
10306 << Arg->getSourceRange();
10307}
10308
10309/// BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
10310/// TheCall is a constant expression representing either a shifted byte value,
10311/// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
10312/// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
10313/// Arm MVE intrinsics.
10314bool Sema::BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum,
10315 unsigned ArgBits) {
10316 llvm::APSInt Result;
10317
10318 // We can't check the value of a dependent argument.
10319 Expr *Arg = TheCall->getArg(ArgNum);
10320 if (Arg->isTypeDependent() || Arg->isValueDependent())
10321 return false;
10322
10323 // Check constant-ness first.
10324 if (BuiltinConstantArg(TheCall, ArgNum, Result))
10325 return true;
10326
10327 // Truncate to the given size.
10328 Result = Result.getLoBits(ArgBits);
10329 Result.setIsUnsigned(true);
10330
10331 // Check to see if it's in either of the required forms.
10332 if (IsShiftedByte(Result) ||
10333 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
10334 return false;
10335
10336 return Diag(TheCall->getBeginLoc(),
10337 diag::err_argument_not_shifted_byte_or_xxff)
10338 << Arg->getSourceRange();
10339}
10340
10341/// BuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
10342bool Sema::BuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
10343 if (BuiltinID == AArch64::BI__builtin_arm_irg) {
10344 if (checkArgCount(*this, TheCall, 2))
10345 return true;
10346 Expr *Arg0 = TheCall->getArg(0);
10347 Expr *Arg1 = TheCall->getArg(1);
10348
10350 if (FirstArg.isInvalid())
10351 return true;
10352 QualType FirstArgType = FirstArg.get()->getType();
10353 if (!FirstArgType->isAnyPointerType())
10354 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
10355 << "first" << FirstArgType << Arg0->getSourceRange();
10356 TheCall->setArg(0, FirstArg.get());
10357
10358 ExprResult SecArg = DefaultLvalueConversion(Arg1);
10359 if (SecArg.isInvalid())
10360 return true;
10361 QualType SecArgType = SecArg.get()->getType();
10362 if (!SecArgType->isIntegerType())
10363 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
10364 << "second" << SecArgType << Arg1->getSourceRange();
10365
10366 // Derive the return type from the pointer argument.
10367 TheCall->setType(FirstArgType);
10368 return false;
10369 }
10370
10371 if (BuiltinID == AArch64::BI__builtin_arm_addg) {
10372 if (checkArgCount(*this, TheCall, 2))
10373 return true;
10374
10375 Expr *Arg0 = TheCall->getArg(0);
10377 if (FirstArg.isInvalid())
10378 return true;
10379 QualType FirstArgType = FirstArg.get()->getType();
10380 if (!FirstArgType->isAnyPointerType())
10381 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
10382 << "first" << FirstArgType << Arg0->getSourceRange();
10383 TheCall->setArg(0, FirstArg.get());
10384
10385 // Derive the return type from the pointer argument.
10386 TheCall->setType(FirstArgType);
10387
10388 // Second arg must be an constant in range [0,15]
10389 return BuiltinConstantArgRange(TheCall, 1, 0, 15);
10390 }
10391
10392 if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
10393 if (checkArgCount(*this, TheCall, 2))
10394 return true;
10395 Expr *Arg0 = TheCall->getArg(0);
10396 Expr *Arg1 = TheCall->getArg(1);
10397
10399 if (FirstArg.isInvalid())
10400 return true;
10401 QualType FirstArgType = FirstArg.get()->getType();
10402 if (!FirstArgType->isAnyPointerType())
10403 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
10404 << "first" << FirstArgType << Arg0->getSourceRange();
10405
10406 QualType SecArgType = Arg1->getType();
10407 if (!SecArgType->isIntegerType())
10408 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
10409 << "second" << SecArgType << Arg1->getSourceRange();
10410 TheCall->setType(Context.IntTy);
10411 return false;
10412 }
10413
10414 if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
10415 BuiltinID == AArch64::BI__builtin_arm_stg) {
10416 if (checkArgCount(*this, TheCall, 1))
10417 return true;
10418 Expr *Arg0 = TheCall->getArg(0);
10420 if (FirstArg.isInvalid())
10421 return true;
10422
10423 QualType FirstArgType = FirstArg.get()->getType();
10424 if (!FirstArgType->isAnyPointerType())
10425 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
10426 << "first" << FirstArgType << Arg0->getSourceRange();
10427 TheCall->setArg(0, FirstArg.get());
10428
10429 // Derive the return type from the pointer argument.
10430 if (BuiltinID == AArch64::BI__builtin_arm_ldg)
10431 TheCall->setType(FirstArgType);
10432 return false;
10433 }
10434
10435 if (BuiltinID == AArch64::BI__builtin_arm_subp) {
10436 Expr *ArgA = TheCall->getArg(0);
10437 Expr *ArgB = TheCall->getArg(1);
10438
10441
10442 if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
10443 return true;
10444
10445 QualType ArgTypeA = ArgExprA.get()->getType();
10446 QualType ArgTypeB = ArgExprB.get()->getType();
10447
10448 auto isNull = [&] (Expr *E) -> bool {
10449 return E->isNullPointerConstant(
10451
10452 // argument should be either a pointer or null
10453 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
10454 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
10455 << "first" << ArgTypeA << ArgA->getSourceRange();
10456
10457 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
10458 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
10459 << "second" << ArgTypeB << ArgB->getSourceRange();
10460
10461 // Ensure Pointee types are compatible
10462 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
10463 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
10464 QualType pointeeA = ArgTypeA->getPointeeType();
10465 QualType pointeeB = ArgTypeB->getPointeeType();
10469 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
10470 << ArgTypeA << ArgTypeB << ArgA->getSourceRange()
10471 << ArgB->getSourceRange();
10472 }
10473 }
10474
10475 // at least one argument should be pointer type
10476 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
10477 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
10478 << ArgTypeA << ArgTypeB << ArgA->getSourceRange();
10479
10480 if (isNull(ArgA)) // adopt type of the other pointer
10481 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
10482
10483 if (isNull(ArgB))
10484 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
10485
10486 TheCall->setArg(0, ArgExprA.get());
10487 TheCall->setArg(1, ArgExprB.get());
10488 TheCall->setType(Context.LongLongTy);
10489 return false;
10490 }
10491 assert(false && "Unhandled ARM MTE intrinsic");
10492 return true;
10493}
10494
10495/// BuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
10496/// TheCall is an ARM/AArch64 special register string literal.
10497bool Sema::BuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
10498 int ArgNum, unsigned ExpectedFieldNum,
10499 bool AllowName) {
10500 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
10501 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
10502 BuiltinID == ARM::BI__builtin_arm_rsr ||
10503 BuiltinID == ARM::BI__builtin_arm_rsrp ||
10504 BuiltinID == ARM::BI__builtin_arm_wsr ||
10505 BuiltinID == ARM::BI__builtin_arm_wsrp;
10506 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
10507 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
10508 BuiltinID == AArch64::BI__builtin_arm_rsr128 ||
10509 BuiltinID == AArch64::BI__builtin_arm_wsr128 ||
10510 BuiltinID == AArch64::BI__builtin_arm_rsr ||
10511 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
10512 BuiltinID == AArch64::BI__builtin_arm_wsr ||
10513 BuiltinID == AArch64::BI__builtin_arm_wsrp;
10514 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
10515
10516 // We can't check the value of a dependent argument.
10517 Expr *Arg = TheCall->getArg(ArgNum);
10518 if (Arg->isTypeDependent() || Arg->isValueDependent())
10519 return false;
10520
10521 // Check if the argument is a string literal.
10522 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
10523 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
10524 << Arg->getSourceRange();
10525
10526 // Check the type of special register given.
10527 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
10529 Reg.split(Fields, ":");
10530
10531 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
10532 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
10533 << Arg->getSourceRange();
10534
10535 // If the string is the name of a register then we cannot check that it is
10536 // valid here but if the string is of one the forms described in ACLE then we
10537 // can check that the supplied fields are integers and within the valid
10538 // ranges.
10539 if (Fields.size() > 1) {
10540 bool FiveFields = Fields.size() == 5;
10541
10542 bool ValidString = true;
10543 if (IsARMBuiltin) {
10544 ValidString &= Fields[0].starts_with_insensitive("cp") ||
10545 Fields[0].starts_with_insensitive("p");
10546 if (ValidString)
10547 Fields[0] = Fields[0].drop_front(
10548 Fields[0].starts_with_insensitive("cp") ? 2 : 1);
10549
10550 ValidString &= Fields[2].starts_with_insensitive("c");
10551 if (ValidString)
10552 Fields[2] = Fields[2].drop_front(1);
10553
10554 if (FiveFields) {
10555 ValidString &= Fields[3].starts_with_insensitive("c");
10556 if (ValidString)
10557 Fields[3] = Fields[3].drop_front(1);
10558 }
10559 }
10560
10561 SmallVector<int, 5> Ranges;
10562 if (FiveFields)
10563 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
10564 else
10565 Ranges.append({15, 7, 15});
10566
10567 for (unsigned i=0; i<Fields.size(); ++i) {
10568 int IntField;
10569 ValidString &= !Fields[i].getAsInteger(10, IntField);
10570 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
10571 }
10572
10573 if (!ValidString)
10574 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
10575 << Arg->getSourceRange();
10576 } else if (IsAArch64Builtin && Fields.size() == 1) {
10577 // This code validates writes to PSTATE registers.
10578
10579 // Not a write.
10580 if (TheCall->getNumArgs() != 2)
10581 return false;
10582
10583 // The 128-bit system register accesses do not touch PSTATE.
10584 if (BuiltinID == AArch64::BI__builtin_arm_rsr128 ||
10585 BuiltinID == AArch64::BI__builtin_arm_wsr128)
10586 return false;
10587
10588 // These are the named PSTATE accesses using "MSR (immediate)" instructions,
10589 // along with the upper limit on the immediates allowed.
10590 auto MaxLimit = llvm::StringSwitch<std::optional<unsigned>>(Reg)
10591 .CaseLower("spsel", 15)
10592 .CaseLower("daifclr", 15)
10593 .CaseLower("daifset", 15)
10594 .CaseLower("pan", 15)
10595 .CaseLower("uao", 15)
10596 .CaseLower("dit", 15)
10597 .CaseLower("ssbs", 15)
10598 .CaseLower("tco", 15)
10599 .CaseLower("allint", 1)
10600 .CaseLower("pm", 1)
10601 .Default(std::nullopt);
10602
10603 // If this is not a named PSTATE, just continue without validating, as this
10604 // will be lowered to an "MSR (register)" instruction directly
10605 if (!MaxLimit)
10606 return false;
10607
10608 // Here we only allow constants in the range for that pstate, as required by
10609 // the ACLE.
10610 //
10611 // While clang also accepts the names of system registers in its ACLE
10612 // intrinsics, we prevent this with the PSTATE names used in MSR (immediate)
10613 // as the value written via a register is different to the value used as an
10614 // immediate to have the same effect. e.g., for the instruction `msr tco,
10615 // x0`, it is bit 25 of register x0 that is written into PSTATE.TCO, but
10616 // with `msr tco, #imm`, it is bit 0 of xN that is written into PSTATE.TCO.
10617 //
10618 // If a programmer wants to codegen the MSR (register) form of `msr tco,
10619 // xN`, they can still do so by specifying the register using five
10620 // colon-separated numbers in a string.
10621 return BuiltinConstantArgRange(TheCall, 1, 0, *MaxLimit);
10622 }
10623
10624 return false;
10625}
10626
10627/// BuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
10628/// Emit an error and return true on failure; return false on success.
10629/// TypeStr is a string containing the type descriptor of the value returned by
10630/// the builtin and the descriptors of the expected type of the arguments.
10631bool Sema::BuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
10632 const char *TypeStr) {
10633
10634 assert((TypeStr[0] != '\0') &&
10635 "Invalid types in PPC MMA builtin declaration");
10636
10637 unsigned Mask = 0;
10638 unsigned ArgNum = 0;
10639
10640 // The first type in TypeStr is the type of the value returned by the
10641 // builtin. So we first read that type and change the type of TheCall.
10642 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
10643 TheCall->setType(type);
10644
10645 while (*TypeStr != '\0') {
10646 Mask = 0;
10648 if (ArgNum >= TheCall->getNumArgs()) {
10649 ArgNum++;
10650 break;
10651 }
10652
10653 Expr *Arg = TheCall->getArg(ArgNum);
10654 QualType PassedType = Arg->getType();
10655 QualType StrippedRVType = PassedType.getCanonicalType();
10656
10657 // Strip Restrict/Volatile qualifiers.
10658 if (StrippedRVType.isRestrictQualified() ||
10659 StrippedRVType.isVolatileQualified())
10660 StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
10661
10662 // The only case where the argument type and expected type are allowed to
10663 // mismatch is if the argument type is a non-void pointer (or array) and
10664 // expected type is a void pointer.
10665 if (StrippedRVType != ExpectedType)
10666 if (!(ExpectedType->isVoidPointerType() &&
10667 (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
10668 return Diag(Arg->getBeginLoc(),
10669 diag::err_typecheck_convert_incompatible)
10670 << PassedType << ExpectedType << 1 << 0 << 0;
10671
10672 // If the value of the Mask is not 0, we have a constraint in the size of
10673 // the integer argument so here we ensure the argument is a constant that
10674 // is in the valid range.
10675 if (Mask != 0 && BuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
10676 return true;
10677
10678 ArgNum++;
10679 }
10680
10681 // In case we exited early from the previous loop, there are other types to
10682 // read from TypeStr. So we need to read them all to ensure we have the right
10683 // number of arguments in TheCall and if it is not the case, to display a
10684 // better error message.
10685 while (*TypeStr != '\0') {
10686 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
10687 ArgNum++;
10688 }
10689 if (checkArgCount(*this, TheCall, ArgNum))
10690 return true;
10691
10692 return false;
10693}
10694
10695/// BuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
10696/// This checks that the target supports __builtin_longjmp and
10697/// that val is a constant 1.
10698bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
10700 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
10701 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
10702
10703 Expr *Arg = TheCall->getArg(1);
10704 llvm::APSInt Result;
10705
10706 // TODO: This is less than ideal. Overload this to take a value.
10707 if (BuiltinConstantArg(TheCall, 1, Result))
10708 return true;
10709
10710 if (Result != 1)
10711 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
10712 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
10713
10714 return false;
10715}
10716
10717/// BuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
10718/// This checks that the target supports __builtin_setjmp.
10719bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
10721 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
10722 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
10723 return false;
10724}
10725
10726namespace {
10727
10728class UncoveredArgHandler {
10729 enum { Unknown = -1, AllCovered = -2 };
10730
10731 signed FirstUncoveredArg = Unknown;
10732 SmallVector<const Expr *, 4> DiagnosticExprs;
10733
10734public:
10735 UncoveredArgHandler() = default;
10736
10737 bool hasUncoveredArg() const {
10738 return (FirstUncoveredArg >= 0);
10739 }
10740
10741 unsigned getUncoveredArg() const {
10742 assert(hasUncoveredArg() && "no uncovered argument");
10743 return FirstUncoveredArg;
10744 }
10745
10746 void setAllCovered() {
10747 // A string has been found with all arguments covered, so clear out
10748 // the diagnostics.
10749 DiagnosticExprs.clear();
10750 FirstUncoveredArg = AllCovered;
10751 }
10752
10753 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
10754 assert(NewFirstUncoveredArg >= 0 && "Outside range");
10755
10756 // Don't update if a previous string covers all arguments.
10757 if (FirstUncoveredArg == AllCovered)
10758 return;
10759
10760 // UncoveredArgHandler tracks the highest uncovered argument index
10761 // and with it all the strings that match this index.
10762 if (NewFirstUncoveredArg == FirstUncoveredArg)
10763 DiagnosticExprs.push_back(StrExpr);
10764 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
10765 DiagnosticExprs.clear();
10766 DiagnosticExprs.push_back(StrExpr);
10767 FirstUncoveredArg = NewFirstUncoveredArg;
10768 }
10769 }
10770
10771 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
10772};
10773
10774enum StringLiteralCheckType {
10775 SLCT_NotALiteral,
10776 SLCT_UncheckedLiteral,
10777 SLCT_CheckedLiteral
10778};
10779
10780} // namespace
10781
10782static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
10783 BinaryOperatorKind BinOpKind,
10784 bool AddendIsRight) {
10785 unsigned BitWidth = Offset.getBitWidth();
10786 unsigned AddendBitWidth = Addend.getBitWidth();
10787 // There might be negative interim results.
10788 if (Addend.isUnsigned()) {
10789 Addend = Addend.zext(++AddendBitWidth);
10790 Addend.setIsSigned(true);
10791 }
10792 // Adjust the bit width of the APSInts.
10793 if (AddendBitWidth > BitWidth) {
10794 Offset = Offset.sext(AddendBitWidth);
10795 BitWidth = AddendBitWidth;
10796 } else if (BitWidth > AddendBitWidth) {
10797 Addend = Addend.sext(BitWidth);
10798 }
10799
10800 bool Ov = false;
10801 llvm::APSInt ResOffset = Offset;
10802 if (BinOpKind == BO_Add)
10803 ResOffset = Offset.sadd_ov(Addend, Ov);
10804 else {
10805 assert(AddendIsRight && BinOpKind == BO_Sub &&
10806 "operator must be add or sub with addend on the right");
10807 ResOffset = Offset.ssub_ov(Addend, Ov);
10808 }
10809
10810 // We add an offset to a pointer here so we should support an offset as big as
10811 // possible.
10812 if (Ov) {
10813 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
10814 "index (intermediate) result too big");
10815 Offset = Offset.sext(2 * BitWidth);
10816 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
10817 return;
10818 }
10819
10820 Offset = ResOffset;
10821}
10822
10823namespace {
10824
10825// This is a wrapper class around StringLiteral to support offsetted string
10826// literals as format strings. It takes the offset into account when returning
10827// the string and its length or the source locations to display notes correctly.
10828class FormatStringLiteral {
10829 const StringLiteral *FExpr;
10830 int64_t Offset;
10831
10832 public:
10833 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
10834 : FExpr(fexpr), Offset(Offset) {}
10835
10836 StringRef getString() const {
10837 return FExpr->getString().drop_front(Offset);
10838 }
10839
10840 unsigned getByteLength() const {
10841 return FExpr->getByteLength() - getCharByteWidth() * Offset;
10842 }
10843
10844 unsigned getLength() const { return FExpr->getLength() - Offset; }
10845 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
10846
10847 StringLiteralKind getKind() const { return FExpr->getKind(); }
10848
10849 QualType getType() const { return FExpr->getType(); }
10850
10851 bool isAscii() const { return FExpr->isOrdinary(); }
10852 bool isWide() const { return FExpr->isWide(); }
10853 bool isUTF8() const { return FExpr->isUTF8(); }
10854 bool isUTF16() const { return FExpr->isUTF16(); }
10855 bool isUTF32() const { return FExpr->isUTF32(); }
10856 bool isPascal() const { return FExpr->isPascal(); }
10857
10858 SourceLocation getLocationOfByte(
10859 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
10860 const TargetInfo &Target, unsigned *StartToken = nullptr,
10861 unsigned *StartTokenByteOffset = nullptr) const {
10862 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
10863 StartToken, StartTokenByteOffset);
10864 }
10865
10866 SourceLocation getBeginLoc() const LLVM_READONLY {
10867 return FExpr->getBeginLoc().getLocWithOffset(Offset);
10868 }
10869
10870 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
10871};
10872
10873} // namespace
10874
10875static void CheckFormatString(
10876 Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr,
10878 unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type,
10879 bool inFunctionCall, Sema::VariadicCallType CallType,
10880 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
10881 bool IgnoreStringsWithoutSpecifiers);
10882
10883static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
10884 const Expr *E);
10885
10886// Determine if an expression is a string literal or constant string.
10887// If this function returns false on the arguments to a function expecting a
10888// format string, we will usually need to emit a warning.
10889// True string literals are then checked by CheckFormatString.
10890static StringLiteralCheckType
10892 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
10893 unsigned firstDataArg, Sema::FormatStringType Type,
10894 Sema::VariadicCallType CallType, bool InFunctionCall,
10895 llvm::SmallBitVector &CheckedVarArgs,
10896 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
10897 bool IgnoreStringsWithoutSpecifiers = false) {
10899 return SLCT_NotALiteral;
10900tryAgain:
10901 assert(Offset.isSigned() && "invalid offset");
10902
10903 if (E->isTypeDependent() || E->isValueDependent())
10904 return SLCT_NotALiteral;
10905
10906 E = E->IgnoreParenCasts();
10907
10909 // Technically -Wformat-nonliteral does not warn about this case.
10910 // The behavior of printf and friends in this case is implementation
10911 // dependent. Ideally if the format string cannot be null then
10912 // it should have a 'nonnull' attribute in the function prototype.
10913 return SLCT_UncheckedLiteral;
10914
10915 switch (E->getStmtClass()) {
10916 case Stmt::InitListExprClass:
10917 // Handle expressions like {"foobar"}.
10918 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
10919 return checkFormatStringExpr(S, SLE, Args, APK, format_idx, firstDataArg,
10920 Type, CallType, /*InFunctionCall*/ false,
10921 CheckedVarArgs, UncoveredArg, Offset,
10922 IgnoreStringsWithoutSpecifiers);
10923 }
10924 return SLCT_NotALiteral;
10925 case Stmt::BinaryConditionalOperatorClass:
10926 case Stmt::ConditionalOperatorClass: {
10927 // The expression is a literal if both sub-expressions were, and it was
10928 // completely checked only if both sub-expressions were checked.
10930 cast<AbstractConditionalOperator>(E);
10931
10932 // Determine whether it is necessary to check both sub-expressions, for
10933 // example, because the condition expression is a constant that can be
10934 // evaluated at compile time.
10935 bool CheckLeft = true, CheckRight = true;
10936
10937 bool Cond;
10938 if (C->getCond()->EvaluateAsBooleanCondition(
10939 Cond, S.getASTContext(), S.isConstantEvaluatedContext())) {
10940 if (Cond)
10941 CheckRight = false;
10942 else
10943 CheckLeft = false;
10944 }
10945
10946 // We need to maintain the offsets for the right and the left hand side
10947 // separately to check if every possible indexed expression is a valid
10948 // string literal. They might have different offsets for different string
10949 // literals in the end.
10950 StringLiteralCheckType Left;
10951 if (!CheckLeft)
10952 Left = SLCT_UncheckedLiteral;
10953 else {
10954 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, APK, format_idx,
10955 firstDataArg, Type, CallType, InFunctionCall,
10956 CheckedVarArgs, UncoveredArg, Offset,
10957 IgnoreStringsWithoutSpecifiers);
10958 if (Left == SLCT_NotALiteral || !CheckRight) {
10959 return Left;
10960 }
10961 }
10962
10963 StringLiteralCheckType Right = checkFormatStringExpr(
10964 S, C->getFalseExpr(), Args, APK, format_idx, firstDataArg, Type,
10965 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
10966 IgnoreStringsWithoutSpecifiers);
10967
10968 return (CheckLeft && Left < Right) ? Left : Right;
10969 }
10970
10971 case Stmt::ImplicitCastExprClass:
10972 E = cast<ImplicitCastExpr>(E)->getSubExpr();
10973 goto tryAgain;
10974
10975 case Stmt::OpaqueValueExprClass:
10976 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
10977 E = src;
10978 goto tryAgain;
10979 }
10980 return SLCT_NotALiteral;
10981
10982 case Stmt::PredefinedExprClass:
10983 // While __func__, etc., are technically not string literals, they
10984 // cannot contain format specifiers and thus are not a security
10985 // liability.
10986 return SLCT_UncheckedLiteral;
10987
10988 case Stmt::DeclRefExprClass: {
10989 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
10990
10991 // As an exception, do not flag errors for variables binding to
10992 // const string literals.
10993 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
10994 bool isConstant = false;
10995 QualType T = DR->getType();
10996
10997 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
10998 isConstant = AT->getElementType().isConstant(S.Context);
10999 } else if (const PointerType *PT = T->getAs<PointerType>()) {
11000 isConstant = T.isConstant(S.Context) &&
11002 } else if (T->isObjCObjectPointerType()) {
11003 // In ObjC, there is usually no "const ObjectPointer" type,
11004 // so don't check if the pointee type is constant.
11005 isConstant = T.isConstant(S.Context);
11006 }
11007
11008 if (isConstant) {
11009 if (const Expr *Init = VD->getAnyInitializer()) {
11010 // Look through initializers like const char c[] = { "foo" }
11011 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
11012 if (InitList->isStringLiteralInit())
11013 Init = InitList->getInit(0)->IgnoreParenImpCasts();
11014 }
11015 return checkFormatStringExpr(
11016 S, Init, Args, APK, format_idx, firstDataArg, Type, CallType,
11017 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg, Offset);
11018 }
11019 }
11020
11021 // When the format argument is an argument of this function, and this
11022 // function also has the format attribute, there are several interactions
11023 // for which there shouldn't be a warning. For instance, when calling
11024 // v*printf from a function that has the printf format attribute, we
11025 // should not emit a warning about using `fmt`, even though it's not
11026 // constant, because the arguments have already been checked for the
11027 // caller of `logmessage`:
11028 //
11029 // __attribute__((format(printf, 1, 2)))
11030 // void logmessage(char const *fmt, ...) {
11031 // va_list ap;
11032 // va_start(ap, fmt);
11033 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
11034 // ...
11035 // }
11036 //
11037 // Another interaction that we need to support is calling a variadic
11038 // format function from a format function that has fixed arguments. For
11039 // instance:
11040 //
11041 // __attribute__((format(printf, 1, 2)))
11042 // void logstring(char const *fmt, char const *str) {
11043 // printf(fmt, str); /* do not emit a warning about "fmt" */
11044 // }
11045 //
11046 // Same (and perhaps more relatably) for the variadic template case:
11047 //
11048 // template<typename... Args>
11049 // __attribute__((format(printf, 1, 2)))
11050 // void log(const char *fmt, Args&&... args) {
11051 // printf(fmt, forward<Args>(args)...);
11052 // /* do not emit a warning about "fmt" */
11053 // }
11054 //
11055 // Due to implementation difficulty, we only check the format, not the
11056 // format arguments, in all cases.
11057 //
11058 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
11059 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
11060 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
11061 bool IsCXXMember = false;
11062 if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
11063 IsCXXMember = MD->isInstance();
11064
11065 bool IsVariadic = false;
11066 if (const FunctionType *FnTy = D->getFunctionType())
11067 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
11068 else if (const auto *BD = dyn_cast<BlockDecl>(D))
11069 IsVariadic = BD->isVariadic();
11070 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
11071 IsVariadic = OMD->isVariadic();
11072
11073 Sema::FormatStringInfo CallerFSI;
11074 if (Sema::getFormatStringInfo(PVFormat, IsCXXMember, IsVariadic,
11075 &CallerFSI)) {
11076 // We also check if the formats are compatible.
11077 // We can't pass a 'scanf' string to a 'printf' function.
11078 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx &&
11079 Type == S.GetFormatStringType(PVFormat)) {
11080 // Lastly, check that argument passing kinds transition in a
11081 // way that makes sense:
11082 // from a caller with FAPK_VAList, allow FAPK_VAList
11083 // from a caller with FAPK_Fixed, allow FAPK_Fixed
11084 // from a caller with FAPK_Fixed, allow FAPK_Variadic
11085 // from a caller with FAPK_Variadic, allow FAPK_VAList
11086 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
11091 return SLCT_UncheckedLiteral;
11092 }
11093 }
11094 }
11095 }
11096 }
11097 }
11098 }
11099
11100 return SLCT_NotALiteral;
11101 }
11102
11103 case Stmt::CallExprClass:
11104 case Stmt::CXXMemberCallExprClass: {
11105 const CallExpr *CE = cast<CallExpr>(E);
11106 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
11107 bool IsFirst = true;
11108 StringLiteralCheckType CommonResult;
11109 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
11110 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
11111 StringLiteralCheckType Result = checkFormatStringExpr(
11112 S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
11113 InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
11114 IgnoreStringsWithoutSpecifiers);
11115 if (IsFirst) {
11116 CommonResult = Result;
11117 IsFirst = false;
11118 }
11119 }
11120 if (!IsFirst)
11121 return CommonResult;
11122
11123 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
11124 unsigned BuiltinID = FD->getBuiltinID();
11125 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
11126 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
11127 const Expr *Arg = CE->getArg(0);
11128 return checkFormatStringExpr(
11129 S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
11130 InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
11131 IgnoreStringsWithoutSpecifiers);
11132 }
11133 }
11134 }
11135 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
11136 return checkFormatStringExpr(S, SLE, Args, APK, format_idx, firstDataArg,
11137 Type, CallType, /*InFunctionCall*/ false,
11138 CheckedVarArgs, UncoveredArg, Offset,
11139 IgnoreStringsWithoutSpecifiers);
11140 return SLCT_NotALiteral;
11141 }
11142 case Stmt::ObjCMessageExprClass: {
11143 const auto *ME = cast<ObjCMessageExpr>(E);
11144 if (const auto *MD = ME->getMethodDecl()) {
11145 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
11146 // As a special case heuristic, if we're using the method -[NSBundle
11147 // localizedStringForKey:value:table:], ignore any key strings that lack
11148 // format specifiers. The idea is that if the key doesn't have any
11149 // format specifiers then its probably just a key to map to the
11150 // localized strings. If it does have format specifiers though, then its
11151 // likely that the text of the key is the format string in the
11152 // programmer's language, and should be checked.
11153 const ObjCInterfaceDecl *IFace;
11154 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
11155 IFace->getIdentifier()->isStr("NSBundle") &&
11156 MD->getSelector().isKeywordSelector(
11157 {"localizedStringForKey", "value", "table"})) {
11158 IgnoreStringsWithoutSpecifiers = true;
11159 }
11160
11161 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
11162 return checkFormatStringExpr(
11163 S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
11164 InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
11165 IgnoreStringsWithoutSpecifiers);
11166 }
11167 }
11168
11169 return SLCT_NotALiteral;
11170 }
11171 case Stmt::ObjCStringLiteralClass:
11172 case Stmt::StringLiteralClass: {
11173 const StringLiteral *StrE = nullptr;
11174
11175 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
11176 StrE = ObjCFExpr->getString();
11177 else
11178 StrE = cast<StringLiteral>(E);
11179
11180 if (StrE) {
11181 if (Offset.isNegative() || Offset > StrE->getLength()) {
11182 // TODO: It would be better to have an explicit warning for out of
11183 // bounds literals.
11184 return SLCT_NotALiteral;
11185 }
11186 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
11187 CheckFormatString(S, &FStr, E, Args, APK, format_idx, firstDataArg, Type,
11188 InFunctionCall, CallType, CheckedVarArgs, UncoveredArg,
11189 IgnoreStringsWithoutSpecifiers);
11190 return SLCT_CheckedLiteral;
11191 }
11192
11193 return SLCT_NotALiteral;
11194 }
11195 case Stmt::BinaryOperatorClass: {
11196 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
11197
11198 // A string literal + an int offset is still a string literal.
11199 if (BinOp->isAdditiveOp()) {
11200 Expr::EvalResult LResult, RResult;
11201
11202 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
11203 LResult, S.Context, Expr::SE_NoSideEffects,
11205 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
11206 RResult, S.Context, Expr::SE_NoSideEffects,
11208
11209 if (LIsInt != RIsInt) {
11210 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
11211
11212 if (LIsInt) {
11213 if (BinOpKind == BO_Add) {
11214 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
11215 E = BinOp->getRHS();
11216 goto tryAgain;
11217 }
11218 } else {
11219 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
11220 E = BinOp->getLHS();
11221 goto tryAgain;
11222 }
11223 }
11224 }
11225
11226 return SLCT_NotALiteral;
11227 }
11228 case Stmt::UnaryOperatorClass: {
11229 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
11230 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
11231 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
11232 Expr::EvalResult IndexResult;
11233 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
11236 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
11237 /*RHS is int*/ true);
11238 E = ASE->getBase();
11239 goto tryAgain;
11240 }
11241 }
11242
11243 return SLCT_NotALiteral;
11244 }
11245
11246 default:
11247 return SLCT_NotALiteral;
11248 }
11249}
11250
11251// If this expression can be evaluated at compile-time,
11252// check if the result is a StringLiteral and return it
11253// otherwise return nullptr
11255 const Expr *E) {
11257 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
11258 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
11259 if (isa_and_nonnull<StringLiteral>(LVE))
11260 return LVE;
11261 }
11262 return nullptr;
11263}
11264
11266 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
11267 .Case("scanf", FST_Scanf)
11268 .Cases("printf", "printf0", FST_Printf)
11269 .Cases("NSString", "CFString", FST_NSString)
11270 .Case("strftime", FST_Strftime)
11271 .Case("strfmon", FST_Strfmon)
11272 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
11273 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
11274 .Case("os_trace", FST_OSLog)
11275 .Case("os_log", FST_OSLog)
11276 .Default(FST_Unknown);
11277}
11278
11279/// CheckFormatArguments - Check calls to printf and scanf (and similar
11280/// functions) for correct use of format strings.
11281/// Returns true if a format string has been fully checked.
11282bool Sema::CheckFormatArguments(const FormatAttr *Format,
11283 ArrayRef<const Expr *> Args, bool IsCXXMember,
11284 VariadicCallType CallType, SourceLocation Loc,
11285 SourceRange Range,
11286 llvm::SmallBitVector &CheckedVarArgs) {
11287 FormatStringInfo FSI;
11288 if (getFormatStringInfo(Format, IsCXXMember, CallType != VariadicDoesNotApply,
11289 &FSI))
11290 return CheckFormatArguments(Args, FSI.ArgPassingKind, FSI.FormatIdx,
11291 FSI.FirstDataArg, GetFormatStringType(Format),
11292 CallType, Loc, Range, CheckedVarArgs);
11293 return false;
11294}
11295
11296bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
11298 unsigned format_idx, unsigned firstDataArg,
11299 FormatStringType Type,
11300 VariadicCallType CallType, SourceLocation Loc,
11301 SourceRange Range,
11302 llvm::SmallBitVector &CheckedVarArgs) {
11303 // CHECK: printf/scanf-like function is called with no format string.
11304 if (format_idx >= Args.size()) {
11305 Diag(Loc, diag::warn_missing_format_string) << Range;
11306 return false;
11307 }
11308
11309 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
11310
11311 // CHECK: format string is not a string literal.
11312 //
11313 // Dynamically generated format strings are difficult to
11314 // automatically vet at compile time. Requiring that format strings
11315 // are string literals: (1) permits the checking of format strings by
11316 // the compiler and thereby (2) can practically remove the source of
11317 // many format string exploits.
11318
11319 // Format string can be either ObjC string (e.g. @"%d") or
11320 // C string (e.g. "%d")
11321 // ObjC string uses the same format specifiers as C string, so we can use
11322 // the same format string checking logic for both ObjC and C strings.
11323 UncoveredArgHandler UncoveredArg;
11324 StringLiteralCheckType CT = checkFormatStringExpr(
11325 *this, OrigFormatExpr, Args, APK, format_idx, firstDataArg, Type,
11326 CallType,
11327 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
11328 /*no string offset*/ llvm::APSInt(64, false) = 0);
11329
11330 // Generate a diagnostic where an uncovered argument is detected.
11331 if (UncoveredArg.hasUncoveredArg()) {
11332 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
11333 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
11334 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
11335 }
11336
11337 if (CT != SLCT_NotALiteral)
11338 // Literal format string found, check done!
11339 return CT == SLCT_CheckedLiteral;
11340
11341 // Strftime is particular as it always uses a single 'time' argument,
11342 // so it is safe to pass a non-literal string.
11343 if (Type == FST_Strftime)
11344 return false;
11345
11346 // Do not emit diag when the string param is a macro expansion and the
11347 // format is either NSString or CFString. This is a hack to prevent
11348 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
11349 // which are usually used in place of NS and CF string literals.
11350 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
11351 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
11352 return false;
11353
11354 // If there are no arguments specified, warn with -Wformat-security, otherwise
11355 // warn only with -Wformat-nonliteral.
11356 if (Args.size() == firstDataArg) {
11357 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
11358 << OrigFormatExpr->getSourceRange();
11359 switch (Type) {
11360 default:
11361 break;
11362 case FST_Kprintf:
11363 case FST_FreeBSDKPrintf:
11364 case FST_Printf:
11365 Diag(FormatLoc, diag::note_format_security_fixit)
11366 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
11367 break;
11368 case FST_NSString:
11369 Diag(FormatLoc, diag::note_format_security_fixit)
11370 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
11371 break;
11372 }
11373 } else {
11374 Diag(FormatLoc, diag::warn_format_nonliteral)
11375 << OrigFormatExpr->getSourceRange();
11376 }
11377 return false;
11378}
11379
11380namespace {
11381
11382class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
11383protected:
11384 Sema &S;
11385 const FormatStringLiteral *FExpr;
11386 const Expr *OrigFormatExpr;
11387 const Sema::FormatStringType FSType;
11388 const unsigned FirstDataArg;
11389 const unsigned NumDataArgs;
11390 const char *Beg; // Start of format string.
11391 const Sema::FormatArgumentPassingKind ArgPassingKind;
11393 unsigned FormatIdx;
11394 llvm::SmallBitVector CoveredArgs;
11395 bool usesPositionalArgs = false;
11396 bool atFirstArg = true;
11397 bool inFunctionCall;
11398 Sema::VariadicCallType CallType;
11399 llvm::SmallBitVector &CheckedVarArgs;
11400 UncoveredArgHandler &UncoveredArg;
11401
11402public:
11403 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
11404 const Expr *origFormatExpr,
11405 const Sema::FormatStringType type, unsigned firstDataArg,
11406 unsigned numDataArgs, const char *beg,
11408 ArrayRef<const Expr *> Args, unsigned formatIdx,
11409 bool inFunctionCall, Sema::VariadicCallType callType,
11410 llvm::SmallBitVector &CheckedVarArgs,
11411 UncoveredArgHandler &UncoveredArg)
11412 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
11413 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
11414 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
11415 inFunctionCall(inFunctionCall), CallType(callType),
11416 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
11417 CoveredArgs.resize(numDataArgs);
11418 CoveredArgs.reset();
11419 }
11420
11421 void DoneProcessing();
11422
11423 void HandleIncompleteSpecifier(const char *startSpecifier,
11424 unsigned specifierLen) override;
11425
11426 void HandleInvalidLengthModifier(
11429 const char *startSpecifier, unsigned specifierLen,
11430 unsigned DiagID);
11431
11432 void HandleNonStandardLengthModifier(
11434 const char *startSpecifier, unsigned specifierLen);
11435
11436 void HandleNonStandardConversionSpecifier(
11438 const char *startSpecifier, unsigned specifierLen);
11439
11440 void HandlePosition(const char *startPos, unsigned posLen) override;
11441
11442 void HandleInvalidPosition(const char *startSpecifier,
11443 unsigned specifierLen,
11445
11446 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
11447
11448 void HandleNullChar(const char *nullCharacter) override;
11449
11450 template <typename Range>
11451 static void
11452 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
11453 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
11454 bool IsStringLocation, Range StringRange,
11455 ArrayRef<FixItHint> Fixit = std::nullopt);
11456
11457protected:
11458 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
11459 const char *startSpec,
11460 unsigned specifierLen,
11461 const char *csStart, unsigned csLen);
11462
11463 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
11464 const char *startSpec,
11465 unsigned specifierLen);
11466
11467 SourceRange getFormatStringRange();
11468 CharSourceRange getSpecifierRange(const char *startSpecifier,
11469 unsigned specifierLen);
11470 SourceLocation getLocationOfByte(const char *x);
11471
11472 const Expr *getDataArg(unsigned i) const;
11473
11474 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
11476 const char *startSpecifier, unsigned specifierLen,
11477 unsigned argIndex);
11478
11479 template <typename Range>
11480 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
11481 bool IsStringLocation, Range StringRange,
11482 ArrayRef<FixItHint> Fixit = std::nullopt);
11483};
11484
11485} // namespace
11486
11487SourceRange CheckFormatHandler::getFormatStringRange() {
11488 return OrigFormatExpr->getSourceRange();
11489}
11490
11491CharSourceRange CheckFormatHandler::
11492getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
11493 SourceLocation Start = getLocationOfByte(startSpecifier);
11494 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
11495
11496 // Advance the end SourceLocation by one due to half-open ranges.
11497 End = End.getLocWithOffset(1);
11498
11499 return CharSourceRange::getCharRange(Start, End);
11500}
11501
11502SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
11503 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
11505}
11506
11507void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
11508 unsigned specifierLen){
11509 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
11510 getLocationOfByte(startSpecifier),
11511 /*IsStringLocation*/true,
11512 getSpecifierRange(startSpecifier, specifierLen));
11513}
11514
11515void CheckFormatHandler::HandleInvalidLengthModifier(
11518 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
11519 using namespace analyze_format_string;
11520
11521 const LengthModifier &LM = FS.getLengthModifier();
11522 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
11523
11524 // See if we know how to fix this length modifier.
11525 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
11526 if (FixedLM) {
11527 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
11528 getLocationOfByte(LM.getStart()),
11529 /*IsStringLocation*/true,
11530 getSpecifierRange(startSpecifier, specifierLen));
11531
11532 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
11533 << FixedLM->toString()
11534 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
11535
11536 } else {
11537 FixItHint Hint;
11538 if (DiagID == diag::warn_format_nonsensical_length)
11539 Hint = FixItHint::CreateRemoval(LMRange);
11540
11541 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
11542 getLocationOfByte(LM.getStart()),
11543 /*IsStringLocation*/true,
11544 getSpecifierRange(startSpecifier, specifierLen),
11545 Hint);
11546 }
11547}
11548
11549void CheckFormatHandler::HandleNonStandardLengthModifier(
11551 const char *startSpecifier, unsigned specifierLen) {
11552 using namespace analyze_format_string;
11553
11554 const LengthModifier &LM = FS.getLengthModifier();
11555 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
11556
11557 // See if we know how to fix this length modifier.
11558 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
11559 if (FixedLM) {
11560 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
11561 << LM.toString() << 0,
11562 getLocationOfByte(LM.getStart()),
11563 /*IsStringLocation*/true,
11564 getSpecifierRange(startSpecifier, specifierLen));
11565
11566 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
11567 << FixedLM->toString()
11568 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
11569
11570 } else {
11571 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
11572 << LM.toString() << 0,
11573 getLocationOfByte(LM.getStart()),
11574 /*IsStringLocation*/true,
11575 getSpecifierRange(startSpecifier, specifierLen));
11576 }
11577}
11578
11579void CheckFormatHandler::HandleNonStandardConversionSpecifier(
11581 const char *startSpecifier, unsigned specifierLen) {
11582 using namespace analyze_format_string;
11583
11584 // See if we know how to fix this conversion specifier.
11585 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
11586 if (FixedCS) {
11587 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
11588 << CS.toString() << /*conversion specifier*/1,
11589 getLocationOfByte(CS.getStart()),
11590 /*IsStringLocation*/true,
11591 getSpecifierRange(startSpecifier, specifierLen));
11592
11593 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
11594 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
11595 << FixedCS->toString()
11596 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
11597 } else {
11598 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
11599 << CS.toString() << /*conversion specifier*/1,
11600 getLocationOfByte(CS.getStart()),
11601 /*IsStringLocation*/true,
11602 getSpecifierRange(startSpecifier, specifierLen));
11603 }
11604}
11605
11606void CheckFormatHandler::HandlePosition(const char *startPos,
11607 unsigned posLen) {
11608 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
11609 getLocationOfByte(startPos),
11610 /*IsStringLocation*/true,
11611 getSpecifierRange(startPos, posLen));
11612}
11613
11614void CheckFormatHandler::HandleInvalidPosition(
11615 const char *startSpecifier, unsigned specifierLen,
11617 EmitFormatDiagnostic(
11618 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
11619 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
11620 getSpecifierRange(startSpecifier, specifierLen));
11621}
11622
11623void CheckFormatHandler::HandleZeroPosition(const char *startPos,
11624 unsigned posLen) {
11625 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
11626 getLocationOfByte(startPos),
11627 /*IsStringLocation*/true,
11628 getSpecifierRange(startPos, posLen));
11629}
11630
11631void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
11632 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
11633 // The presence of a null character is likely an error.
11634 EmitFormatDiagnostic(
11635 S.PDiag(diag::warn_printf_format_string_contains_null_char),
11636 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
11637 getFormatStringRange());
11638 }
11639}
11640
11641// Note that this may return NULL if there was an error parsing or building
11642// one of the argument expressions.
11643const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
11644 return Args[FirstDataArg + i];
11645}
11646
11647void CheckFormatHandler::DoneProcessing() {
11648 // Does the number of data arguments exceed the number of
11649 // format conversions in the format string?
11650 if (ArgPassingKind != Sema::FAPK_VAList) {
11651 // Find any arguments that weren't covered.
11652 CoveredArgs.flip();
11653 signed notCoveredArg = CoveredArgs.find_first();
11654 if (notCoveredArg >= 0) {
11655 assert((unsigned)notCoveredArg < NumDataArgs);
11656 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
11657 } else {
11658 UncoveredArg.setAllCovered();
11659 }
11660 }
11661}
11662
11663void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
11664 const Expr *ArgExpr) {
11665 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
11666 "Invalid state");
11667
11668 if (!ArgExpr)
11669 return;
11670
11671 SourceLocation Loc = ArgExpr->getBeginLoc();
11672
11673 if (S.getSourceManager().isInSystemMacro(Loc))
11674 return;
11675
11676 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
11677 for (auto E : DiagnosticExprs)
11678 PDiag << E->getSourceRange();
11679
11680 CheckFormatHandler::EmitFormatDiagnostic(
11681 S, IsFunctionCall, DiagnosticExprs[0],
11682 PDiag, Loc, /*IsStringLocation*/false,
11683 DiagnosticExprs[0]->getSourceRange());
11684}
11685
11686bool
11687CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
11688 SourceLocation Loc,
11689 const char *startSpec,
11690 unsigned specifierLen,
11691 const char *csStart,
11692 unsigned csLen) {
11693 bool keepGoing = true;
11694 if (argIndex < NumDataArgs) {
11695 // Consider the argument coverered, even though the specifier doesn't
11696 // make sense.
11697 CoveredArgs.set(argIndex);
11698 }
11699 else {
11700 // If argIndex exceeds the number of data arguments we
11701 // don't issue a warning because that is just a cascade of warnings (and
11702 // they may have intended '%%' anyway). We don't want to continue processing
11703 // the format string after this point, however, as we will like just get
11704 // gibberish when trying to match arguments.
11705 keepGoing = false;
11706 }
11707
11708 StringRef Specifier(csStart, csLen);
11709
11710 // If the specifier in non-printable, it could be the first byte of a UTF-8
11711 // sequence. In that case, print the UTF-8 code point. If not, print the byte
11712 // hex value.
11713 std::string CodePointStr;
11714 if (!llvm::sys::locale::isPrint(*csStart)) {
11715 llvm::UTF32 CodePoint;
11716 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
11717 const llvm::UTF8 *E =
11718 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
11719 llvm::ConversionResult Result =
11720 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
11721
11722 if (Result != llvm::conversionOK) {
11723 unsigned char FirstChar = *csStart;
11724 CodePoint = (llvm::UTF32)FirstChar;
11725 }
11726
11727 llvm::raw_string_ostream OS(CodePointStr);
11728 if (CodePoint < 256)
11729 OS << "\\x" << llvm::format("%02x", CodePoint);
11730 else if (CodePoint <= 0xFFFF)
11731 OS << "\\u" << llvm::format("%04x", CodePoint);
11732 else
11733 OS << "\\U" << llvm::format("%08x", CodePoint);
11734 OS.flush();
11735 Specifier = CodePointStr;
11736 }
11737
11738 EmitFormatDiagnostic(
11739 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
11740 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
11741
11742 return keepGoing;
11743}
11744
11745void
11746CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
11747 const char *startSpec,
11748 unsigned specifierLen) {
11749 EmitFormatDiagnostic(
11750 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
11751 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
11752}
11753
11754bool
11755CheckFormatHandler::CheckNumArgs(
11758 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
11759
11760 if (argIndex >= NumDataArgs) {
11761 PartialDiagnostic PDiag = FS.usesPositionalArg()
11762 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
11763 << (argIndex+1) << NumDataArgs)
11764 : S.PDiag(diag::warn_printf_insufficient_data_args);
11765 EmitFormatDiagnostic(
11766 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
11767 getSpecifierRange(startSpecifier, specifierLen));
11768
11769 // Since more arguments than conversion tokens are given, by extension
11770 // all arguments are covered, so mark this as so.
11771 UncoveredArg.setAllCovered();
11772 return false;
11773 }
11774 return true;
11775}
11776
11777template<typename Range>
11778void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
11779 SourceLocation Loc,
11780 bool IsStringLocation,
11781 Range StringRange,
11782 ArrayRef<FixItHint> FixIt) {
11783 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
11784 Loc, IsStringLocation, StringRange, FixIt);
11785}
11786
11787/// If the format string is not within the function call, emit a note
11788/// so that the function call and string are in diagnostic messages.
11789///
11790/// \param InFunctionCall if true, the format string is within the function
11791/// call and only one diagnostic message will be produced. Otherwise, an
11792/// extra note will be emitted pointing to location of the format string.
11793///
11794/// \param ArgumentExpr the expression that is passed as the format string
11795/// argument in the function call. Used for getting locations when two
11796/// diagnostics are emitted.
11797///
11798/// \param PDiag the callee should already have provided any strings for the
11799/// diagnostic message. This function only adds locations and fixits
11800/// to diagnostics.
11801///
11802/// \param Loc primary location for diagnostic. If two diagnostics are
11803/// required, one will be at Loc and a new SourceLocation will be created for
11804/// the other one.
11805///
11806/// \param IsStringLocation if true, Loc points to the format string should be
11807/// used for the note. Otherwise, Loc points to the argument list and will
11808/// be used with PDiag.
11809///
11810/// \param StringRange some or all of the string to highlight. This is
11811/// templated so it can accept either a CharSourceRange or a SourceRange.
11812///
11813/// \param FixIt optional fix it hint for the format string.
11814template <typename Range>
11815void CheckFormatHandler::EmitFormatDiagnostic(
11816 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
11817 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
11818 Range StringRange, ArrayRef<FixItHint> FixIt) {
11819 if (InFunctionCall) {
11820 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
11821 D << StringRange;
11822 D << FixIt;
11823 } else {
11824 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
11825 << ArgumentExpr->getSourceRange();
11826
11828 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
11829 diag::note_format_string_defined);
11830
11831 Note << StringRange;
11832 Note << FixIt;
11833 }
11834}
11835
11836//===--- CHECK: Printf format string checking -----------------------------===//
11837
11838namespace {
11839
11840class CheckPrintfHandler : public CheckFormatHandler {
11841public:
11842 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
11843 const Expr *origFormatExpr,
11844 const Sema::FormatStringType type, unsigned firstDataArg,
11845 unsigned numDataArgs, bool isObjC, const char *beg,
11847 ArrayRef<const Expr *> Args, unsigned formatIdx,
11848 bool inFunctionCall, Sema::VariadicCallType CallType,
11849 llvm::SmallBitVector &CheckedVarArgs,
11850 UncoveredArgHandler &UncoveredArg)
11851 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
11852 numDataArgs, beg, APK, Args, formatIdx,
11853 inFunctionCall, CallType, CheckedVarArgs,
11854 UncoveredArg) {}
11855
11856 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
11857
11858 /// Returns true if '%@' specifiers are allowed in the format string.
11859 bool allowsObjCArg() const {
11860 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
11861 FSType == Sema::FST_OSTrace;
11862 }
11863
11864 bool HandleInvalidPrintfConversionSpecifier(
11866 const char *startSpecifier,
11867 unsigned specifierLen) override;
11868
11869 void handleInvalidMaskType(StringRef MaskType) override;
11870
11871 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
11872 const char *startSpecifier, unsigned specifierLen,
11873 const TargetInfo &Target) override;
11874 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
11875 const char *StartSpecifier,
11876 unsigned SpecifierLen,
11877 const Expr *E);
11878
11879 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
11880 const char *startSpecifier, unsigned specifierLen);
11881 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
11883 unsigned type,
11884 const char *startSpecifier, unsigned specifierLen);
11885 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
11886 const analyze_printf::OptionalFlag &flag,
11887 const char *startSpecifier, unsigned specifierLen);
11888 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
11889 const analyze_printf::OptionalFlag &ignoredFlag,
11890 const analyze_printf::OptionalFlag &flag,
11891 const char *startSpecifier, unsigned specifierLen);
11892 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
11893 const Expr *E);
11894
11895 void HandleEmptyObjCModifierFlag(const char *startFlag,
11896 unsigned flagLen) override;
11897
11898 void HandleInvalidObjCModifierFlag(const char *startFlag,
11899 unsigned flagLen) override;
11900
11901 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
11902 const char *flagsEnd,
11903 const char *conversionPosition)
11904 override;
11905};
11906
11907} // namespace
11908
11909bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
11911 const char *startSpecifier,
11912 unsigned specifierLen) {
11914 FS.getConversionSpecifier();
11915
11916 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
11917 getLocationOfByte(CS.getStart()),
11918 startSpecifier, specifierLen,
11919 CS.getStart(), CS.getLength());
11920}
11921
11922void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
11923 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
11924}
11925
11926bool CheckPrintfHandler::HandleAmount(
11927 const analyze_format_string::OptionalAmount &Amt, unsigned k,
11928 const char *startSpecifier, unsigned specifierLen) {
11929 if (Amt.hasDataArgument()) {
11930 if (ArgPassingKind != Sema::FAPK_VAList) {
11931 unsigned argIndex = Amt.getArgIndex();
11932 if (argIndex >= NumDataArgs) {
11933 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
11934 << k,
11935 getLocationOfByte(Amt.getStart()),
11936 /*IsStringLocation*/ true,
11937 getSpecifierRange(startSpecifier, specifierLen));
11938 // Don't do any more checking. We will just emit
11939 // spurious errors.
11940 return false;
11941 }
11942
11943 // Type check the data argument. It should be an 'int'.
11944 // Although not in conformance with C99, we also allow the argument to be
11945 // an 'unsigned int' as that is a reasonably safe case. GCC also
11946 // doesn't emit a warning for that case.
11947 CoveredArgs.set(argIndex);
11948 const Expr *Arg = getDataArg(argIndex);
11949 if (!Arg)
11950 return false;
11951
11952 QualType T = Arg->getType();
11953
11954 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
11955 assert(AT.isValid());
11956
11957 if (!AT.matchesType(S.Context, T)) {
11958 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
11960 << T << Arg->getSourceRange(),
11961 getLocationOfByte(Amt.getStart()),
11962 /*IsStringLocation*/true,
11963 getSpecifierRange(startSpecifier, specifierLen));
11964 // Don't do any more checking. We will just emit
11965 // spurious errors.
11966 return false;
11967 }
11968 }
11969 }
11970 return true;
11971}
11972
11973void CheckPrintfHandler::HandleInvalidAmount(
11976 unsigned type,
11977 const char *startSpecifier,
11978 unsigned specifierLen) {
11980 FS.getConversionSpecifier();
11981
11982 FixItHint fixit =
11984 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
11985 Amt.getConstantLength()))
11986 : FixItHint();
11987
11988 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
11989 << type << CS.toString(),
11990 getLocationOfByte(Amt.getStart()),
11991 /*IsStringLocation*/true,
11992 getSpecifierRange(startSpecifier, specifierLen),
11993 fixit);
11994}
11995
11996void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
11997 const analyze_printf::OptionalFlag &flag,
11998 const char *startSpecifier,
11999 unsigned specifierLen) {
12000 // Warn about pointless flag with a fixit removal.
12002 FS.getConversionSpecifier();
12003 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
12004 << flag.toString() << CS.toString(),
12005 getLocationOfByte(flag.getPosition()),
12006 /*IsStringLocation*/true,
12007 getSpecifierRange(startSpecifier, specifierLen),
12009 getSpecifierRange(flag.getPosition(), 1)));
12010}
12011
12012void CheckPrintfHandler::HandleIgnoredFlag(
12014 const analyze_printf::OptionalFlag &ignoredFlag,
12015 const analyze_printf::OptionalFlag &flag,
12016 const char *startSpecifier,
12017 unsigned specifierLen) {
12018 // Warn about ignored flag with a fixit removal.
12019 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
12020 << ignoredFlag.toString() << flag.toString(),
12021 getLocationOfByte(ignoredFlag.getPosition()),
12022 /*IsStringLocation*/true,
12023 getSpecifierRange(startSpecifier, specifierLen),
12025 getSpecifierRange(ignoredFlag.getPosition(), 1)));
12026}
12027
12028void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
12029 unsigned flagLen) {
12030 // Warn about an empty flag.
12031 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
12032 getLocationOfByte(startFlag),
12033 /*IsStringLocation*/true,
12034 getSpecifierRange(startFlag, flagLen));
12035}
12036
12037void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
12038 unsigned flagLen) {
12039 // Warn about an invalid flag.
12040 auto Range = getSpecifierRange(startFlag, flagLen);
12041 StringRef flag(startFlag, flagLen);
12042 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
12043 getLocationOfByte(startFlag),
12044 /*IsStringLocation*/true,
12045 Range, FixItHint::CreateRemoval(Range));
12046}
12047
12048void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
12049 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
12050 // Warn about using '[...]' without a '@' conversion.
12051 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
12052 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
12053 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
12054 getLocationOfByte(conversionPosition),
12055 /*IsStringLocation*/true,
12056 Range, FixItHint::CreateRemoval(Range));
12057}
12058
12059// Determines if the specified is a C++ class or struct containing
12060// a member with the specified name and kind (e.g. a CXXMethodDecl named
12061// "c_str()").
12062template<typename MemberKind>
12064CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
12065 const RecordType *RT = Ty->getAs<RecordType>();
12067
12068 if (!RT)
12069 return Results;
12070 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
12071 if (!RD || !RD->getDefinition())
12072 return Results;
12073
12074 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
12077
12078 // We just need to include all members of the right kind turned up by the
12079 // filter, at this point.
12080 if (S.LookupQualifiedName(R, RT->getDecl()))
12081 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12082 NamedDecl *decl = (*I)->getUnderlyingDecl();
12083 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
12084 Results.insert(FK);
12085 }
12086 return Results;
12087}
12088
12089/// Check if we could call '.c_str()' on an object.
12090///
12091/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
12092/// allow the call, or if it would be ambiguous).
12094 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
12095
12096 MethodSet Results =
12097 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
12098 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
12099 MI != ME; ++MI)
12100 if ((*MI)->getMinRequiredArguments() == 0)
12101 return true;
12102 return false;
12103}
12104
12105// Check if a (w)string was passed when a (w)char* was needed, and offer a
12106// better diagnostic if so. AT is assumed to be valid.
12107// Returns true when a c_str() conversion method is found.
12108bool CheckPrintfHandler::checkForCStrMembers(
12109 const analyze_printf::ArgType &AT, const Expr *E) {
12110 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
12111
12112 MethodSet Results =
12113 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
12114
12115 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
12116 MI != ME; ++MI) {
12117 const CXXMethodDecl *Method = *MI;
12118 if (Method->getMinRequiredArguments() == 0 &&
12119 AT.matchesType(S.Context, Method->getReturnType())) {
12120 // FIXME: Suggest parens if the expression needs them.
12122 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
12123 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
12124 return true;
12125 }
12126 }
12127
12128 return false;
12129}
12130
12131bool CheckPrintfHandler::HandlePrintfSpecifier(
12132 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
12133 unsigned specifierLen, const TargetInfo &Target) {
12134 using namespace analyze_format_string;
12135 using namespace analyze_printf;
12136
12137 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
12138
12139 if (FS.consumesDataArgument()) {
12140 if (atFirstArg) {
12141 atFirstArg = false;
12142 usesPositionalArgs = FS.usesPositionalArg();
12143 }
12144 else if (usesPositionalArgs != FS.usesPositionalArg()) {
12145 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
12146 startSpecifier, specifierLen);
12147 return false;
12148 }
12149 }
12150
12151 // First check if the field width, precision, and conversion specifier
12152 // have matching data arguments.
12153 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
12154 startSpecifier, specifierLen)) {
12155 return false;
12156 }
12157
12158 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
12159 startSpecifier, specifierLen)) {
12160 return false;
12161 }
12162
12163 if (!CS.consumesDataArgument()) {
12164 // FIXME: Technically specifying a precision or field width here
12165 // makes no sense. Worth issuing a warning at some point.
12166 return true;
12167 }
12168
12169 // Consume the argument.
12170 unsigned argIndex = FS.getArgIndex();
12171 if (argIndex < NumDataArgs) {
12172 // The check to see if the argIndex is valid will come later.
12173 // We set the bit here because we may exit early from this
12174 // function if we encounter some other error.
12175 CoveredArgs.set(argIndex);
12176 }
12177
12178 // FreeBSD kernel extensions.
12179 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
12180 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
12181 // We need at least two arguments.
12182 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
12183 return false;
12184
12185 // Claim the second argument.
12186 CoveredArgs.set(argIndex + 1);
12187
12188 // Type check the first argument (int for %b, pointer for %D)
12189 const Expr *Ex = getDataArg(argIndex);
12190 const analyze_printf::ArgType &AT =
12191 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
12192 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
12193 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
12194 EmitFormatDiagnostic(
12195 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
12196 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
12197 << false << Ex->getSourceRange(),
12198 Ex->getBeginLoc(), /*IsStringLocation*/ false,
12199 getSpecifierRange(startSpecifier, specifierLen));
12200
12201 // Type check the second argument (char * for both %b and %D)
12202 Ex = getDataArg(argIndex + 1);
12203 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
12204 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
12205 EmitFormatDiagnostic(
12206 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
12207 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
12208 << false << Ex->getSourceRange(),
12209 Ex->getBeginLoc(), /*IsStringLocation*/ false,
12210 getSpecifierRange(startSpecifier, specifierLen));
12211
12212 return true;
12213 }
12214
12215 // Check for using an Objective-C specific conversion specifier
12216 // in a non-ObjC literal.
12217 if (!allowsObjCArg() && CS.isObjCArg()) {
12218 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
12219 specifierLen);
12220 }
12221
12222 // %P can only be used with os_log.
12223 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
12224 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
12225 specifierLen);
12226 }
12227
12228 // %n is not allowed with os_log.
12229 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
12230 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
12231 getLocationOfByte(CS.getStart()),
12232 /*IsStringLocation*/ false,
12233 getSpecifierRange(startSpecifier, specifierLen));
12234
12235 return true;
12236 }
12237
12238 // Only scalars are allowed for os_trace.
12239 if (FSType == Sema::FST_OSTrace &&
12240 (CS.getKind() == ConversionSpecifier::PArg ||
12241 CS.getKind() == ConversionSpecifier::sArg ||
12242 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
12243 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
12244 specifierLen);
12245 }
12246
12247 // Check for use of public/private annotation outside of os_log().
12248 if (FSType != Sema::FST_OSLog) {
12249 if (FS.isPublic().isSet()) {
12250 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
12251 << "public",
12252 getLocationOfByte(FS.isPublic().getPosition()),
12253 /*IsStringLocation*/ false,
12254 getSpecifierRange(startSpecifier, specifierLen));
12255 }
12256 if (FS.isPrivate().isSet()) {
12257 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
12258 << "private",
12259 getLocationOfByte(FS.isPrivate().getPosition()),
12260 /*IsStringLocation*/ false,
12261 getSpecifierRange(startSpecifier, specifierLen));
12262 }
12263 }
12264
12265 const llvm::Triple &Triple = Target.getTriple();
12266 if (CS.getKind() == ConversionSpecifier::nArg &&
12267 (Triple.isAndroid() || Triple.isOSFuchsia())) {
12268 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
12269 getLocationOfByte(CS.getStart()),
12270 /*IsStringLocation*/ false,
12271 getSpecifierRange(startSpecifier, specifierLen));
12272 }
12273
12274 // Check for invalid use of field width
12275 if (!FS.hasValidFieldWidth()) {
12276 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
12277 startSpecifier, specifierLen);
12278 }
12279
12280 // Check for invalid use of precision
12281 if (!FS.hasValidPrecision()) {
12282 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
12283 startSpecifier, specifierLen);
12284 }
12285
12286 // Precision is mandatory for %P specifier.
12287 if (CS.getKind() == ConversionSpecifier::PArg &&
12288 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
12289 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
12290 getLocationOfByte(startSpecifier),
12291 /*IsStringLocation*/ false,
12292 getSpecifierRange(startSpecifier, specifierLen));
12293 }
12294
12295 // Check each flag does not conflict with any other component.
12296 if (!FS.hasValidThousandsGroupingPrefix())
12297 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
12298 if (!FS.hasValidLeadingZeros())
12299 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
12300 if (!FS.hasValidPlusPrefix())
12301 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
12302 if (!FS.hasValidSpacePrefix())
12303 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
12304 if (!FS.hasValidAlternativeForm())
12305 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
12306 if (!FS.hasValidLeftJustified())
12307 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
12308
12309 // Check that flags are not ignored by another flag
12310 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
12311 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
12312 startSpecifier, specifierLen);
12313 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
12314 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
12315 startSpecifier, specifierLen);
12316
12317 // Check the length modifier is valid with the given conversion specifier.
12318 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
12319 S.getLangOpts()))
12320 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
12321 diag::warn_format_nonsensical_length);
12322 else if (!FS.hasStandardLengthModifier())
12323 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
12324 else if (!FS.hasStandardLengthConversionCombination())
12325 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
12326 diag::warn_format_non_standard_conversion_spec);
12327
12328 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
12329 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
12330
12331 // The remaining checks depend on the data arguments.
12332 if (ArgPassingKind == Sema::FAPK_VAList)
12333 return true;
12334
12335 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
12336 return false;
12337
12338 const Expr *Arg = getDataArg(argIndex);
12339 if (!Arg)
12340 return true;
12341
12342 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
12343}
12344
12345static bool requiresParensToAddCast(const Expr *E) {
12346 // FIXME: We should have a general way to reason about operator
12347 // precedence and whether parens are actually needed here.
12348 // Take care of a few common cases where they aren't.
12349 const Expr *Inside = E->IgnoreImpCasts();
12350 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
12351 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
12352
12353 switch (Inside->getStmtClass()) {
12354 case Stmt::ArraySubscriptExprClass:
12355 case Stmt::CallExprClass:
12356 case Stmt::CharacterLiteralClass:
12357 case Stmt::CXXBoolLiteralExprClass:
12358 case Stmt::DeclRefExprClass:
12359 case Stmt::FloatingLiteralClass:
12360 case Stmt::IntegerLiteralClass:
12361 case Stmt::MemberExprClass:
12362 case Stmt::ObjCArrayLiteralClass:
12363 case Stmt::ObjCBoolLiteralExprClass:
12364 case Stmt::ObjCBoxedExprClass:
12365 case Stmt::ObjCDictionaryLiteralClass:
12366 case Stmt::ObjCEncodeExprClass:
12367 case Stmt::ObjCIvarRefExprClass:
12368 case Stmt::ObjCMessageExprClass:
12369 case Stmt::ObjCPropertyRefExprClass:
12370 case Stmt::ObjCStringLiteralClass:
12371 case Stmt::ObjCSubscriptRefExprClass:
12372 case Stmt::ParenExprClass:
12373 case Stmt::StringLiteralClass:
12374 case Stmt::UnaryOperatorClass:
12375 return false;
12376 default:
12377 return true;
12378 }
12379}
12380
12381static std::pair<QualType, StringRef>
12383 QualType IntendedTy,
12384 const Expr *E) {
12385 // Use a 'while' to peel off layers of typedefs.
12386 QualType TyTy = IntendedTy;
12387 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
12388 StringRef Name = UserTy->getDecl()->getName();
12389 QualType CastTy = llvm::StringSwitch<QualType>(Name)
12390 .Case("CFIndex", Context.getNSIntegerType())
12391 .Case("NSInteger", Context.getNSIntegerType())
12392 .Case("NSUInteger", Context.getNSUIntegerType())
12393 .Case("SInt32", Context.IntTy)
12394 .Case("UInt32", Context.UnsignedIntTy)
12395 .Default(QualType());
12396
12397 if (!CastTy.isNull())
12398 return std::make_pair(CastTy, Name);
12399
12400 TyTy = UserTy->desugar();
12401 }
12402
12403 // Strip parens if necessary.
12404 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
12405 return shouldNotPrintDirectly(Context,
12406 PE->getSubExpr()->getType(),
12407 PE->getSubExpr());
12408
12409 // If this is a conditional expression, then its result type is constructed
12410 // via usual arithmetic conversions and thus there might be no necessary
12411 // typedef sugar there. Recurse to operands to check for NSInteger &
12412 // Co. usage condition.
12413 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12414 QualType TrueTy, FalseTy;
12415 StringRef TrueName, FalseName;
12416
12417 std::tie(TrueTy, TrueName) =
12418 shouldNotPrintDirectly(Context,
12419 CO->getTrueExpr()->getType(),
12420 CO->getTrueExpr());
12421 std::tie(FalseTy, FalseName) =
12422 shouldNotPrintDirectly(Context,
12423 CO->getFalseExpr()->getType(),
12424 CO->getFalseExpr());
12425
12426 if (TrueTy == FalseTy)
12427 return std::make_pair(TrueTy, TrueName);
12428 else if (TrueTy.isNull())
12429 return std::make_pair(FalseTy, FalseName);
12430 else if (FalseTy.isNull())
12431 return std::make_pair(TrueTy, TrueName);
12432 }
12433
12434 return std::make_pair(QualType(), StringRef());
12435}
12436
12437/// Return true if \p ICE is an implicit argument promotion of an arithmetic
12438/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
12439/// type do not count.
12440static bool
12442 QualType From = ICE->getSubExpr()->getType();
12443 QualType To = ICE->getType();
12444 // It's an integer promotion if the destination type is the promoted
12445 // source type.
12446 if (ICE->getCastKind() == CK_IntegralCast &&
12448 S.Context.getPromotedIntegerType(From) == To)
12449 return true;
12450 // Look through vector types, since we do default argument promotion for
12451 // those in OpenCL.
12452 if (const auto *VecTy = From->getAs<ExtVectorType>())
12453 From = VecTy->getElementType();
12454 if (const auto *VecTy = To->getAs<ExtVectorType>())
12455 To = VecTy->getElementType();
12456 // It's a floating promotion if the source type is a lower rank.
12457 return ICE->getCastKind() == CK_FloatingCast &&
12458 S.Context.getFloatingTypeOrder(From, To) < 0;
12459}
12460
12463 DiagnosticsEngine &Diags, SourceLocation Loc) {
12465 Match =
12466 Diags.isIgnored(
12467 diag::warn_format_conversion_argument_type_mismatch_signedness, Loc)
12470 }
12471 return Match;
12472}
12473
12474bool
12475CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
12476 const char *StartSpecifier,
12477 unsigned SpecifierLen,
12478 const Expr *E) {
12479 using namespace analyze_format_string;
12480 using namespace analyze_printf;
12481
12482 // Now type check the data expression that matches the
12483 // format specifier.
12484 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
12485 if (!AT.isValid())
12486 return true;
12487
12488 QualType ExprTy = E->getType();
12489 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
12490 ExprTy = TET->getUnderlyingExpr()->getType();
12491 }
12492
12493 // When using the format attribute in C++, you can receive a function or an
12494 // array that will necessarily decay to a pointer when passed to the final
12495 // format consumer. Apply decay before type comparison.
12496 if (ExprTy->canDecayToPointerType())
12497 ExprTy = S.Context.getDecayedType(ExprTy);
12498
12499 // Diagnose attempts to print a boolean value as a character. Unlike other
12500 // -Wformat diagnostics, this is fine from a type perspective, but it still
12501 // doesn't make sense.
12502 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
12504 const CharSourceRange &CSR =
12505 getSpecifierRange(StartSpecifier, SpecifierLen);
12506 SmallString<4> FSString;
12507 llvm::raw_svector_ostream os(FSString);
12508 FS.toString(os);
12509 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
12510 << FSString,
12511 E->getExprLoc(), false, CSR);
12512 return true;
12513 }
12514
12515 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
12516 ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
12517 ArgType::MatchKind OrigMatch = Match;
12518
12519 Match = handleFormatSignedness(Match, S.getDiagnostics(), E->getExprLoc());
12520 if (Match == ArgType::Match)
12521 return true;
12522
12523 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
12524 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
12525
12526 // Look through argument promotions for our error message's reported type.
12527 // This includes the integral and floating promotions, but excludes array
12528 // and function pointer decay (seeing that an argument intended to be a
12529 // string has type 'char [6]' is probably more confusing than 'char *') and
12530 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
12531 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12532 if (isArithmeticArgumentPromotion(S, ICE)) {
12533 E = ICE->getSubExpr();
12534 ExprTy = E->getType();
12535
12536 // Check if we didn't match because of an implicit cast from a 'char'
12537 // or 'short' to an 'int'. This is done because printf is a varargs
12538 // function.
12539 if (ICE->getType() == S.Context.IntTy ||
12540 ICE->getType() == S.Context.UnsignedIntTy) {
12541 // All further checking is done on the subexpression
12542 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
12543 if (OrigMatch == ArgType::NoMatchSignedness &&
12544 ImplicitMatch != ArgType::NoMatchSignedness)
12545 // If the original match was a signedness match this match on the
12546 // implicit cast type also need to be signedness match otherwise we
12547 // might introduce new unexpected warnings from -Wformat-signedness.
12548 return true;
12549 ImplicitMatch = handleFormatSignedness(
12550 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
12551 if (ImplicitMatch == ArgType::Match)
12552 return true;
12553 }
12554 }
12555 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
12556 // Special case for 'a', which has type 'int' in C.
12557 // Note, however, that we do /not/ want to treat multibyte constants like
12558 // 'MooV' as characters! This form is deprecated but still exists. In
12559 // addition, don't treat expressions as of type 'char' if one byte length
12560 // modifier is provided.
12561 if (ExprTy == S.Context.IntTy &&
12562 FS.getLengthModifier().getKind() != LengthModifier::AsChar)
12563 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
12564 ExprTy = S.Context.CharTy;
12565 // To improve check results, we consider a character literal in C
12566 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
12567 // more likely a type confusion situation, so we will suggest to
12568 // use '%hhd' instead by discarding the MatchPromotion.
12569 if (Match == ArgType::MatchPromotion)
12570 Match = ArgType::NoMatch;
12571 }
12572 }
12573 if (Match == ArgType::MatchPromotion) {
12574 // WG14 N2562 only clarified promotions in *printf
12575 // For NSLog in ObjC, just preserve -Wformat behavior
12576 if (!S.getLangOpts().ObjC &&
12577 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
12578 ImplicitMatch != ArgType::NoMatchTypeConfusion)
12579 return true;
12580 Match = ArgType::NoMatch;
12581 }
12582 if (ImplicitMatch == ArgType::NoMatchPedantic ||
12583 ImplicitMatch == ArgType::NoMatchTypeConfusion)
12584 Match = ImplicitMatch;
12585 assert(Match != ArgType::MatchPromotion);
12586
12587 // Look through unscoped enums to their underlying type.
12588 bool IsEnum = false;
12589 bool IsScopedEnum = false;
12590 QualType IntendedTy = ExprTy;
12591 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
12592 IntendedTy = EnumTy->getDecl()->getIntegerType();
12593 if (EnumTy->isUnscopedEnumerationType()) {
12594 ExprTy = IntendedTy;
12595 // This controls whether we're talking about the underlying type or not,
12596 // which we only want to do when it's an unscoped enum.
12597 IsEnum = true;
12598 } else {
12599 IsScopedEnum = true;
12600 }
12601 }
12602
12603 // %C in an Objective-C context prints a unichar, not a wchar_t.
12604 // If the argument is an integer of some kind, believe the %C and suggest
12605 // a cast instead of changing the conversion specifier.
12606 if (isObjCContext() &&
12607 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
12609 !ExprTy->isCharType()) {
12610 // 'unichar' is defined as a typedef of unsigned short, but we should
12611 // prefer using the typedef if it is visible.
12612 IntendedTy = S.Context.UnsignedShortTy;
12613
12614 // While we are here, check if the value is an IntegerLiteral that happens
12615 // to be within the valid range.
12616 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
12617 const llvm::APInt &V = IL->getValue();
12618 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
12619 return true;
12620 }
12621
12622 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
12624 if (S.LookupName(Result, S.getCurScope())) {
12625 NamedDecl *ND = Result.getFoundDecl();
12626 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
12627 if (TD->getUnderlyingType() == IntendedTy)
12628 IntendedTy = S.Context.getTypedefType(TD);
12629 }
12630 }
12631 }
12632
12633 // Special-case some of Darwin's platform-independence types by suggesting
12634 // casts to primitive types that are known to be large enough.
12635 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
12636 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
12637 QualType CastTy;
12638 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
12639 if (!CastTy.isNull()) {
12640 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
12641 // (long in ASTContext). Only complain to pedants or when they're the
12642 // underlying type of a scoped enum (which always needs a cast).
12643 if (!IsScopedEnum &&
12644 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
12645 (AT.isSizeT() || AT.isPtrdiffT()) &&
12646 AT.matchesType(S.Context, CastTy))
12647 Match = ArgType::NoMatchPedantic;
12648 IntendedTy = CastTy;
12649 ShouldNotPrintDirectly = true;
12650 }
12651 }
12652
12653 // We may be able to offer a FixItHint if it is a supported type.
12654 PrintfSpecifier fixedFS = FS;
12655 bool Success =
12656 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
12657
12658 if (Success) {
12659 // Get the fix string from the fixed format specifier
12660 SmallString<16> buf;
12661 llvm::raw_svector_ostream os(buf);
12662 fixedFS.toString(os);
12663
12664 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
12665
12666 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
12667 unsigned Diag;
12668 switch (Match) {
12669 case ArgType::Match:
12670 case ArgType::MatchPromotion:
12671 case ArgType::NoMatchPromotionTypeConfusion:
12672 case ArgType::NoMatchSignedness:
12673 llvm_unreachable("expected non-matching");
12674 case ArgType::NoMatchPedantic:
12675 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
12676 break;
12677 case ArgType::NoMatchTypeConfusion:
12678 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
12679 break;
12680 case ArgType::NoMatch:
12681 Diag = diag::warn_format_conversion_argument_type_mismatch;
12682 break;
12683 }
12684
12685 // In this case, the specifier is wrong and should be changed to match
12686 // the argument.
12687 EmitFormatDiagnostic(S.PDiag(Diag)
12689 << IntendedTy << IsEnum << E->getSourceRange(),
12690 E->getBeginLoc(),
12691 /*IsStringLocation*/ false, SpecRange,
12692 FixItHint::CreateReplacement(SpecRange, os.str()));
12693 } else {
12694 // The canonical type for formatting this value is different from the
12695 // actual type of the expression. (This occurs, for example, with Darwin's
12696 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
12697 // should be printed as 'long' for 64-bit compatibility.)
12698 // Rather than emitting a normal format/argument mismatch, we want to
12699 // add a cast to the recommended type (and correct the format string
12700 // if necessary). We should also do so for scoped enumerations.
12701 SmallString<16> CastBuf;
12702 llvm::raw_svector_ostream CastFix(CastBuf);
12703 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
12704 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
12705 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
12706
12708 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
12709 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
12710 E->getExprLoc());
12711 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
12712 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
12713
12714 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
12715 // If there's already a cast present, just replace it.
12716 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
12717 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
12718
12719 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
12720 // If the expression has high enough precedence,
12721 // just write the C-style cast.
12722 Hints.push_back(
12723 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
12724 } else {
12725 // Otherwise, add parens around the expression as well as the cast.
12726 CastFix << "(";
12727 Hints.push_back(
12728 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
12729
12730 // We don't use getLocForEndOfToken because it returns invalid source
12731 // locations for macro expansions (by design).
12735 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
12736 }
12737
12738 if (ShouldNotPrintDirectly && !IsScopedEnum) {
12739 // The expression has a type that should not be printed directly.
12740 // We extract the name from the typedef because we don't want to show
12741 // the underlying type in the diagnostic.
12742 StringRef Name;
12743 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
12744 Name = TypedefTy->getDecl()->getName();
12745 else
12746 Name = CastTyName;
12747 unsigned Diag = Match == ArgType::NoMatchPedantic
12748 ? diag::warn_format_argument_needs_cast_pedantic
12749 : diag::warn_format_argument_needs_cast;
12750 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
12751 << E->getSourceRange(),
12752 E->getBeginLoc(), /*IsStringLocation=*/false,
12753 SpecRange, Hints);
12754 } else {
12755 // In this case, the expression could be printed using a different
12756 // specifier, but we've decided that the specifier is probably correct
12757 // and we should cast instead. Just use the normal warning message.
12758 EmitFormatDiagnostic(
12759 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
12760 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
12761 << E->getSourceRange(),
12762 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
12763 }
12764 }
12765 } else {
12766 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
12767 SpecifierLen);
12768 // Since the warning for passing non-POD types to variadic functions
12769 // was deferred until now, we emit a warning for non-POD
12770 // arguments here.
12771 bool EmitTypeMismatch = false;
12772 switch (S.isValidVarArgType(ExprTy)) {
12773 case Sema::VAK_Valid:
12775 unsigned Diag;
12776 switch (Match) {
12777 case ArgType::Match:
12778 case ArgType::MatchPromotion:
12779 case ArgType::NoMatchPromotionTypeConfusion:
12780 case ArgType::NoMatchSignedness:
12781 llvm_unreachable("expected non-matching");
12782 case ArgType::NoMatchPedantic:
12783 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
12784 break;
12785 case ArgType::NoMatchTypeConfusion:
12786 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
12787 break;
12788 case ArgType::NoMatch:
12789 Diag = diag::warn_format_conversion_argument_type_mismatch;
12790 break;
12791 }
12792
12793 EmitFormatDiagnostic(
12794 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
12795 << IsEnum << CSR << E->getSourceRange(),
12796 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
12797 break;
12798 }
12801 if (CallType == Sema::VariadicDoesNotApply) {
12802 EmitTypeMismatch = true;
12803 } else {
12804 EmitFormatDiagnostic(
12805 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
12806 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
12807 << AT.getRepresentativeTypeName(S.Context) << CSR
12808 << E->getSourceRange(),
12809 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
12810 checkForCStrMembers(AT, E);
12811 }
12812 break;
12813
12814 case Sema::VAK_Invalid:
12815 if (CallType == Sema::VariadicDoesNotApply)
12816 EmitTypeMismatch = true;
12817 else if (ExprTy->isObjCObjectType())
12818 EmitFormatDiagnostic(
12819 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
12820 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
12821 << AT.getRepresentativeTypeName(S.Context) << CSR
12822 << E->getSourceRange(),
12823 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
12824 else
12825 // FIXME: If this is an initializer list, suggest removing the braces
12826 // or inserting a cast to the target type.
12827 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
12828 << isa<InitListExpr>(E) << ExprTy << CallType
12830 break;
12831 }
12832
12833 if (EmitTypeMismatch) {
12834 // The function is not variadic, so we do not generate warnings about
12835 // being allowed to pass that object as a variadic argument. Instead,
12836 // since there are inherently no printf specifiers for types which cannot
12837 // be passed as variadic arguments, emit a plain old specifier mismatch
12838 // argument.
12839 EmitFormatDiagnostic(
12840 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
12841 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
12842 << E->getSourceRange(),
12843 E->getBeginLoc(), false, CSR);
12844 }
12845
12846 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
12847 "format string specifier index out of range");
12848 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
12849 }
12850
12851 return true;
12852}
12853
12854//===--- CHECK: Scanf format string checking ------------------------------===//
12855
12856namespace {
12857
12858class CheckScanfHandler : public CheckFormatHandler {
12859public:
12860 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
12861 const Expr *origFormatExpr, Sema::FormatStringType type,
12862 unsigned firstDataArg, unsigned numDataArgs,
12863 const char *beg, Sema::FormatArgumentPassingKind APK,
12864 ArrayRef<const Expr *> Args, unsigned formatIdx,
12865 bool inFunctionCall, Sema::VariadicCallType CallType,
12866 llvm::SmallBitVector &CheckedVarArgs,
12867 UncoveredArgHandler &UncoveredArg)
12868 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
12869 numDataArgs, beg, APK, Args, formatIdx,
12870 inFunctionCall, CallType, CheckedVarArgs,
12871 UncoveredArg) {}
12872
12873 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
12874 const char *startSpecifier,
12875 unsigned specifierLen) override;
12876
12877 bool HandleInvalidScanfConversionSpecifier(
12879 const char *startSpecifier,
12880 unsigned specifierLen) override;
12881
12882 void HandleIncompleteScanList(const char *start, const char *end) override;
12883};
12884
12885} // namespace
12886
12887void CheckScanfHandler::HandleIncompleteScanList(const char *start,
12888 const char *end) {
12889 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
12890 getLocationOfByte(end), /*IsStringLocation*/true,
12891 getSpecifierRange(start, end - start));
12892}
12893
12894bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
12896 const char *startSpecifier,
12897 unsigned specifierLen) {
12899 FS.getConversionSpecifier();
12900
12901 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
12902 getLocationOfByte(CS.getStart()),
12903 startSpecifier, specifierLen,
12904 CS.getStart(), CS.getLength());
12905}
12906
12907bool CheckScanfHandler::HandleScanfSpecifier(
12909 const char *startSpecifier,
12910 unsigned specifierLen) {
12911 using namespace analyze_scanf;
12912 using namespace analyze_format_string;
12913
12914 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
12915
12916 // Handle case where '%' and '*' don't consume an argument. These shouldn't
12917 // be used to decide if we are using positional arguments consistently.
12918 if (FS.consumesDataArgument()) {
12919 if (atFirstArg) {
12920 atFirstArg = false;
12921 usesPositionalArgs = FS.usesPositionalArg();
12922 }
12923 else if (usesPositionalArgs != FS.usesPositionalArg()) {
12924 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
12925 startSpecifier, specifierLen);
12926 return false;
12927 }
12928 }
12929
12930 // Check if the field with is non-zero.
12931 const OptionalAmount &Amt = FS.getFieldWidth();
12932 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
12933 if (Amt.getConstantAmount() == 0) {
12934 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
12935 Amt.getConstantLength());
12936 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
12937 getLocationOfByte(Amt.getStart()),
12938 /*IsStringLocation*/true, R,
12940 }
12941 }
12942
12943 if (!FS.consumesDataArgument()) {
12944 // FIXME: Technically specifying a precision or field width here
12945 // makes no sense. Worth issuing a warning at some point.
12946 return true;
12947 }
12948
12949 // Consume the argument.
12950 unsigned argIndex = FS.getArgIndex();
12951 if (argIndex < NumDataArgs) {
12952 // The check to see if the argIndex is valid will come later.
12953 // We set the bit here because we may exit early from this
12954 // function if we encounter some other error.
12955 CoveredArgs.set(argIndex);
12956 }
12957
12958 // Check the length modifier is valid with the given conversion specifier.
12959 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
12960 S.getLangOpts()))
12961 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
12962 diag::warn_format_nonsensical_length);
12963 else if (!FS.hasStandardLengthModifier())
12964 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
12965 else if (!FS.hasStandardLengthConversionCombination())
12966 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
12967 diag::warn_format_non_standard_conversion_spec);
12968
12969 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
12970 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
12971
12972 // The remaining checks depend on the data arguments.
12973 if (ArgPassingKind == Sema::FAPK_VAList)
12974 return true;
12975
12976 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
12977 return false;
12978
12979 // Check that the argument type matches the format specifier.
12980 const Expr *Ex = getDataArg(argIndex);
12981 if (!Ex)
12982 return true;
12983
12984 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
12985
12986 if (!AT.isValid()) {
12987 return true;
12988 }
12989
12991 AT.matchesType(S.Context, Ex->getType());
12992 Match = handleFormatSignedness(Match, S.getDiagnostics(), Ex->getExprLoc());
12995 return true;
12996
12997 ScanfSpecifier fixedFS = FS;
12998 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
12999 S.getLangOpts(), S.Context);
13000
13001 unsigned Diag =
13002 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
13003 : diag::warn_format_conversion_argument_type_mismatch;
13004
13005 if (Success) {
13006 // Get the fix string from the fixed format specifier.
13007 SmallString<128> buf;
13008 llvm::raw_svector_ostream os(buf);
13009 fixedFS.toString(os);
13010
13011 EmitFormatDiagnostic(
13013 << Ex->getType() << false << Ex->getSourceRange(),
13014 Ex->getBeginLoc(),
13015 /*IsStringLocation*/ false,
13016 getSpecifierRange(startSpecifier, specifierLen),
13018 getSpecifierRange(startSpecifier, specifierLen), os.str()));
13019 } else {
13020 EmitFormatDiagnostic(S.PDiag(Diag)
13022 << Ex->getType() << false << Ex->getSourceRange(),
13023 Ex->getBeginLoc(),
13024 /*IsStringLocation*/ false,
13025 getSpecifierRange(startSpecifier, specifierLen));
13026 }
13027
13028 return true;
13029}
13030
13032 Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr,
13034 unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type,
13035 bool inFunctionCall, Sema::VariadicCallType CallType,
13036 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
13037 bool IgnoreStringsWithoutSpecifiers) {
13038 // CHECK: is the format string a wide literal?
13039 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
13040 CheckFormatHandler::EmitFormatDiagnostic(
13041 S, inFunctionCall, Args[format_idx],
13042 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
13043 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
13044 return;
13045 }
13046
13047 // Str - The format string. NOTE: this is NOT null-terminated!
13048 StringRef StrRef = FExpr->getString();
13049 const char *Str = StrRef.data();
13050 // Account for cases where the string literal is truncated in a declaration.
13051 const ConstantArrayType *T =
13052 S.Context.getAsConstantArrayType(FExpr->getType());
13053 assert(T && "String literal not of constant array type!");
13054 size_t TypeSize = T->getZExtSize();
13055 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
13056 const unsigned numDataArgs = Args.size() - firstDataArg;
13057
13058 if (IgnoreStringsWithoutSpecifiers &&
13060 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
13061 return;
13062
13063 // Emit a warning if the string literal is truncated and does not contain an
13064 // embedded null character.
13065 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
13066 CheckFormatHandler::EmitFormatDiagnostic(
13067 S, inFunctionCall, Args[format_idx],
13068 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
13069 FExpr->getBeginLoc(),
13070 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
13071 return;
13072 }
13073
13074 // CHECK: empty format string?
13075 if (StrLen == 0 && numDataArgs > 0) {
13076 CheckFormatHandler::EmitFormatDiagnostic(
13077 S, inFunctionCall, Args[format_idx],
13078 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
13079 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
13080 return;
13081 }
13082
13086 CheckPrintfHandler H(
13087 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
13088 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, APK,
13089 Args, format_idx, inFunctionCall, CallType, CheckedVarArgs,
13090 UncoveredArg);
13091
13093 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
13095 H.DoneProcessing();
13096 } else if (Type == Sema::FST_Scanf) {
13097 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
13098 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
13099 CallType, CheckedVarArgs, UncoveredArg);
13100
13102 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
13103 H.DoneProcessing();
13104 } // TODO: handle other formats
13105}
13106
13108 // Str - The format string. NOTE: this is NOT null-terminated!
13109 StringRef StrRef = FExpr->getString();
13110 const char *Str = StrRef.data();
13111 // Account for cases where the string literal is truncated in a declaration.
13113 assert(T && "String literal not of constant array type!");
13114 size_t TypeSize = T->getZExtSize();
13115 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
13116 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
13117 getLangOpts(),
13119}
13120
13121//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
13122
13123// Returns the related absolute value function that is larger, of 0 if one
13124// does not exist.
13125static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
13126 switch (AbsFunction) {
13127 default:
13128 return 0;
13129
13130 case Builtin::BI__builtin_abs:
13131 return Builtin::BI__builtin_labs;
13132 case Builtin::BI__builtin_labs:
13133 return Builtin::BI__builtin_llabs;
13134 case Builtin::BI__builtin_llabs:
13135 return 0;
13136
13137 case Builtin::BI__builtin_fabsf:
13138 return Builtin::BI__builtin_fabs;
13139 case Builtin::BI__builtin_fabs:
13140 return Builtin::BI__builtin_fabsl;
13141 case Builtin::BI__builtin_fabsl:
13142 return 0;
13143
13144 case Builtin::BI__builtin_cabsf:
13145 return Builtin::BI__builtin_cabs;
13146 case Builtin::BI__builtin_cabs:
13147 return Builtin::BI__builtin_cabsl;
13148 case Builtin::BI__builtin_cabsl:
13149 return 0;
13150
13151 case Builtin::BIabs:
13152 return Builtin::BIlabs;
13153 case Builtin::BIlabs:
13154 return Builtin::BIllabs;
13155 case Builtin::BIllabs:
13156 return 0;
13157
13158 case Builtin::BIfabsf:
13159 return Builtin::BIfabs;
13160 case Builtin::BIfabs:
13161 return Builtin::BIfabsl;
13162 case Builtin::BIfabsl:
13163 return 0;
13164
13165 case Builtin::BIcabsf:
13166 return Builtin::BIcabs;
13167 case Builtin::BIcabs:
13168 return Builtin::BIcabsl;
13169 case Builtin::BIcabsl:
13170 return 0;
13171 }
13172}
13173
13174// Returns the argument type of the absolute value function.
13176 unsigned AbsType) {
13177 if (AbsType == 0)
13178 return QualType();
13179
13181 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
13182 if (Error != ASTContext::GE_None)
13183 return QualType();
13184
13186 if (!FT)
13187 return QualType();
13188
13189 if (FT->getNumParams() != 1)
13190 return QualType();
13191
13192 return FT->getParamType(0);
13193}
13194
13195// Returns the best absolute value function, or zero, based on type and
13196// current absolute value function.
13197static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
13198 unsigned AbsFunctionKind) {
13199 unsigned BestKind = 0;
13200 uint64_t ArgSize = Context.getTypeSize(ArgType);
13201 for (unsigned Kind = AbsFunctionKind; Kind != 0;
13202 Kind = getLargerAbsoluteValueFunction(Kind)) {
13203 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
13204 if (Context.getTypeSize(ParamType) >= ArgSize) {
13205 if (BestKind == 0)
13206 BestKind = Kind;
13207 else if (Context.hasSameType(ParamType, ArgType)) {
13208 BestKind = Kind;
13209 break;
13210 }
13211 }
13212 }
13213 return BestKind;
13214}
13215
13221
13224 return AVK_Integer;
13225 if (T->isRealFloatingType())
13226 return AVK_Floating;
13227 if (T->isAnyComplexType())
13228 return AVK_Complex;
13229
13230 llvm_unreachable("Type not integer, floating, or complex");
13231}
13232
13233// Changes the absolute value function to a different type. Preserves whether
13234// the function is a builtin.
13235static unsigned changeAbsFunction(unsigned AbsKind,
13236 AbsoluteValueKind ValueKind) {
13237 switch (ValueKind) {
13238 case AVK_Integer:
13239 switch (AbsKind) {
13240 default:
13241 return 0;
13242 case Builtin::BI__builtin_fabsf:
13243 case Builtin::BI__builtin_fabs:
13244 case Builtin::BI__builtin_fabsl:
13245 case Builtin::BI__builtin_cabsf:
13246 case Builtin::BI__builtin_cabs:
13247 case Builtin::BI__builtin_cabsl:
13248 return Builtin::BI__builtin_abs;
13249 case Builtin::BIfabsf:
13250 case Builtin::BIfabs:
13251 case Builtin::BIfabsl:
13252 case Builtin::BIcabsf:
13253 case Builtin::BIcabs:
13254 case Builtin::BIcabsl:
13255 return Builtin::BIabs;
13256 }
13257 case AVK_Floating:
13258 switch (AbsKind) {
13259 default:
13260 return 0;
13261 case Builtin::BI__builtin_abs:
13262 case Builtin::BI__builtin_labs:
13263 case Builtin::BI__builtin_llabs:
13264 case Builtin::BI__builtin_cabsf:
13265 case Builtin::BI__builtin_cabs:
13266 case Builtin::BI__builtin_cabsl:
13267 return Builtin::BI__builtin_fabsf;
13268 case Builtin::BIabs:
13269 case Builtin::BIlabs:
13270 case Builtin::BIllabs:
13271 case Builtin::BIcabsf:
13272 case Builtin::BIcabs:
13273 case Builtin::BIcabsl:
13274 return Builtin::BIfabsf;
13275 }
13276 case AVK_Complex:
13277 switch (AbsKind) {
13278 default:
13279 return 0;
13280 case Builtin::BI__builtin_abs:
13281 case Builtin::BI__builtin_labs:
13282 case Builtin::BI__builtin_llabs:
13283 case Builtin::BI__builtin_fabsf:
13284 case Builtin::BI__builtin_fabs:
13285 case Builtin::BI__builtin_fabsl:
13286 return Builtin::BI__builtin_cabsf;
13287 case Builtin::BIabs:
13288 case Builtin::BIlabs:
13289 case Builtin::BIllabs:
13290 case Builtin::BIfabsf:
13291 case Builtin::BIfabs:
13292 case Builtin::BIfabsl:
13293 return Builtin::BIcabsf;
13294 }
13295 }
13296 llvm_unreachable("Unable to convert function");
13297}
13298
13299static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
13300 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
13301 if (!FnInfo)
13302 return 0;
13303
13304 switch (FDecl->getBuiltinID()) {
13305 default:
13306 return 0;
13307 case Builtin::BI__builtin_abs:
13308 case Builtin::BI__builtin_fabs:
13309 case Builtin::BI__builtin_fabsf:
13310 case Builtin::BI__builtin_fabsl:
13311 case Builtin::BI__builtin_labs:
13312 case Builtin::BI__builtin_llabs:
13313 case Builtin::BI__builtin_cabs:
13314 case Builtin::BI__builtin_cabsf:
13315 case Builtin::BI__builtin_cabsl:
13316 case Builtin::BIabs:
13317 case Builtin::BIlabs:
13318 case Builtin::BIllabs:
13319 case Builtin::BIfabs:
13320 case Builtin::BIfabsf:
13321 case Builtin::BIfabsl:
13322 case Builtin::BIcabs:
13323 case Builtin::BIcabsf:
13324 case Builtin::BIcabsl:
13325 return FDecl->getBuiltinID();
13326 }
13327 llvm_unreachable("Unknown Builtin type");
13328}
13329
13330// If the replacement is valid, emit a note with replacement function.
13331// Additionally, suggest including the proper header if not already included.
13333 unsigned AbsKind, QualType ArgType) {
13334 bool EmitHeaderHint = true;
13335 const char *HeaderName = nullptr;
13336 StringRef FunctionName;
13337 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
13338 FunctionName = "std::abs";
13339 if (ArgType->isIntegralOrEnumerationType()) {
13340 HeaderName = "cstdlib";
13341 } else if (ArgType->isRealFloatingType()) {
13342 HeaderName = "cmath";
13343 } else {
13344 llvm_unreachable("Invalid Type");
13345 }
13346
13347 // Lookup all std::abs
13348 if (NamespaceDecl *Std = S.getStdNamespace()) {
13349 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
13352
13353 for (const auto *I : R) {
13354 const FunctionDecl *FDecl = nullptr;
13355 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
13356 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
13357 } else {
13358 FDecl = dyn_cast<FunctionDecl>(I);
13359 }
13360 if (!FDecl)
13361 continue;
13362
13363 // Found std::abs(), check that they are the right ones.
13364 if (FDecl->getNumParams() != 1)
13365 continue;
13366
13367 // Check that the parameter type can handle the argument.
13368 QualType ParamType = FDecl->getParamDecl(0)->getType();
13369 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
13370 S.Context.getTypeSize(ArgType) <=
13371 S.Context.getTypeSize(ParamType)) {
13372 // Found a function, don't need the header hint.
13373 EmitHeaderHint = false;
13374 break;
13375 }
13376 }
13377 }
13378 } else {
13379 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
13380 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
13381
13382 if (HeaderName) {
13383 DeclarationName DN(&S.Context.Idents.get(FunctionName));
13384 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
13386 S.LookupName(R, S.getCurScope());
13387
13388 if (R.isSingleResult()) {
13389 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
13390 if (FD && FD->getBuiltinID() == AbsKind) {
13391 EmitHeaderHint = false;
13392 } else {
13393 return;
13394 }
13395 } else if (!R.empty()) {
13396 return;
13397 }
13398 }
13399 }
13400
13401 S.Diag(Loc, diag::note_replace_abs_function)
13402 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
13403
13404 if (!HeaderName)
13405 return;
13406
13407 if (!EmitHeaderHint)
13408 return;
13409
13410 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
13411 << FunctionName;
13412}
13413
13414template <std::size_t StrLen>
13415static bool IsStdFunction(const FunctionDecl *FDecl,
13416 const char (&Str)[StrLen]) {
13417 if (!FDecl)
13418 return false;
13419 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
13420 return false;
13421 if (!FDecl->isInStdNamespace())
13422 return false;
13423
13424 return true;
13425}
13426
13427void Sema::CheckInfNaNFunction(const CallExpr *Call,
13428 const FunctionDecl *FDecl) {
13429 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
13430 if ((IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
13431 (Call->getBuiltinCallee() == Builtin::BI__builtin_nanf)) &&
13432 FPO.getNoHonorNaNs())
13433 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
13434 << 1 << 0 << Call->getSourceRange();
13435 else if ((IsStdFunction(FDecl, "isinf") ||
13436 (IsStdFunction(FDecl, "isfinite") ||
13437 (FDecl->getIdentifier() && FDecl->getName() == "infinity"))) &&
13438 FPO.getNoHonorInfs())
13439 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
13440 << 0 << 0 << Call->getSourceRange();
13441}
13442
13443// Warn when using the wrong abs() function.
13444void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
13445 const FunctionDecl *FDecl) {
13446 if (Call->getNumArgs() != 1)
13447 return;
13448
13449 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
13450 bool IsStdAbs = IsStdFunction(FDecl, "abs");
13451 if (AbsKind == 0 && !IsStdAbs)
13452 return;
13453
13454 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
13455 QualType ParamType = Call->getArg(0)->getType();
13456
13457 // Unsigned types cannot be negative. Suggest removing the absolute value
13458 // function call.
13459 if (ArgType->isUnsignedIntegerType()) {
13460 StringRef FunctionName =
13461 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
13462 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
13463 Diag(Call->getExprLoc(), diag::note_remove_abs)
13464 << FunctionName
13465 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
13466 return;
13467 }
13468
13469 // Taking the absolute value of a pointer is very suspicious, they probably
13470 // wanted to index into an array, dereference a pointer, call a function, etc.
13471 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
13472 unsigned DiagType = 0;
13473 if (ArgType->isFunctionType())
13474 DiagType = 1;
13475 else if (ArgType->isArrayType())
13476 DiagType = 2;
13477
13478 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
13479 return;
13480 }
13481
13482 // std::abs has overloads which prevent most of the absolute value problems
13483 // from occurring.
13484 if (IsStdAbs)
13485 return;
13486
13487 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
13488 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
13489
13490 // The argument and parameter are the same kind. Check if they are the right
13491 // size.
13492 if (ArgValueKind == ParamValueKind) {
13493 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
13494 return;
13495
13496 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
13497 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
13498 << FDecl << ArgType << ParamType;
13499
13500 if (NewAbsKind == 0)
13501 return;
13502
13503 emitReplacement(*this, Call->getExprLoc(),
13504 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
13505 return;
13506 }
13507
13508 // ArgValueKind != ParamValueKind
13509 // The wrong type of absolute value function was used. Attempt to find the
13510 // proper one.
13511 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
13512 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
13513 if (NewAbsKind == 0)
13514 return;
13515
13516 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
13517 << FDecl << ParamValueKind << ArgValueKind;
13518
13519 emitReplacement(*this, Call->getExprLoc(),
13520 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
13521}
13522
13523//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
13524void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
13525 const FunctionDecl *FDecl) {
13526 if (!Call || !FDecl) return;
13527
13528 // Ignore template specializations and macros.
13529 if (inTemplateInstantiation()) return;
13530 if (Call->getExprLoc().isMacroID()) return;
13531
13532 // Only care about the one template argument, two function parameter std::max
13533 if (Call->getNumArgs() != 2) return;
13534 if (!IsStdFunction(FDecl, "max")) return;
13535 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
13536 if (!ArgList) return;
13537 if (ArgList->size() != 1) return;
13538
13539 // Check that template type argument is unsigned integer.
13540 const auto& TA = ArgList->get(0);
13541 if (TA.getKind() != TemplateArgument::Type) return;
13542 QualType ArgType = TA.getAsType();
13543 if (!ArgType->isUnsignedIntegerType()) return;
13544
13545 // See if either argument is a literal zero.
13546 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
13547 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
13548 if (!MTE) return false;
13549 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
13550 if (!Num) return false;
13551 if (Num->getValue() != 0) return false;
13552 return true;
13553 };
13554
13555 const Expr *FirstArg = Call->getArg(0);
13556 const Expr *SecondArg = Call->getArg(1);
13557 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
13558 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
13559
13560 // Only warn when exactly one argument is zero.
13561 if (IsFirstArgZero == IsSecondArgZero) return;
13562
13563 SourceRange FirstRange = FirstArg->getSourceRange();
13564 SourceRange SecondRange = SecondArg->getSourceRange();
13565
13566 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
13567
13568 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
13569 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
13570
13571 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
13572 SourceRange RemovalRange;
13573 if (IsFirstArgZero) {
13574 RemovalRange = SourceRange(FirstRange.getBegin(),
13575 SecondRange.getBegin().getLocWithOffset(-1));
13576 } else {
13577 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
13578 SecondRange.getEnd());
13579 }
13580
13581 Diag(Call->getExprLoc(), diag::note_remove_max_call)
13582 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
13583 << FixItHint::CreateRemoval(RemovalRange);
13584}
13585
13586//===--- CHECK: Standard memory functions ---------------------------------===//
13587
13588/// Takes the expression passed to the size_t parameter of functions
13589/// such as memcmp, strncat, etc and warns if it's a comparison.
13590///
13591/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
13593 IdentifierInfo *FnName,
13594 SourceLocation FnLoc,
13595 SourceLocation RParenLoc) {
13596 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
13597 if (!Size)
13598 return false;
13599
13600 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
13601 if (!Size->isComparisonOp() && !Size->isLogicalOp())
13602 return false;
13603
13604 SourceRange SizeRange = Size->getSourceRange();
13605 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
13606 << SizeRange << FnName;
13607 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
13608 << FnName
13610 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
13611 << FixItHint::CreateRemoval(RParenLoc);
13612 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
13613 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
13615 ")");
13616
13617 return true;
13618}
13619
13620/// Determine whether the given type is or contains a dynamic class type
13621/// (e.g., whether it has a vtable).
13623 bool &IsContained) {
13624 // Look through array types while ignoring qualifiers.
13625 const Type *Ty = T->getBaseElementTypeUnsafe();
13626 IsContained = false;
13627
13628 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
13629 RD = RD ? RD->getDefinition() : nullptr;
13630 if (!RD || RD->isInvalidDecl())
13631 return nullptr;
13632
13633 if (RD->isDynamicClass())
13634 return RD;
13635
13636 // Check all the fields. If any bases were dynamic, the class is dynamic.
13637 // It's impossible for a class to transitively contain itself by value, so
13638 // infinite recursion is impossible.
13639 for (auto *FD : RD->fields()) {
13640 bool SubContained;
13641 if (const CXXRecordDecl *ContainedRD =
13642 getContainedDynamicClass(FD->getType(), SubContained)) {
13643 IsContained = true;
13644 return ContainedRD;
13645 }
13646 }
13647
13648 return nullptr;
13649}
13650
13652 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
13653 if (Unary->getKind() == UETT_SizeOf)
13654 return Unary;
13655 return nullptr;
13656}
13657
13658/// If E is a sizeof expression, returns its argument expression,
13659/// otherwise returns NULL.
13660static const Expr *getSizeOfExprArg(const Expr *E) {
13662 if (!SizeOf->isArgumentType())
13663 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
13664 return nullptr;
13665}
13666
13667/// If E is a sizeof expression, returns its argument type.
13670 return SizeOf->getTypeOfArgument();
13671 return QualType();
13672}
13673
13674namespace {
13675
13676struct SearchNonTrivialToInitializeField
13677 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
13678 using Super =
13680
13681 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
13682
13683 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
13684 SourceLocation SL) {
13685 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
13686 asDerived().visitArray(PDIK, AT, SL);
13687 return;
13688 }
13689
13690 Super::visitWithKind(PDIK, FT, SL);
13691 }
13692
13693 void visitARCStrong(QualType FT, SourceLocation SL) {
13694 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
13695 }
13696 void visitARCWeak(QualType FT, SourceLocation SL) {
13697 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
13698 }
13699 void visitStruct(QualType FT, SourceLocation SL) {
13700 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
13701 visit(FD->getType(), FD->getLocation());
13702 }
13703 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
13704 const ArrayType *AT, SourceLocation SL) {
13705 visit(getContext().getBaseElementType(AT), SL);
13706 }
13707 void visitTrivial(QualType FT, SourceLocation SL) {}
13708
13709 static void diag(QualType RT, const Expr *E, Sema &S) {
13710 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
13711 }
13712
13713 ASTContext &getContext() { return S.getASTContext(); }
13714
13715 const Expr *E;
13716 Sema &S;
13717};
13718
13719struct SearchNonTrivialToCopyField
13720 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
13722
13723 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
13724
13725 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
13726 SourceLocation SL) {
13727 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
13728 asDerived().visitArray(PCK, AT, SL);
13729 return;
13730 }
13731
13732 Super::visitWithKind(PCK, FT, SL);
13733 }
13734
13735 void visitARCStrong(QualType FT, SourceLocation SL) {
13736 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
13737 }
13738 void visitARCWeak(QualType FT, SourceLocation SL) {
13739 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
13740 }
13741 void visitStruct(QualType FT, SourceLocation SL) {
13742 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
13743 visit(FD->getType(), FD->getLocation());
13744 }
13745 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
13746 SourceLocation SL) {
13747 visit(getContext().getBaseElementType(AT), SL);
13748 }
13749 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
13750 SourceLocation SL) {}
13751 void visitTrivial(QualType FT, SourceLocation SL) {}
13752 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
13753
13754 static void diag(QualType RT, const Expr *E, Sema &S) {
13755 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
13756 }
13757
13758 ASTContext &getContext() { return S.getASTContext(); }
13759
13760 const Expr *E;
13761 Sema &S;
13762};
13763
13764}
13765
13766/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
13767static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
13768 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
13769
13770 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
13771 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
13772 return false;
13773
13774 return doesExprLikelyComputeSize(BO->getLHS()) ||
13775 doesExprLikelyComputeSize(BO->getRHS());
13776 }
13777
13778 return getAsSizeOfExpr(SizeofExpr) != nullptr;
13779}
13780
13781/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
13782///
13783/// \code
13784/// #define MACRO 0
13785/// foo(MACRO);
13786/// foo(0);
13787/// \endcode
13788///
13789/// This should return true for the first call to foo, but not for the second
13790/// (regardless of whether foo is a macro or function).
13792 SourceLocation CallLoc,
13793 SourceLocation ArgLoc) {
13794 if (!CallLoc.isMacroID())
13795 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
13796
13797 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
13798 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
13799}
13800
13801/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
13802/// last two arguments transposed.
13803static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
13804 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
13805 return;
13806
13807 const Expr *SizeArg =
13808 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
13809
13810 auto isLiteralZero = [](const Expr *E) {
13811 return (isa<IntegerLiteral>(E) &&
13812 cast<IntegerLiteral>(E)->getValue() == 0) ||
13813 (isa<CharacterLiteral>(E) &&
13814 cast<CharacterLiteral>(E)->getValue() == 0);
13815 };
13816
13817 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
13818 SourceLocation CallLoc = Call->getRParenLoc();
13820 if (isLiteralZero(SizeArg) &&
13821 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
13822
13823 SourceLocation DiagLoc = SizeArg->getExprLoc();
13824
13825 // Some platforms #define bzero to __builtin_memset. See if this is the
13826 // case, and if so, emit a better diagnostic.
13827 if (BId == Builtin::BIbzero ||
13829 CallLoc, SM, S.getLangOpts()) == "bzero")) {
13830 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
13831 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
13832 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
13833 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
13834 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
13835 }
13836 return;
13837 }
13838
13839 // If the second argument to a memset is a sizeof expression and the third
13840 // isn't, this is also likely an error. This should catch
13841 // 'memset(buf, sizeof(buf), 0xff)'.
13842 if (BId == Builtin::BImemset &&
13843 doesExprLikelyComputeSize(Call->getArg(1)) &&
13844 !doesExprLikelyComputeSize(Call->getArg(2))) {
13845 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
13846 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
13847 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
13848 return;
13849 }
13850}
13851
13852/// Check for dangerous or invalid arguments to memset().
13853///
13854/// This issues warnings on known problematic, dangerous or unspecified
13855/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
13856/// function calls.
13857///
13858/// \param Call The call expression to diagnose.
13859void Sema::CheckMemaccessArguments(const CallExpr *Call,
13860 unsigned BId,
13861 IdentifierInfo *FnName) {
13862 assert(BId != 0);
13863
13864 // It is possible to have a non-standard definition of memset. Validate
13865 // we have enough arguments, and if not, abort further checking.
13866 unsigned ExpectedNumArgs =
13867 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
13868 if (Call->getNumArgs() < ExpectedNumArgs)
13869 return;
13870
13871 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
13872 BId == Builtin::BIstrndup ? 1 : 2);
13873 unsigned LenArg =
13874 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
13875 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
13876
13877 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
13878 Call->getBeginLoc(), Call->getRParenLoc()))
13879 return;
13880
13881 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
13882 CheckMemaccessSize(*this, BId, Call);
13883
13884 // We have special checking when the length is a sizeof expression.
13885 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
13886 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
13887 llvm::FoldingSetNodeID SizeOfArgID;
13888
13889 // Although widely used, 'bzero' is not a standard function. Be more strict
13890 // with the argument types before allowing diagnostics and only allow the
13891 // form bzero(ptr, sizeof(...)).
13892 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
13893 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
13894 return;
13895
13896 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
13897 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
13898 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
13899
13900 QualType DestTy = Dest->getType();
13901 QualType PointeeTy;
13902 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
13903 PointeeTy = DestPtrTy->getPointeeType();
13904
13905 // Never warn about void type pointers. This can be used to suppress
13906 // false positives.
13907 if (PointeeTy->isVoidType())
13908 continue;
13909
13910 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
13911 // actually comparing the expressions for equality. Because computing the
13912 // expression IDs can be expensive, we only do this if the diagnostic is
13913 // enabled.
13914 if (SizeOfArg &&
13915 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
13916 SizeOfArg->getExprLoc())) {
13917 // We only compute IDs for expressions if the warning is enabled, and
13918 // cache the sizeof arg's ID.
13919 if (SizeOfArgID == llvm::FoldingSetNodeID())
13920 SizeOfArg->Profile(SizeOfArgID, Context, true);
13921 llvm::FoldingSetNodeID DestID;
13922 Dest->Profile(DestID, Context, true);
13923 if (DestID == SizeOfArgID) {
13924 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
13925 // over sizeof(src) as well.
13926 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
13927 StringRef ReadableName = FnName->getName();
13928
13929 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
13930 if (UnaryOp->getOpcode() == UO_AddrOf)
13931 ActionIdx = 1; // If its an address-of operator, just remove it.
13932 if (!PointeeTy->isIncompleteType() &&
13933 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
13934 ActionIdx = 2; // If the pointee's size is sizeof(char),
13935 // suggest an explicit length.
13936
13937 // If the function is defined as a builtin macro, do not show macro
13938 // expansion.
13939 SourceLocation SL = SizeOfArg->getExprLoc();
13940 SourceRange DSR = Dest->getSourceRange();
13941 SourceRange SSR = SizeOfArg->getSourceRange();
13943
13944 if (SM.isMacroArgExpansion(SL)) {
13945 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
13946 SL = SM.getSpellingLoc(SL);
13947 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
13948 SM.getSpellingLoc(DSR.getEnd()));
13949 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
13950 SM.getSpellingLoc(SSR.getEnd()));
13951 }
13952
13953 DiagRuntimeBehavior(SL, SizeOfArg,
13954 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
13955 << ReadableName
13956 << PointeeTy
13957 << DestTy
13958 << DSR
13959 << SSR);
13960 DiagRuntimeBehavior(SL, SizeOfArg,
13961 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
13962 << ActionIdx
13963 << SSR);
13964
13965 break;
13966 }
13967 }
13968
13969 // Also check for cases where the sizeof argument is the exact same
13970 // type as the memory argument, and where it points to a user-defined
13971 // record type.
13972 if (SizeOfArgTy != QualType()) {
13973 if (PointeeTy->isRecordType() &&
13974 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
13975 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
13976 PDiag(diag::warn_sizeof_pointer_type_memaccess)
13977 << FnName << SizeOfArgTy << ArgIdx
13978 << PointeeTy << Dest->getSourceRange()
13979 << LenExpr->getSourceRange());
13980 break;
13981 }
13982 }
13983 } else if (DestTy->isArrayType()) {
13984 PointeeTy = DestTy;
13985 }
13986
13987 if (PointeeTy == QualType())
13988 continue;
13989
13990 // Always complain about dynamic classes.
13991 bool IsContained;
13992 if (const CXXRecordDecl *ContainedRD =
13993 getContainedDynamicClass(PointeeTy, IsContained)) {
13994
13995 unsigned OperationType = 0;
13996 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
13997 // "overwritten" if we're warning about the destination for any call
13998 // but memcmp; otherwise a verb appropriate to the call.
13999 if (ArgIdx != 0 || IsCmp) {
14000 if (BId == Builtin::BImemcpy)
14001 OperationType = 1;
14002 else if(BId == Builtin::BImemmove)
14003 OperationType = 2;
14004 else if (IsCmp)
14005 OperationType = 3;
14006 }
14007
14008 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
14009 PDiag(diag::warn_dyn_class_memaccess)
14010 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
14011 << IsContained << ContainedRD << OperationType
14012 << Call->getCallee()->getSourceRange());
14013 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
14014 BId != Builtin::BImemset)
14016 Dest->getExprLoc(), Dest,
14017 PDiag(diag::warn_arc_object_memaccess)
14018 << ArgIdx << FnName << PointeeTy
14019 << Call->getCallee()->getSourceRange());
14020 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
14021 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
14022 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
14023 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
14024 PDiag(diag::warn_cstruct_memaccess)
14025 << ArgIdx << FnName << PointeeTy << 0);
14026 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
14027 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
14028 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
14029 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
14030 PDiag(diag::warn_cstruct_memaccess)
14031 << ArgIdx << FnName << PointeeTy << 1);
14032 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
14033 } else {
14034 continue;
14035 }
14036 } else
14037 continue;
14038
14040 Dest->getExprLoc(), Dest,
14041 PDiag(diag::note_bad_memaccess_silence)
14042 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
14043 break;
14044 }
14045}
14046
14047// A little helper routine: ignore addition and subtraction of integer literals.
14048// This intentionally does not ignore all integer constant expressions because
14049// we don't want to remove sizeof().
14050static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
14051 Ex = Ex->IgnoreParenCasts();
14052
14053 while (true) {
14054 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
14055 if (!BO || !BO->isAdditiveOp())
14056 break;
14057
14058 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
14059 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
14060
14061 if (isa<IntegerLiteral>(RHS))
14062 Ex = LHS;
14063 else if (isa<IntegerLiteral>(LHS))
14064 Ex = RHS;
14065 else
14066 break;
14067 }
14068
14069 return Ex;
14070}
14071
14073 ASTContext &Context) {
14074 // Only handle constant-sized or VLAs, but not flexible members.
14075 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
14076 // Only issue the FIXIT for arrays of size > 1.
14077 if (CAT->getZExtSize() <= 1)
14078 return false;
14079 } else if (!Ty->isVariableArrayType()) {
14080 return false;
14081 }
14082 return true;
14083}
14084
14085// Warn if the user has made the 'size' argument to strlcpy or strlcat
14086// be the size of the source, instead of the destination.
14087void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
14088 IdentifierInfo *FnName) {
14089
14090 // Don't crash if the user has the wrong number of arguments
14091 unsigned NumArgs = Call->getNumArgs();
14092 if ((NumArgs != 3) && (NumArgs != 4))
14093 return;
14094
14095 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
14096 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
14097 const Expr *CompareWithSrc = nullptr;
14098
14099 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
14100 Call->getBeginLoc(), Call->getRParenLoc()))
14101 return;
14102
14103 // Look for 'strlcpy(dst, x, sizeof(x))'
14104 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
14105 CompareWithSrc = Ex;
14106 else {
14107 // Look for 'strlcpy(dst, x, strlen(x))'
14108 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
14109 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
14110 SizeCall->getNumArgs() == 1)
14111 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
14112 }
14113 }
14114
14115 if (!CompareWithSrc)
14116 return;
14117
14118 // Determine if the argument to sizeof/strlen is equal to the source
14119 // argument. In principle there's all kinds of things you could do
14120 // here, for instance creating an == expression and evaluating it with
14121 // EvaluateAsBooleanCondition, but this uses a more direct technique:
14122 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
14123 if (!SrcArgDRE)
14124 return;
14125
14126 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
14127 if (!CompareWithSrcDRE ||
14128 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
14129 return;
14130
14131 const Expr *OriginalSizeArg = Call->getArg(2);
14132 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
14133 << OriginalSizeArg->getSourceRange() << FnName;
14134
14135 // Output a FIXIT hint if the destination is an array (rather than a
14136 // pointer to an array). This could be enhanced to handle some
14137 // pointers if we know the actual size, like if DstArg is 'array+2'
14138 // we could say 'sizeof(array)-2'.
14139 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
14141 return;
14142
14143 SmallString<128> sizeString;
14144 llvm::raw_svector_ostream OS(sizeString);
14145 OS << "sizeof(";
14146 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
14147 OS << ")";
14148
14149 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
14150 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
14151 OS.str());
14152}
14153
14154/// Check if two expressions refer to the same declaration.
14155static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
14156 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
14157 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
14158 return D1->getDecl() == D2->getDecl();
14159 return false;
14160}
14161
14162static const Expr *getStrlenExprArg(const Expr *E) {
14163 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
14164 const FunctionDecl *FD = CE->getDirectCallee();
14165 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
14166 return nullptr;
14167 return CE->getArg(0)->IgnoreParenCasts();
14168 }
14169 return nullptr;
14170}
14171
14172// Warn on anti-patterns as the 'size' argument to strncat.
14173// The correct size argument should look like following:
14174// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
14175void Sema::CheckStrncatArguments(const CallExpr *CE,
14176 IdentifierInfo *FnName) {
14177 // Don't crash if the user has the wrong number of arguments.
14178 if (CE->getNumArgs() < 3)
14179 return;
14180 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
14181 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
14182 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
14183
14184 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
14185 CE->getRParenLoc()))
14186 return;
14187
14188 // Identify common expressions, which are wrongly used as the size argument
14189 // to strncat and may lead to buffer overflows.
14190 unsigned PatternType = 0;
14191 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
14192 // - sizeof(dst)
14193 if (referToTheSameDecl(SizeOfArg, DstArg))
14194 PatternType = 1;
14195 // - sizeof(src)
14196 else if (referToTheSameDecl(SizeOfArg, SrcArg))
14197 PatternType = 2;
14198 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
14199 if (BE->getOpcode() == BO_Sub) {
14200 const Expr *L = BE->getLHS()->IgnoreParenCasts();
14201 const Expr *R = BE->getRHS()->IgnoreParenCasts();
14202 // - sizeof(dst) - strlen(dst)
14203 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
14205 PatternType = 1;
14206 // - sizeof(src) - (anything)
14207 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
14208 PatternType = 2;
14209 }
14210 }
14211
14212 if (PatternType == 0)
14213 return;
14214
14215 // Generate the diagnostic.
14216 SourceLocation SL = LenArg->getBeginLoc();
14217 SourceRange SR = LenArg->getSourceRange();
14219
14220 // If the function is defined as a builtin macro, do not show macro expansion.
14221 if (SM.isMacroArgExpansion(SL)) {
14222 SL = SM.getSpellingLoc(SL);
14223 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
14224 SM.getSpellingLoc(SR.getEnd()));
14225 }
14226
14227 // Check if the destination is an array (rather than a pointer to an array).
14228 QualType DstTy = DstArg->getType();
14229 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
14230 Context);
14231 if (!isKnownSizeArray) {
14232 if (PatternType == 1)
14233 Diag(SL, diag::warn_strncat_wrong_size) << SR;
14234 else
14235 Diag(SL, diag::warn_strncat_src_size) << SR;
14236 return;
14237 }
14238
14239 if (PatternType == 1)
14240 Diag(SL, diag::warn_strncat_large_size) << SR;
14241 else
14242 Diag(SL, diag::warn_strncat_src_size) << SR;
14243
14244 SmallString<128> sizeString;
14245 llvm::raw_svector_ostream OS(sizeString);
14246 OS << "sizeof(";
14247 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
14248 OS << ") - ";
14249 OS << "strlen(";
14250 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
14251 OS << ") - 1";
14252
14253 Diag(SL, diag::note_strncat_wrong_size)
14254 << FixItHint::CreateReplacement(SR, OS.str());
14255}
14256
14257namespace {
14258void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
14259 const UnaryOperator *UnaryExpr, const Decl *D) {
14260 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
14261 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
14262 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
14263 return;
14264 }
14265}
14266
14267void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
14268 const UnaryOperator *UnaryExpr) {
14269 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
14270 const Decl *D = Lvalue->getDecl();
14271 if (isa<DeclaratorDecl>(D))
14272 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
14273 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
14274 }
14275
14276 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
14277 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
14278 Lvalue->getMemberDecl());
14279}
14280
14281void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
14282 const UnaryOperator *UnaryExpr) {
14283 const auto *Lambda = dyn_cast<LambdaExpr>(
14285 if (!Lambda)
14286 return;
14287
14288 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
14289 << CalleeName << 2 /*object: lambda expression*/;
14290}
14291
14292void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
14293 const DeclRefExpr *Lvalue) {
14294 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
14295 if (Var == nullptr)
14296 return;
14297
14298 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
14299 << CalleeName << 0 /*object: */ << Var;
14300}
14301
14302void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
14303 const CastExpr *Cast) {
14304 SmallString<128> SizeString;
14305 llvm::raw_svector_ostream OS(SizeString);
14306
14307 clang::CastKind Kind = Cast->getCastKind();
14308 if (Kind == clang::CK_BitCast &&
14309 !Cast->getSubExpr()->getType()->isFunctionPointerType())
14310 return;
14311 if (Kind == clang::CK_IntegralToPointer &&
14312 !isa<IntegerLiteral>(
14313 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
14314 return;
14315
14316 switch (Cast->getCastKind()) {
14317 case clang::CK_BitCast:
14318 case clang::CK_IntegralToPointer:
14319 case clang::CK_FunctionToPointerDecay:
14320 OS << '\'';
14321 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
14322 OS << '\'';
14323 break;
14324 default:
14325 return;
14326 }
14327
14328 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
14329 << CalleeName << 0 /*object: */ << OS.str();
14330}
14331} // namespace
14332
14333/// Alerts the user that they are attempting to free a non-malloc'd object.
14334void Sema::CheckFreeArguments(const CallExpr *E) {
14335 const std::string CalleeName =
14336 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
14337
14338 { // Prefer something that doesn't involve a cast to make things simpler.
14339 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
14340 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
14341 switch (UnaryExpr->getOpcode()) {
14342 case UnaryOperator::Opcode::UO_AddrOf:
14343 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
14344 case UnaryOperator::Opcode::UO_Plus:
14345 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
14346 default:
14347 break;
14348 }
14349
14350 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
14351 if (Lvalue->getType()->isArrayType())
14352 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
14353
14354 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
14355 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
14356 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
14357 return;
14358 }
14359
14360 if (isa<BlockExpr>(Arg)) {
14361 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
14362 << CalleeName << 1 /*object: block*/;
14363 return;
14364 }
14365 }
14366 // Maybe the cast was important, check after the other cases.
14367 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
14368 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
14369}
14370
14371void
14372Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
14373 SourceLocation ReturnLoc,
14374 bool isObjCMethod,
14375 const AttrVec *Attrs,
14376 const FunctionDecl *FD) {
14377 // Check if the return value is null but should not be.
14378 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
14379 (!isObjCMethod && isNonNullType(lhsType))) &&
14380 CheckNonNullExpr(*this, RetValExp))
14381 Diag(ReturnLoc, diag::warn_null_ret)
14382 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
14383
14384 // C++11 [basic.stc.dynamic.allocation]p4:
14385 // If an allocation function declared with a non-throwing
14386 // exception-specification fails to allocate storage, it shall return
14387 // a null pointer. Any other allocation function that fails to allocate
14388 // storage shall indicate failure only by throwing an exception [...]
14389 if (FD) {
14391 if (Op == OO_New || Op == OO_Array_New) {
14392 const FunctionProtoType *Proto
14393 = FD->getType()->castAs<FunctionProtoType>();
14394 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
14395 CheckNonNullExpr(*this, RetValExp))
14396 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
14397 << FD << getLangOpts().CPlusPlus11;
14398 }
14399 }
14400
14401 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
14402 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
14403 }
14404
14405 // PPC MMA non-pointer types are not allowed as return type. Checking the type
14406 // here prevent the user from using a PPC MMA type as trailing return type.
14407 if (Context.getTargetInfo().getTriple().isPPC64())
14408 CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
14409}
14410
14411/// Check for comparisons of floating-point values using == and !=. Issue a
14412/// warning if the comparison is not likely to do what the programmer intended.
14414 BinaryOperatorKind Opcode) {
14415 if (!BinaryOperator::isEqualityOp(Opcode))
14416 return;
14417
14418 // Match and capture subexpressions such as "(float) X == 0.1".
14419 FloatingLiteral *FPLiteral;
14420 CastExpr *FPCast;
14421 auto getCastAndLiteral = [&FPLiteral, &FPCast](Expr *L, Expr *R) {
14422 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
14423 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
14424 return FPLiteral && FPCast;
14425 };
14426
14427 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
14428 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
14429 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
14430 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
14431 TargetTy->isFloatingPoint()) {
14432 bool Lossy;
14433 llvm::APFloat TargetC = FPLiteral->getValue();
14434 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
14435 llvm::APFloat::rmNearestTiesToEven, &Lossy);
14436 if (Lossy) {
14437 // If the literal cannot be represented in the source type, then a
14438 // check for == is always false and check for != is always true.
14439 Diag(Loc, diag::warn_float_compare_literal)
14440 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
14441 << LHS->getSourceRange() << RHS->getSourceRange();
14442 return;
14443 }
14444 }
14445 }
14446
14447 // Match a more general floating-point equality comparison (-Wfloat-equal).
14448 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
14449 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
14450
14451 // Special case: check for x == x (which is OK).
14452 // Do not emit warnings for such cases.
14453 if (auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
14454 if (auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
14455 if (DRL->getDecl() == DRR->getDecl())
14456 return;
14457
14458 // Special case: check for comparisons against literals that can be exactly
14459 // represented by APFloat. In such cases, do not emit a warning. This
14460 // is a heuristic: often comparison against such literals are used to
14461 // detect if a value in a variable has not changed. This clearly can
14462 // lead to false negatives.
14463 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
14464 if (FLL->isExact())
14465 return;
14466 } else
14467 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
14468 if (FLR->isExact())
14469 return;
14470
14471 // Check for comparisons with builtin types.
14472 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
14473 if (CL->getBuiltinCallee())
14474 return;
14475
14476 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
14477 if (CR->getBuiltinCallee())
14478 return;
14479
14480 // Emit the diagnostic.
14481 Diag(Loc, diag::warn_floatingpoint_eq)
14482 << LHS->getSourceRange() << RHS->getSourceRange();
14483}
14484
14485//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
14486//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
14487
14488namespace {
14489
14490/// Structure recording the 'active' range of an integer-valued
14491/// expression.
14492struct IntRange {
14493 /// The number of bits active in the int. Note that this includes exactly one
14494 /// sign bit if !NonNegative.
14495 unsigned Width;
14496
14497 /// True if the int is known not to have negative values. If so, all leading
14498 /// bits before Width are known zero, otherwise they are known to be the
14499 /// same as the MSB within Width.
14500 bool NonNegative;
14501
14502 IntRange(unsigned Width, bool NonNegative)
14503 : Width(Width), NonNegative(NonNegative) {}
14504
14505 /// Number of bits excluding the sign bit.
14506 unsigned valueBits() const {
14507 return NonNegative ? Width : Width - 1;
14508 }
14509
14510 /// Returns the range of the bool type.
14511 static IntRange forBoolType() {
14512 return IntRange(1, true);
14513 }
14514
14515 /// Returns the range of an opaque value of the given integral type.
14516 static IntRange forValueOfType(ASTContext &C, QualType T) {
14517 return forValueOfCanonicalType(C,
14519 }
14520
14521 /// Returns the range of an opaque value of a canonical integral type.
14522 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
14523 assert(T->isCanonicalUnqualified());
14524
14525 if (const VectorType *VT = dyn_cast<VectorType>(T))
14526 T = VT->getElementType().getTypePtr();
14527 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
14528 T = CT->getElementType().getTypePtr();
14529 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
14530 T = AT->getValueType().getTypePtr();
14531
14532 if (!C.getLangOpts().CPlusPlus) {
14533 // For enum types in C code, use the underlying datatype.
14534 if (const EnumType *ET = dyn_cast<EnumType>(T))
14535 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
14536 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
14537 // For enum types in C++, use the known bit width of the enumerators.
14538 EnumDecl *Enum = ET->getDecl();
14539 // In C++11, enums can have a fixed underlying type. Use this type to
14540 // compute the range.
14541 if (Enum->isFixed()) {
14542 return IntRange(C.getIntWidth(QualType(T, 0)),
14543 !ET->isSignedIntegerOrEnumerationType());
14544 }
14545
14546 unsigned NumPositive = Enum->getNumPositiveBits();
14547 unsigned NumNegative = Enum->getNumNegativeBits();
14548
14549 if (NumNegative == 0)
14550 return IntRange(NumPositive, true/*NonNegative*/);
14551 else
14552 return IntRange(std::max(NumPositive + 1, NumNegative),
14553 false/*NonNegative*/);
14554 }
14555
14556 if (const auto *EIT = dyn_cast<BitIntType>(T))
14557 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
14558
14559 const BuiltinType *BT = cast<BuiltinType>(T);
14560 assert(BT->isInteger());
14561
14562 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
14563 }
14564
14565 /// Returns the "target" range of a canonical integral type, i.e.
14566 /// the range of values expressible in the type.
14567 ///
14568 /// This matches forValueOfCanonicalType except that enums have the
14569 /// full range of their type, not the range of their enumerators.
14570 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
14571 assert(T->isCanonicalUnqualified());
14572
14573 if (const VectorType *VT = dyn_cast<VectorType>(T))
14574 T = VT->getElementType().getTypePtr();
14575 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
14576 T = CT->getElementType().getTypePtr();
14577 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
14578 T = AT->getValueType().getTypePtr();
14579 if (const EnumType *ET = dyn_cast<EnumType>(T))
14580 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
14581
14582 if (const auto *EIT = dyn_cast<BitIntType>(T))
14583 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
14584
14585 const BuiltinType *BT = cast<BuiltinType>(T);
14586 assert(BT->isInteger());
14587
14588 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
14589 }
14590
14591 /// Returns the supremum of two ranges: i.e. their conservative merge.
14592 static IntRange join(IntRange L, IntRange R) {
14593 bool Unsigned = L.NonNegative && R.NonNegative;
14594 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
14595 L.NonNegative && R.NonNegative);
14596 }
14597
14598 /// Return the range of a bitwise-AND of the two ranges.
14599 static IntRange bit_and(IntRange L, IntRange R) {
14600 unsigned Bits = std::max(L.Width, R.Width);
14601 bool NonNegative = false;
14602 if (L.NonNegative) {
14603 Bits = std::min(Bits, L.Width);
14604 NonNegative = true;
14605 }
14606 if (R.NonNegative) {
14607 Bits = std::min(Bits, R.Width);
14608 NonNegative = true;
14609 }
14610 return IntRange(Bits, NonNegative);
14611 }
14612
14613 /// Return the range of a sum of the two ranges.
14614 static IntRange sum(IntRange L, IntRange R) {
14615 bool Unsigned = L.NonNegative && R.NonNegative;
14616 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
14617 Unsigned);
14618 }
14619
14620 /// Return the range of a difference of the two ranges.
14621 static IntRange difference(IntRange L, IntRange R) {
14622 // We need a 1-bit-wider range if:
14623 // 1) LHS can be negative: least value can be reduced.
14624 // 2) RHS can be negative: greatest value can be increased.
14625 bool CanWiden = !L.NonNegative || !R.NonNegative;
14626 bool Unsigned = L.NonNegative && R.Width == 0;
14627 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
14628 !Unsigned,
14629 Unsigned);
14630 }
14631
14632 /// Return the range of a product of the two ranges.
14633 static IntRange product(IntRange L, IntRange R) {
14634 // If both LHS and RHS can be negative, we can form
14635 // -2^L * -2^R = 2^(L + R)
14636 // which requires L + R + 1 value bits to represent.
14637 bool CanWiden = !L.NonNegative && !R.NonNegative;
14638 bool Unsigned = L.NonNegative && R.NonNegative;
14639 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
14640 Unsigned);
14641 }
14642
14643 /// Return the range of a remainder operation between the two ranges.
14644 static IntRange rem(IntRange L, IntRange R) {
14645 // The result of a remainder can't be larger than the result of
14646 // either side. The sign of the result is the sign of the LHS.
14647 bool Unsigned = L.NonNegative;
14648 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
14649 Unsigned);
14650 }
14651};
14652
14653} // namespace
14654
14655static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
14656 unsigned MaxWidth) {
14657 if (value.isSigned() && value.isNegative())
14658 return IntRange(value.getSignificantBits(), false);
14659
14660 if (value.getBitWidth() > MaxWidth)
14661 value = value.trunc(MaxWidth);
14662
14663 // isNonNegative() just checks the sign bit without considering
14664 // signedness.
14665 return IntRange(value.getActiveBits(), true);
14666}
14667
14668static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
14669 unsigned MaxWidth) {
14670 if (result.isInt())
14671 return GetValueRange(C, result.getInt(), MaxWidth);
14672
14673 if (result.isVector()) {
14674 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
14675 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
14676 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
14677 R = IntRange::join(R, El);
14678 }
14679 return R;
14680 }
14681
14682 if (result.isComplexInt()) {
14683 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
14684 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
14685 return IntRange::join(R, I);
14686 }
14687
14688 // This can happen with lossless casts to intptr_t of "based" lvalues.
14689 // Assume it might use arbitrary bits.
14690 // FIXME: The only reason we need to pass the type in here is to get
14691 // the sign right on this one case. It would be nice if APValue
14692 // preserved this.
14693 assert(result.isLValue() || result.isAddrLabelDiff());
14694 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
14695}
14696
14697static QualType GetExprType(const Expr *E) {
14698 QualType Ty = E->getType();
14699 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
14700 Ty = AtomicRHS->getValueType();
14701 return Ty;
14702}
14703
14704/// Pseudo-evaluate the given integer expression, estimating the
14705/// range of values it might take.
14706///
14707/// \param MaxWidth The width to which the value will be truncated.
14708/// \param Approximate If \c true, return a likely range for the result: in
14709/// particular, assume that arithmetic on narrower types doesn't leave
14710/// those types. If \c false, return a range including all possible
14711/// result values.
14712static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
14713 bool InConstantContext, bool Approximate) {
14714 E = E->IgnoreParens();
14715
14716 // Try a full evaluation first.
14717 Expr::EvalResult result;
14718 if (E->EvaluateAsRValue(result, C, InConstantContext))
14719 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
14720
14721 // I think we only want to look through implicit casts here; if the
14722 // user has an explicit widening cast, we should treat the value as
14723 // being of the new, wider type.
14724 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
14725 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
14726 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
14727 Approximate);
14728
14729 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
14730
14731 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
14732 CE->getCastKind() == CK_BooleanToSignedIntegral;
14733
14734 // Assume that non-integer casts can span the full range of the type.
14735 if (!isIntegerCast)
14736 return OutputTypeRange;
14737
14738 IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
14739 std::min(MaxWidth, OutputTypeRange.Width),
14740 InConstantContext, Approximate);
14741
14742 // Bail out if the subexpr's range is as wide as the cast type.
14743 if (SubRange.Width >= OutputTypeRange.Width)
14744 return OutputTypeRange;
14745
14746 // Otherwise, we take the smaller width, and we're non-negative if
14747 // either the output type or the subexpr is.
14748 return IntRange(SubRange.Width,
14749 SubRange.NonNegative || OutputTypeRange.NonNegative);
14750 }
14751
14752 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
14753 // If we can fold the condition, just take that operand.
14754 bool CondResult;
14755 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
14756 return GetExprRange(C,
14757 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
14758 MaxWidth, InConstantContext, Approximate);
14759
14760 // Otherwise, conservatively merge.
14761 // GetExprRange requires an integer expression, but a throw expression
14762 // results in a void type.
14763 Expr *E = CO->getTrueExpr();
14764 IntRange L = E->getType()->isVoidType()
14765 ? IntRange{0, true}
14766 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
14767 E = CO->getFalseExpr();
14768 IntRange R = E->getType()->isVoidType()
14769 ? IntRange{0, true}
14770 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
14771 return IntRange::join(L, R);
14772 }
14773
14774 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
14775 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
14776
14777 switch (BO->getOpcode()) {
14778 case BO_Cmp:
14779 llvm_unreachable("builtin <=> should have class type");
14780
14781 // Boolean-valued operations are single-bit and positive.
14782 case BO_LAnd:
14783 case BO_LOr:
14784 case BO_LT:
14785 case BO_GT:
14786 case BO_LE:
14787 case BO_GE:
14788 case BO_EQ:
14789 case BO_NE:
14790 return IntRange::forBoolType();
14791
14792 // The type of the assignments is the type of the LHS, so the RHS
14793 // is not necessarily the same type.
14794 case BO_MulAssign:
14795 case BO_DivAssign:
14796 case BO_RemAssign:
14797 case BO_AddAssign:
14798 case BO_SubAssign:
14799 case BO_XorAssign:
14800 case BO_OrAssign:
14801 // TODO: bitfields?
14802 return IntRange::forValueOfType(C, GetExprType(E));
14803
14804 // Simple assignments just pass through the RHS, which will have
14805 // been coerced to the LHS type.
14806 case BO_Assign:
14807 // TODO: bitfields?
14808 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
14809 Approximate);
14810
14811 // Operations with opaque sources are black-listed.
14812 case BO_PtrMemD:
14813 case BO_PtrMemI:
14814 return IntRange::forValueOfType(C, GetExprType(E));
14815
14816 // Bitwise-and uses the *infinum* of the two source ranges.
14817 case BO_And:
14818 case BO_AndAssign:
14819 Combine = IntRange::bit_and;
14820 break;
14821
14822 // Left shift gets black-listed based on a judgement call.
14823 case BO_Shl:
14824 // ...except that we want to treat '1 << (blah)' as logically
14825 // positive. It's an important idiom.
14826 if (IntegerLiteral *I
14827 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
14828 if (I->getValue() == 1) {
14829 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
14830 return IntRange(R.Width, /*NonNegative*/ true);
14831 }
14832 }
14833 [[fallthrough]];
14834
14835 case BO_ShlAssign:
14836 return IntRange::forValueOfType(C, GetExprType(E));
14837
14838 // Right shift by a constant can narrow its left argument.
14839 case BO_Shr:
14840 case BO_ShrAssign: {
14841 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
14842 Approximate);
14843
14844 // If the shift amount is a positive constant, drop the width by
14845 // that much.
14846 if (std::optional<llvm::APSInt> shift =
14847 BO->getRHS()->getIntegerConstantExpr(C)) {
14848 if (shift->isNonNegative()) {
14849 if (shift->uge(L.Width))
14850 L.Width = (L.NonNegative ? 0 : 1);
14851 else
14852 L.Width -= shift->getZExtValue();
14853 }
14854 }
14855
14856 return L;
14857 }
14858
14859 // Comma acts as its right operand.
14860 case BO_Comma:
14861 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
14862 Approximate);
14863
14864 case BO_Add:
14865 if (!Approximate)
14866 Combine = IntRange::sum;
14867 break;
14868
14869 case BO_Sub:
14870 if (BO->getLHS()->getType()->isPointerType())
14871 return IntRange::forValueOfType(C, GetExprType(E));
14872 if (!Approximate)
14873 Combine = IntRange::difference;
14874 break;
14875
14876 case BO_Mul:
14877 if (!Approximate)
14878 Combine = IntRange::product;
14879 break;
14880
14881 // The width of a division result is mostly determined by the size
14882 // of the LHS.
14883 case BO_Div: {
14884 // Don't 'pre-truncate' the operands.
14885 unsigned opWidth = C.getIntWidth(GetExprType(E));
14886 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
14887 Approximate);
14888
14889 // If the divisor is constant, use that.
14890 if (std::optional<llvm::APSInt> divisor =
14891 BO->getRHS()->getIntegerConstantExpr(C)) {
14892 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
14893 if (log2 >= L.Width)
14894 L.Width = (L.NonNegative ? 0 : 1);
14895 else
14896 L.Width = std::min(L.Width - log2, MaxWidth);
14897 return L;
14898 }
14899
14900 // Otherwise, just use the LHS's width.
14901 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
14902 // could be -1.
14903 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
14904 Approximate);
14905 return IntRange(L.Width, L.NonNegative && R.NonNegative);
14906 }
14907
14908 case BO_Rem:
14909 Combine = IntRange::rem;
14910 break;
14911
14912 // The default behavior is okay for these.
14913 case BO_Xor:
14914 case BO_Or:
14915 break;
14916 }
14917
14918 // Combine the two ranges, but limit the result to the type in which we
14919 // performed the computation.
14920 QualType T = GetExprType(E);
14921 unsigned opWidth = C.getIntWidth(T);
14922 IntRange L =
14923 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
14924 IntRange R =
14925 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
14926 IntRange C = Combine(L, R);
14927 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
14928 C.Width = std::min(C.Width, MaxWidth);
14929 return C;
14930 }
14931
14932 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
14933 switch (UO->getOpcode()) {
14934 // Boolean-valued operations are white-listed.
14935 case UO_LNot:
14936 return IntRange::forBoolType();
14937
14938 // Operations with opaque sources are black-listed.
14939 case UO_Deref:
14940 case UO_AddrOf: // should be impossible
14941 return IntRange::forValueOfType(C, GetExprType(E));
14942
14943 default:
14944 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
14945 Approximate);
14946 }
14947 }
14948
14949 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
14950 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
14951 Approximate);
14952
14953 if (const auto *BitField = E->getSourceBitField())
14954 return IntRange(BitField->getBitWidthValue(C),
14955 BitField->getType()->isUnsignedIntegerOrEnumerationType());
14956
14957 return IntRange::forValueOfType(C, GetExprType(E));
14958}
14959
14960static IntRange GetExprRange(ASTContext &C, const Expr *E,
14961 bool InConstantContext, bool Approximate) {
14962 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
14963 Approximate);
14964}
14965
14966/// Checks whether the given value, which currently has the given
14967/// source semantics, has the same value when coerced through the
14968/// target semantics.
14969static bool IsSameFloatAfterCast(const llvm::APFloat &value,
14970 const llvm::fltSemantics &Src,
14971 const llvm::fltSemantics &Tgt) {
14972 llvm::APFloat truncated = value;
14973
14974 bool ignored;
14975 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
14976 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
14977
14978 return truncated.bitwiseIsEqual(value);
14979}
14980
14981/// Checks whether the given value, which currently has the given
14982/// source semantics, has the same value when coerced through the
14983/// target semantics.
14984///
14985/// The value might be a vector of floats (or a complex number).
14986static bool IsSameFloatAfterCast(const APValue &value,
14987 const llvm::fltSemantics &Src,
14988 const llvm::fltSemantics &Tgt) {
14989 if (value.isFloat())
14990 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
14991
14992 if (value.isVector()) {
14993 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
14994 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
14995 return false;
14996 return true;
14997 }
14998
14999 assert(value.isComplexFloat());
15000 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
15001 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
15002}
15003
15004static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
15005 bool IsListInit = false);
15006
15007static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
15008 // Suppress cases where we are comparing against an enum constant.
15009 if (const DeclRefExpr *DR =
15010 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
15011 if (isa<EnumConstantDecl>(DR->getDecl()))
15012 return true;
15013
15014 // Suppress cases where the value is expanded from a macro, unless that macro
15015 // is how a language represents a boolean literal. This is the case in both C
15016 // and Objective-C.
15017 SourceLocation BeginLoc = E->getBeginLoc();
15018 if (BeginLoc.isMacroID()) {
15019 StringRef MacroName = Lexer::getImmediateMacroName(
15020 BeginLoc, S.getSourceManager(), S.getLangOpts());
15021 return MacroName != "YES" && MacroName != "NO" &&
15022 MacroName != "true" && MacroName != "false";
15023 }
15024
15025 return false;
15026}
15027
15029 return E->getType()->isIntegerType() &&
15030 (!E->getType()->isSignedIntegerType() ||
15032}
15033
15034namespace {
15035/// The promoted range of values of a type. In general this has the
15036/// following structure:
15037///
15038/// |-----------| . . . |-----------|
15039/// ^ ^ ^ ^
15040/// Min HoleMin HoleMax Max
15041///
15042/// ... where there is only a hole if a signed type is promoted to unsigned
15043/// (in which case Min and Max are the smallest and largest representable
15044/// values).
15045struct PromotedRange {
15046 // Min, or HoleMax if there is a hole.
15047 llvm::APSInt PromotedMin;
15048 // Max, or HoleMin if there is a hole.
15049 llvm::APSInt PromotedMax;
15050
15051 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
15052 if (R.Width == 0)
15053 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
15054 else if (R.Width >= BitWidth && !Unsigned) {
15055 // Promotion made the type *narrower*. This happens when promoting
15056 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
15057 // Treat all values of 'signed int' as being in range for now.
15058 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
15059 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
15060 } else {
15061 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
15062 .extOrTrunc(BitWidth);
15063 PromotedMin.setIsUnsigned(Unsigned);
15064
15065 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
15066 .extOrTrunc(BitWidth);
15067 PromotedMax.setIsUnsigned(Unsigned);
15068 }
15069 }
15070
15071 // Determine whether this range is contiguous (has no hole).
15072 bool isContiguous() const { return PromotedMin <= PromotedMax; }
15073
15074 // Where a constant value is within the range.
15075 enum ComparisonResult {
15076 LT = 0x1,
15077 LE = 0x2,
15078 GT = 0x4,
15079 GE = 0x8,
15080 EQ = 0x10,
15081 NE = 0x20,
15082 InRangeFlag = 0x40,
15083
15084 Less = LE | LT | NE,
15085 Min = LE | InRangeFlag,
15086 InRange = InRangeFlag,
15087 Max = GE | InRangeFlag,
15088 Greater = GE | GT | NE,
15089
15090 OnlyValue = LE | GE | EQ | InRangeFlag,
15091 InHole = NE
15092 };
15093
15094 ComparisonResult compare(const llvm::APSInt &Value) const {
15095 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
15096 Value.isUnsigned() == PromotedMin.isUnsigned());
15097 if (!isContiguous()) {
15098 assert(Value.isUnsigned() && "discontiguous range for signed compare");
15099 if (Value.isMinValue()) return Min;
15100 if (Value.isMaxValue()) return Max;
15101 if (Value >= PromotedMin) return InRange;
15102 if (Value <= PromotedMax) return InRange;
15103 return InHole;
15104 }
15105
15106 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
15107 case -1: return Less;
15108 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
15109 case 1:
15110 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
15111 case -1: return InRange;
15112 case 0: return Max;
15113 case 1: return Greater;
15114 }
15115 }
15116
15117 llvm_unreachable("impossible compare result");
15118 }
15119
15120 static std::optional<StringRef>
15121 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
15122 if (Op == BO_Cmp) {
15123 ComparisonResult LTFlag = LT, GTFlag = GT;
15124 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
15125
15126 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
15127 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
15128 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
15129 return std::nullopt;
15130 }
15131
15132 ComparisonResult TrueFlag, FalseFlag;
15133 if (Op == BO_EQ) {
15134 TrueFlag = EQ;
15135 FalseFlag = NE;
15136 } else if (Op == BO_NE) {
15137 TrueFlag = NE;
15138 FalseFlag = EQ;
15139 } else {
15140 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
15141 TrueFlag = LT;
15142 FalseFlag = GE;
15143 } else {
15144 TrueFlag = GT;
15145 FalseFlag = LE;
15146 }
15147 if (Op == BO_GE || Op == BO_LE)
15148 std::swap(TrueFlag, FalseFlag);
15149 }
15150 if (R & TrueFlag)
15151 return StringRef("true");
15152 if (R & FalseFlag)
15153 return StringRef("false");
15154 return std::nullopt;
15155 }
15156};
15157}
15158
15159static bool HasEnumType(Expr *E) {
15160 // Strip off implicit integral promotions.
15161 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
15162 if (ICE->getCastKind() != CK_IntegralCast &&
15163 ICE->getCastKind() != CK_NoOp)
15164 break;
15165 E = ICE->getSubExpr();
15166 }
15167
15168 return E->getType()->isEnumeralType();
15169}
15170
15171static int classifyConstantValue(Expr *Constant) {
15172 // The values of this enumeration are used in the diagnostics
15173 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
15174 enum ConstantValueKind {
15175 Miscellaneous = 0,
15176 LiteralTrue,
15177 LiteralFalse
15178 };
15179 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
15180 return BL->getValue() ? ConstantValueKind::LiteralTrue
15181 : ConstantValueKind::LiteralFalse;
15182 return ConstantValueKind::Miscellaneous;
15183}
15184
15186 Expr *Constant, Expr *Other,
15187 const llvm::APSInt &Value,
15188 bool RhsConstant) {
15190 return false;
15191
15192 Expr *OriginalOther = Other;
15193
15194 Constant = Constant->IgnoreParenImpCasts();
15195 Other = Other->IgnoreParenImpCasts();
15196
15197 // Suppress warnings on tautological comparisons between values of the same
15198 // enumeration type. There are only two ways we could warn on this:
15199 // - If the constant is outside the range of representable values of
15200 // the enumeration. In such a case, we should warn about the cast
15201 // to enumeration type, not about the comparison.
15202 // - If the constant is the maximum / minimum in-range value. For an
15203 // enumeratin type, such comparisons can be meaningful and useful.
15204 if (Constant->getType()->isEnumeralType() &&
15205 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
15206 return false;
15207
15208 IntRange OtherValueRange = GetExprRange(
15209 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
15210
15211 QualType OtherT = Other->getType();
15212 if (const auto *AT = OtherT->getAs<AtomicType>())
15213 OtherT = AT->getValueType();
15214 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
15215
15216 // Special case for ObjC BOOL on targets where its a typedef for a signed char
15217 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
15218 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
15219 S.NSAPIObj->isObjCBOOLType(OtherT) &&
15220 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
15221
15222 // Whether we're treating Other as being a bool because of the form of
15223 // expression despite it having another type (typically 'int' in C).
15224 bool OtherIsBooleanDespiteType =
15225 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
15226 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
15227 OtherTypeRange = OtherValueRange = IntRange::forBoolType();
15228
15229 // Check if all values in the range of possible values of this expression
15230 // lead to the same comparison outcome.
15231 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
15232 Value.isUnsigned());
15233 auto Cmp = OtherPromotedValueRange.compare(Value);
15234 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
15235 if (!Result)
15236 return false;
15237
15238 // Also consider the range determined by the type alone. This allows us to
15239 // classify the warning under the proper diagnostic group.
15240 bool TautologicalTypeCompare = false;
15241 {
15242 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
15243 Value.isUnsigned());
15244 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
15245 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
15246 RhsConstant)) {
15247 TautologicalTypeCompare = true;
15248 Cmp = TypeCmp;
15250 }
15251 }
15252
15253 // Don't warn if the non-constant operand actually always evaluates to the
15254 // same value.
15255 if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
15256 return false;
15257
15258 // Suppress the diagnostic for an in-range comparison if the constant comes
15259 // from a macro or enumerator. We don't want to diagnose
15260 //
15261 // some_long_value <= INT_MAX
15262 //
15263 // when sizeof(int) == sizeof(long).
15264 bool InRange = Cmp & PromotedRange::InRangeFlag;
15265 if (InRange && IsEnumConstOrFromMacro(S, Constant))
15266 return false;
15267
15268 // A comparison of an unsigned bit-field against 0 is really a type problem,
15269 // even though at the type level the bit-field might promote to 'signed int'.
15270 if (Other->refersToBitField() && InRange && Value == 0 &&
15271 Other->getType()->isUnsignedIntegerOrEnumerationType())
15272 TautologicalTypeCompare = true;
15273
15274 // If this is a comparison to an enum constant, include that
15275 // constant in the diagnostic.
15276 const EnumConstantDecl *ED = nullptr;
15277 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
15278 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
15279
15280 // Should be enough for uint128 (39 decimal digits)
15281 SmallString<64> PrettySourceValue;
15282 llvm::raw_svector_ostream OS(PrettySourceValue);
15283 if (ED) {
15284 OS << '\'' << *ED << "' (" << Value << ")";
15285 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
15286 Constant->IgnoreParenImpCasts())) {
15287 OS << (BL->getValue() ? "YES" : "NO");
15288 } else {
15289 OS << Value;
15290 }
15291
15292 if (!TautologicalTypeCompare) {
15293 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
15294 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
15295 << E->getOpcodeStr() << OS.str() << *Result
15296 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
15297 return true;
15298 }
15299
15300 if (IsObjCSignedCharBool) {
15302 S.PDiag(diag::warn_tautological_compare_objc_bool)
15303 << OS.str() << *Result);
15304 return true;
15305 }
15306
15307 // FIXME: We use a somewhat different formatting for the in-range cases and
15308 // cases involving boolean values for historical reasons. We should pick a
15309 // consistent way of presenting these diagnostics.
15310 if (!InRange || Other->isKnownToHaveBooleanValue()) {
15311
15313 E->getOperatorLoc(), E,
15314 S.PDiag(!InRange ? diag::warn_out_of_range_compare
15315 : diag::warn_tautological_bool_compare)
15316 << OS.str() << classifyConstantValue(Constant) << OtherT
15317 << OtherIsBooleanDespiteType << *Result
15318 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
15319 } else {
15320 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
15321 unsigned Diag =
15322 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
15323 ? (HasEnumType(OriginalOther)
15324 ? diag::warn_unsigned_enum_always_true_comparison
15325 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
15326 : diag::warn_unsigned_always_true_comparison)
15327 : diag::warn_tautological_constant_compare;
15328
15329 S.Diag(E->getOperatorLoc(), Diag)
15330 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
15331 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
15332 }
15333
15334 return true;
15335}
15336
15337/// Analyze the operands of the given comparison. Implements the
15338/// fallback case from AnalyzeComparison.
15342}
15343
15344/// Implements -Wsign-compare.
15345///
15346/// \param E the binary operator to check for warnings
15348 // The type the comparison is being performed in.
15349 QualType T = E->getLHS()->getType();
15350
15351 // Only analyze comparison operators where both sides have been converted to
15352 // the same type.
15354 return AnalyzeImpConvsInComparison(S, E);
15355
15356 // Don't analyze value-dependent comparisons directly.
15357 if (E->isValueDependent())
15358 return AnalyzeImpConvsInComparison(S, E);
15359
15360 Expr *LHS = E->getLHS();
15361 Expr *RHS = E->getRHS();
15362
15363 if (T->isIntegralType(S.Context)) {
15364 std::optional<llvm::APSInt> RHSValue =
15366 std::optional<llvm::APSInt> LHSValue =
15368
15369 // We don't care about expressions whose result is a constant.
15370 if (RHSValue && LHSValue)
15371 return AnalyzeImpConvsInComparison(S, E);
15372
15373 // We only care about expressions where just one side is literal
15374 if ((bool)RHSValue ^ (bool)LHSValue) {
15375 // Is the constant on the RHS or LHS?
15376 const bool RhsConstant = (bool)RHSValue;
15377 Expr *Const = RhsConstant ? RHS : LHS;
15378 Expr *Other = RhsConstant ? LHS : RHS;
15379 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
15380
15381 // Check whether an integer constant comparison results in a value
15382 // of 'true' or 'false'.
15383 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
15384 return AnalyzeImpConvsInComparison(S, E);
15385 }
15386 }
15387
15389 // We don't do anything special if this isn't an unsigned integral
15390 // comparison: we're only interested in integral comparisons, and
15391 // signed comparisons only happen in cases we don't care to warn about.
15392 return AnalyzeImpConvsInComparison(S, E);
15393 }
15394
15395 LHS = LHS->IgnoreParenImpCasts();
15396 RHS = RHS->IgnoreParenImpCasts();
15397
15398 if (!S.getLangOpts().CPlusPlus) {
15399 // Avoid warning about comparison of integers with different signs when
15400 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
15401 // the type of `E`.
15402 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
15403 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
15404 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
15405 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
15406 }
15407
15408 // Check to see if one of the (unmodified) operands is of different
15409 // signedness.
15410 Expr *signedOperand, *unsignedOperand;
15412 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
15413 "unsigned comparison between two signed integer expressions?");
15414 signedOperand = LHS;
15415 unsignedOperand = RHS;
15416 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
15417 signedOperand = RHS;
15418 unsignedOperand = LHS;
15419 } else {
15420 return AnalyzeImpConvsInComparison(S, E);
15421 }
15422
15423 // Otherwise, calculate the effective range of the signed operand.
15424 IntRange signedRange =
15425 GetExprRange(S.Context, signedOperand, S.isConstantEvaluatedContext(),
15426 /*Approximate=*/true);
15427
15428 // Go ahead and analyze implicit conversions in the operands. Note
15429 // that we skip the implicit conversions on both sides.
15432
15433 // If the signed range is non-negative, -Wsign-compare won't fire.
15434 if (signedRange.NonNegative)
15435 return;
15436
15437 // For (in)equality comparisons, if the unsigned operand is a
15438 // constant which cannot collide with a overflowed signed operand,
15439 // then reinterpreting the signed operand as unsigned will not
15440 // change the result of the comparison.
15441 if (E->isEqualityOp()) {
15442 unsigned comparisonWidth = S.Context.getIntWidth(T);
15443 IntRange unsignedRange =
15444 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
15445 /*Approximate=*/true);
15446
15447 // We should never be unable to prove that the unsigned operand is
15448 // non-negative.
15449 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
15450
15451 if (unsignedRange.Width < comparisonWidth)
15452 return;
15453 }
15454
15456 S.PDiag(diag::warn_mixed_sign_comparison)
15457 << LHS->getType() << RHS->getType()
15458 << LHS->getSourceRange() << RHS->getSourceRange());
15459}
15460
15461/// Analyzes an attempt to assign the given value to a bitfield.
15462///
15463/// Returns true if there was something fishy about the attempt.
15465 SourceLocation InitLoc) {
15466 assert(Bitfield->isBitField());
15467 if (Bitfield->isInvalidDecl())
15468 return false;
15469
15470 // White-list bool bitfields.
15471 QualType BitfieldType = Bitfield->getType();
15472 if (BitfieldType->isBooleanType())
15473 return false;
15474
15475 if (BitfieldType->isEnumeralType()) {
15476 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
15477 // If the underlying enum type was not explicitly specified as an unsigned
15478 // type and the enum contain only positive values, MSVC++ will cause an
15479 // inconsistency by storing this as a signed type.
15480 if (S.getLangOpts().CPlusPlus11 &&
15481 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
15482 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
15483 BitfieldEnumDecl->getNumNegativeBits() == 0) {
15484 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
15485 << BitfieldEnumDecl;
15486 }
15487 }
15488
15489 // Ignore value- or type-dependent expressions.
15490 if (Bitfield->getBitWidth()->isValueDependent() ||
15491 Bitfield->getBitWidth()->isTypeDependent() ||
15492 Init->isValueDependent() ||
15493 Init->isTypeDependent())
15494 return false;
15495
15496 Expr *OriginalInit = Init->IgnoreParenImpCasts();
15497 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
15498
15500 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
15502 // The RHS is not constant. If the RHS has an enum type, make sure the
15503 // bitfield is wide enough to hold all the values of the enum without
15504 // truncation.
15505 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
15506 EnumDecl *ED = EnumTy->getDecl();
15507 bool SignedBitfield = BitfieldType->isSignedIntegerType();
15508
15509 // Enum types are implicitly signed on Windows, so check if there are any
15510 // negative enumerators to see if the enum was intended to be signed or
15511 // not.
15512 bool SignedEnum = ED->getNumNegativeBits() > 0;
15513
15514 // Check for surprising sign changes when assigning enum values to a
15515 // bitfield of different signedness. If the bitfield is signed and we
15516 // have exactly the right number of bits to store this unsigned enum,
15517 // suggest changing the enum to an unsigned type. This typically happens
15518 // on Windows where unfixed enums always use an underlying type of 'int'.
15519 unsigned DiagID = 0;
15520 if (SignedEnum && !SignedBitfield) {
15521 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
15522 } else if (SignedBitfield && !SignedEnum &&
15523 ED->getNumPositiveBits() == FieldWidth) {
15524 DiagID = diag::warn_signed_bitfield_enum_conversion;
15525 }
15526
15527 if (DiagID) {
15528 S.Diag(InitLoc, DiagID) << Bitfield << ED;
15529 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
15530 SourceRange TypeRange =
15531 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
15532 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
15533 << SignedEnum << TypeRange;
15534 }
15535
15536 // Compute the required bitwidth. If the enum has negative values, we need
15537 // one more bit than the normal number of positive bits to represent the
15538 // sign bit.
15539 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
15540 ED->getNumNegativeBits())
15541 : ED->getNumPositiveBits();
15542
15543 // Check the bitwidth.
15544 if (BitsNeeded > FieldWidth) {
15545 Expr *WidthExpr = Bitfield->getBitWidth();
15546 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
15547 << Bitfield << ED;
15548 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
15549 << BitsNeeded << ED << WidthExpr->getSourceRange();
15550 }
15551 }
15552
15553 return false;
15554 }
15555
15556 llvm::APSInt Value = Result.Val.getInt();
15557
15558 unsigned OriginalWidth = Value.getBitWidth();
15559
15560 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
15561 // false positives where the user is demonstrating they intend to use the
15562 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
15563 // to a one-bit bit-field to see if the value came from a macro named 'true'.
15564 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
15565 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
15566 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
15567 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
15568 S.findMacroSpelling(MaybeMacroLoc, "true"))
15569 return false;
15570 }
15571
15572 if (!Value.isSigned() || Value.isNegative())
15573 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
15574 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
15575 OriginalWidth = Value.getSignificantBits();
15576
15577 if (OriginalWidth <= FieldWidth)
15578 return false;
15579
15580 // Compute the value which the bitfield will contain.
15581 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
15582 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
15583
15584 // Check whether the stored value is equal to the original value.
15585 TruncatedValue = TruncatedValue.extend(OriginalWidth);
15586 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
15587 return false;
15588
15589 std::string PrettyValue = toString(Value, 10);
15590 std::string PrettyTrunc = toString(TruncatedValue, 10);
15591
15592 S.Diag(InitLoc, OneAssignedToOneBitBitfield
15593 ? diag::warn_impcast_single_bit_bitield_precision_constant
15594 : diag::warn_impcast_bitfield_precision_constant)
15595 << PrettyValue << PrettyTrunc << OriginalInit->getType()
15596 << Init->getSourceRange();
15597
15598 return true;
15599}
15600
15601/// Analyze the given simple or compound assignment for warning-worthy
15602/// operations.
15604 // Just recurse on the LHS.
15606
15607 // We want to recurse on the RHS as normal unless we're assigning to
15608 // a bitfield.
15609 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
15610 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
15611 E->getOperatorLoc())) {
15612 // Recurse, ignoring any implicit conversions on the RHS.
15614 E->getOperatorLoc());
15615 }
15616 }
15617
15619
15620 // Diagnose implicitly sequentially-consistent atomic assignment.
15621 if (E->getLHS()->getType()->isAtomicType())
15622 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
15623}
15624
15625/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
15626static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
15627 SourceLocation CContext, unsigned diag,
15628 bool pruneControlFlow = false) {
15629 if (pruneControlFlow) {
15631 S.PDiag(diag)
15632 << SourceType << T << E->getSourceRange()
15633 << SourceRange(CContext));
15634 return;
15635 }
15636 S.Diag(E->getExprLoc(), diag)
15637 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
15638}
15639
15640/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
15641static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
15642 SourceLocation CContext,
15643 unsigned diag, bool pruneControlFlow = false) {
15644 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
15645}
15646
15648 return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
15649 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
15650}
15651
15653 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
15654 Expr *Ignored = SourceExpr->IgnoreImplicit();
15655 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
15656 Ignored = OVE->getSourceExpr();
15657 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
15658 isa<BinaryOperator>(Ignored) ||
15659 isa<CXXOperatorCallExpr>(Ignored);
15660 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
15661 if (NeedsParens)
15662 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
15663 << FixItHint::CreateInsertion(EndLoc, ")");
15664 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
15665}
15666
15667/// Diagnose an implicit cast from a floating point value to an integer value.
15669 SourceLocation CContext) {
15670 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
15671 const bool PruneWarnings = S.inTemplateInstantiation();
15672
15673 Expr *InnerE = E->IgnoreParenImpCasts();
15674 // We also want to warn on, e.g., "int i = -1.234"
15675 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
15676 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
15677 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
15678
15679 const bool IsLiteral =
15680 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
15681
15682 llvm::APFloat Value(0.0);
15683 bool IsConstant =
15685 if (!IsConstant) {
15686 if (isObjCSignedCharBool(S, T)) {
15688 S, E,
15689 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
15690 << E->getType());
15691 }
15692
15693 return DiagnoseImpCast(S, E, T, CContext,
15694 diag::warn_impcast_float_integer, PruneWarnings);
15695 }
15696
15697 bool isExact = false;
15698
15699 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
15701 llvm::APFloat::opStatus Result = Value.convertToInteger(
15702 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
15703
15704 // FIXME: Force the precision of the source value down so we don't print
15705 // digits which are usually useless (we don't really care here if we
15706 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
15707 // would automatically print the shortest representation, but it's a bit
15708 // tricky to implement.
15709 SmallString<16> PrettySourceValue;
15710 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
15711 precision = (precision * 59 + 195) / 196;
15712 Value.toString(PrettySourceValue, precision);
15713
15714 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
15716 S, E,
15717 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
15718 << PrettySourceValue);
15719 }
15720
15721 if (Result == llvm::APFloat::opOK && isExact) {
15722 if (IsLiteral) return;
15723 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
15724 PruneWarnings);
15725 }
15726
15727 // Conversion of a floating-point value to a non-bool integer where the
15728 // integral part cannot be represented by the integer type is undefined.
15729 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
15730 return DiagnoseImpCast(
15731 S, E, T, CContext,
15732 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
15733 : diag::warn_impcast_float_to_integer_out_of_range,
15734 PruneWarnings);
15735
15736 unsigned DiagID = 0;
15737 if (IsLiteral) {
15738 // Warn on floating point literal to integer.
15739 DiagID = diag::warn_impcast_literal_float_to_integer;
15740 } else if (IntegerValue == 0) {
15741 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
15742 return DiagnoseImpCast(S, E, T, CContext,
15743 diag::warn_impcast_float_integer, PruneWarnings);
15744 }
15745 // Warn on non-zero to zero conversion.
15746 DiagID = diag::warn_impcast_float_to_integer_zero;
15747 } else {
15748 if (IntegerValue.isUnsigned()) {
15749 if (!IntegerValue.isMaxValue()) {
15750 return DiagnoseImpCast(S, E, T, CContext,
15751 diag::warn_impcast_float_integer, PruneWarnings);
15752 }
15753 } else { // IntegerValue.isSigned()
15754 if (!IntegerValue.isMaxSignedValue() &&
15755 !IntegerValue.isMinSignedValue()) {
15756 return DiagnoseImpCast(S, E, T, CContext,
15757 diag::warn_impcast_float_integer, PruneWarnings);
15758 }
15759 }
15760 // Warn on evaluatable floating point expression to integer conversion.
15761 DiagID = diag::warn_impcast_float_to_integer;
15762 }
15763
15764 SmallString<16> PrettyTargetValue;
15765 if (IsBool)
15766 PrettyTargetValue = Value.isZero() ? "false" : "true";
15767 else
15768 IntegerValue.toString(PrettyTargetValue);
15769
15770 if (PruneWarnings) {
15772 S.PDiag(DiagID)
15773 << E->getType() << T.getUnqualifiedType()
15774 << PrettySourceValue << PrettyTargetValue
15775 << E->getSourceRange() << SourceRange(CContext));
15776 } else {
15777 S.Diag(E->getExprLoc(), DiagID)
15778 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
15779 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
15780 }
15781}
15782
15783/// Analyze the given compound assignment for the possible losing of
15784/// floating-point precision.
15786 assert(isa<CompoundAssignOperator>(E) &&
15787 "Must be compound assignment operation");
15788 // Recurse on the LHS and RHS in here
15791
15792 if (E->getLHS()->getType()->isAtomicType())
15793 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
15794
15795 // Now check the outermost expression
15796 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
15797 const auto *RBT = cast<CompoundAssignOperator>(E)
15798 ->getComputationResultType()
15799 ->getAs<BuiltinType>();
15800
15801 // The below checks assume source is floating point.
15802 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
15803
15804 // If source is floating point but target is an integer.
15805 if (ResultBT->isInteger())
15806 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
15807 E->getExprLoc(), diag::warn_impcast_float_integer);
15808
15809 if (!ResultBT->isFloatingPoint())
15810 return;
15811
15812 // If both source and target are floating points, warn about losing precision.
15814 QualType(ResultBT, 0), QualType(RBT, 0));
15815 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
15816 // warn about dropping FP rank.
15817 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
15818 diag::warn_impcast_float_result_precision);
15819}
15820
15821static std::string PrettyPrintInRange(const llvm::APSInt &Value,
15822 IntRange Range) {
15823 if (!Range.Width) return "0";
15824
15825 llvm::APSInt ValueInRange = Value;
15826 ValueInRange.setIsSigned(!Range.NonNegative);
15827 ValueInRange = ValueInRange.trunc(Range.Width);
15828 return toString(ValueInRange, 10);
15829}
15830
15831static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
15832 if (!isa<ImplicitCastExpr>(Ex))
15833 return false;
15834
15835 Expr *InnerE = Ex->IgnoreParenImpCasts();
15837 const Type *Source =
15839 if (Target->isDependentType())
15840 return false;
15841
15842 const BuiltinType *FloatCandidateBT =
15843 dyn_cast<BuiltinType>(ToBool ? Source : Target);
15844 const Type *BoolCandidateType = ToBool ? Target : Source;
15845
15846 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
15847 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
15848}
15849
15851 SourceLocation CC) {
15852 unsigned NumArgs = TheCall->getNumArgs();
15853 for (unsigned i = 0; i < NumArgs; ++i) {
15854 Expr *CurrA = TheCall->getArg(i);
15855 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
15856 continue;
15857
15858 bool IsSwapped = ((i > 0) &&
15859 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
15860 IsSwapped |= ((i < (NumArgs - 1)) &&
15861 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
15862 if (IsSwapped) {
15863 // Warn on this floating-point to bool conversion.
15865 CurrA->getType(), CC,
15866 diag::warn_impcast_floating_point_to_bool);
15867 }
15868 }
15869}
15870
15872 SourceLocation CC) {
15873 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
15874 E->getExprLoc()))
15875 return;
15876
15877 // Don't warn on functions which have return type nullptr_t.
15878 if (isa<CallExpr>(E))
15879 return;
15880
15881 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
15882 const Expr *NewE = E->IgnoreParenImpCasts();
15883 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
15884 bool HasNullPtrType = NewE->getType()->isNullPtrType();
15885 if (!IsGNUNullExpr && !HasNullPtrType)
15886 return;
15887
15888 // Return if target type is a safe conversion.
15889 if (T->isAnyPointerType() || T->isBlockPointerType() ||
15891 return;
15892
15894
15895 // Venture through the macro stacks to get to the source of macro arguments.
15896 // The new location is a better location than the complete location that was
15897 // passed in.
15898 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
15900
15901 // __null is usually wrapped in a macro. Go up a macro if that is the case.
15902 if (IsGNUNullExpr && Loc.isMacroID()) {
15903 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
15904 Loc, S.SourceMgr, S.getLangOpts());
15905 if (MacroName == "NULL")
15907 }
15908
15909 // Only warn if the null and context location are in the same macro expansion.
15910 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
15911 return;
15912
15913 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
15914 << HasNullPtrType << T << SourceRange(CC)
15917}
15918
15919static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
15920 ObjCArrayLiteral *ArrayLiteral);
15921
15922static void
15924 ObjCDictionaryLiteral *DictionaryLiteral);
15925
15926/// Check a single element within a collection literal against the
15927/// target element type.
15929 QualType TargetElementType,
15930 Expr *Element,
15931 unsigned ElementKind) {
15932 // Skip a bitcast to 'id' or qualified 'id'.
15933 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
15934 if (ICE->getCastKind() == CK_BitCast &&
15935 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
15936 Element = ICE->getSubExpr();
15937 }
15938
15939 QualType ElementType = Element->getType();
15940 ExprResult ElementResult(Element);
15941 if (ElementType->getAs<ObjCObjectPointerType>() &&
15942 S.CheckSingleAssignmentConstraints(TargetElementType,
15943 ElementResult,
15944 false, false)
15945 != Sema::Compatible) {
15946 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
15947 << ElementType << ElementKind << TargetElementType
15948 << Element->getSourceRange();
15949 }
15950
15951 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
15952 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
15953 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
15954 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
15955}
15956
15957/// Check an Objective-C array literal being converted to the given
15958/// target type.
15959static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
15960 ObjCArrayLiteral *ArrayLiteral) {
15961 if (!S.NSArrayDecl)
15962 return;
15963
15964 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
15965 if (!TargetObjCPtr)
15966 return;
15967
15968 if (TargetObjCPtr->isUnspecialized() ||
15969 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
15971 return;
15972
15973 auto TypeArgs = TargetObjCPtr->getTypeArgs();
15974 if (TypeArgs.size() != 1)
15975 return;
15976
15977 QualType TargetElementType = TypeArgs[0];
15978 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
15979 checkObjCCollectionLiteralElement(S, TargetElementType,
15980 ArrayLiteral->getElement(I),
15981 0);
15982 }
15983}
15984
15985/// Check an Objective-C dictionary literal being converted to the given
15986/// target type.
15987static void
15989 ObjCDictionaryLiteral *DictionaryLiteral) {
15990 if (!S.NSDictionaryDecl)
15991 return;
15992
15993 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
15994 if (!TargetObjCPtr)
15995 return;
15996
15997 if (TargetObjCPtr->isUnspecialized() ||
15998 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
16000 return;
16001
16002 auto TypeArgs = TargetObjCPtr->getTypeArgs();
16003 if (TypeArgs.size() != 2)
16004 return;
16005
16006 QualType TargetKeyType = TypeArgs[0];
16007 QualType TargetObjectType = TypeArgs[1];
16008 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
16009 auto Element = DictionaryLiteral->getKeyValueElement(I);
16010 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
16011 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
16012 }
16013}
16014
16015// Helper function to filter out cases for constant width constant conversion.
16016// Don't warn on char array initialization or for non-decimal values.
16018 SourceLocation CC) {
16019 // If initializing from a constant, and the constant starts with '0',
16020 // then it is a binary, octal, or hexadecimal. Allow these constants
16021 // to fill all the bits, even if there is a sign change.
16022 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
16023 const char FirstLiteralCharacter =
16024 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
16025 if (FirstLiteralCharacter == '0')
16026 return false;
16027 }
16028
16029 // If the CC location points to a '{', and the type is char, then assume
16030 // assume it is an array initialization.
16031 if (CC.isValid() && T->isCharType()) {
16032 const char FirstContextCharacter =
16034 if (FirstContextCharacter == '{')
16035 return false;
16036 }
16037
16038 return true;
16039}
16040
16042 const auto *IL = dyn_cast<IntegerLiteral>(E);
16043 if (!IL) {
16044 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
16045 if (UO->getOpcode() == UO_Minus)
16046 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
16047 }
16048 }
16049
16050 return IL;
16051}
16052
16054 E = E->IgnoreParenImpCasts();
16055 SourceLocation ExprLoc = E->getExprLoc();
16056
16057 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
16058 BinaryOperator::Opcode Opc = BO->getOpcode();
16060 // Do not diagnose unsigned shifts.
16061 if (Opc == BO_Shl) {
16062 const auto *LHS = getIntegerLiteral(BO->getLHS());
16063 const auto *RHS = getIntegerLiteral(BO->getRHS());
16064 if (LHS && LHS->getValue() == 0)
16065 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
16066 else if (!E->isValueDependent() && LHS && RHS &&
16067 RHS->getValue().isNonNegative() &&
16069 S.Diag(ExprLoc, diag::warn_left_shift_always)
16070 << (Result.Val.getInt() != 0);
16071 else if (E->getType()->isSignedIntegerType())
16072 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
16073 }
16074 }
16075
16076 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
16077 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
16078 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
16079 if (!LHS || !RHS)
16080 return;
16081 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
16082 (RHS->getValue() == 0 || RHS->getValue() == 1))
16083 // Do not diagnose common idioms.
16084 return;
16085 if (LHS->getValue() != 0 && RHS->getValue() != 0)
16086 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
16087 }
16088}
16089
16091 SourceLocation CC,
16092 bool *ICContext = nullptr,
16093 bool IsListInit = false) {
16094 if (E->isTypeDependent() || E->isValueDependent()) return;
16095
16096 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
16098 if (Source == Target) return;
16099 if (Target->isDependentType()) return;
16100
16101 // If the conversion context location is invalid don't complain. We also
16102 // don't want to emit a warning if the issue occurs from the expansion of
16103 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
16104 // delay this check as long as possible. Once we detect we are in that
16105 // scenario, we just return.
16106 if (CC.isInvalid())
16107 return;
16108
16109 if (Source->isAtomicType())
16110 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
16111
16112 // Diagnose implicit casts to bool.
16113 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
16114 if (isa<StringLiteral>(E))
16115 // Warn on string literal to bool. Checks for string literals in logical
16116 // and expressions, for instance, assert(0 && "error here"), are
16117 // prevented by a check in AnalyzeImplicitConversions().
16118 return DiagnoseImpCast(S, E, T, CC,
16119 diag::warn_impcast_string_literal_to_bool);
16120 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
16121 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
16122 // This covers the literal expressions that evaluate to Objective-C
16123 // objects.
16124 return DiagnoseImpCast(S, E, T, CC,
16125 diag::warn_impcast_objective_c_literal_to_bool);
16126 }
16127 if (Source->isPointerType() || Source->canDecayToPointerType()) {
16128 // Warn on pointer to bool conversion that is always true.
16129 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
16130 SourceRange(CC));
16131 }
16132 }
16133
16134 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
16135 // is a typedef for signed char (macOS), then that constant value has to be 1
16136 // or 0.
16137 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
16141 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
16143 S, E,
16144 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
16145 << toString(Result.Val.getInt(), 10));
16146 }
16147 return;
16148 }
16149 }
16150
16151 // Check implicit casts from Objective-C collection literals to specialized
16152 // collection types, e.g., NSArray<NSString *> *.
16153 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
16154 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
16155 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
16156 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
16157
16158 // Strip vector types.
16159 if (isa<VectorType>(Source)) {
16160 if (Target->isSveVLSBuiltinType() &&
16162 QualType(Source, 0)) ||
16164 QualType(Source, 0))))
16165 return;
16166
16167 if (Target->isRVVVLSBuiltinType() &&
16169 QualType(Source, 0)) ||
16171 QualType(Source, 0))))
16172 return;
16173
16174 if (!isa<VectorType>(Target)) {
16175 if (S.SourceMgr.isInSystemMacro(CC))
16176 return;
16177 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
16178 } else if (S.getLangOpts().HLSL &&
16179 Target->castAs<VectorType>()->getNumElements() <
16180 Source->castAs<VectorType>()->getNumElements()) {
16181 // Diagnose vector truncation but don't return. We may also want to
16182 // diagnose an element conversion.
16183 DiagnoseImpCast(S, E, T, CC, diag::warn_hlsl_impcast_vector_truncation);
16184 }
16185
16186 // If the vector cast is cast between two vectors of the same size, it is
16187 // a bitcast, not a conversion, except under HLSL where it is a conversion.
16188 if (!S.getLangOpts().HLSL &&
16190 return;
16191
16192 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
16193 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
16194 }
16195 if (auto VecTy = dyn_cast<VectorType>(Target))
16196 Target = VecTy->getElementType().getTypePtr();
16197
16198 // Strip complex types.
16199 if (isa<ComplexType>(Source)) {
16200 if (!isa<ComplexType>(Target)) {
16201 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
16202 return;
16203
16204 return DiagnoseImpCast(S, E, T, CC,
16205 S.getLangOpts().CPlusPlus
16206 ? diag::err_impcast_complex_scalar
16207 : diag::warn_impcast_complex_scalar);
16208 }
16209
16210 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
16211 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
16212 }
16213
16214 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
16215 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
16216
16217 // Strip SVE vector types
16218 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
16219 // Need the original target type for vector type checks
16220 const Type *OriginalTarget = S.Context.getCanonicalType(T).getTypePtr();
16221 // Handle conversion from scalable to fixed when msve-vector-bits is
16222 // specified
16223 if (S.Context.areCompatibleSveTypes(QualType(OriginalTarget, 0),
16224 QualType(Source, 0)) ||
16225 S.Context.areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
16226 QualType(Source, 0)))
16227 return;
16228
16229 // If the vector cast is cast between two vectors of the same size, it is
16230 // a bitcast, not a conversion.
16231 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
16232 return;
16233
16234 Source = SourceBT->getSveEltType(S.Context).getTypePtr();
16235 }
16236
16237 if (TargetBT && TargetBT->isSveVLSBuiltinType())
16238 Target = TargetBT->getSveEltType(S.Context).getTypePtr();
16239
16240 // If the source is floating point...
16241 if (SourceBT && SourceBT->isFloatingPoint()) {
16242 // ...and the target is floating point...
16243 if (TargetBT && TargetBT->isFloatingPoint()) {
16244 // ...then warn if we're dropping FP rank.
16245
16247 QualType(SourceBT, 0), QualType(TargetBT, 0));
16248 if (Order > 0) {
16249 // Don't warn about float constants that are precisely
16250 // representable in the target type.
16251 Expr::EvalResult result;
16252 if (E->EvaluateAsRValue(result, S.Context)) {
16253 // Value might be a float, a float vector, or a float complex.
16254 if (IsSameFloatAfterCast(result.Val,
16255 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
16256 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
16257 return;
16258 }
16259
16260 if (S.SourceMgr.isInSystemMacro(CC))
16261 return;
16262
16263 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
16264 }
16265 // ... or possibly if we're increasing rank, too
16266 else if (Order < 0) {
16267 if (S.SourceMgr.isInSystemMacro(CC))
16268 return;
16269
16270 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
16271 }
16272 return;
16273 }
16274
16275 // If the target is integral, always warn.
16276 if (TargetBT && TargetBT->isInteger()) {
16277 if (S.SourceMgr.isInSystemMacro(CC))
16278 return;
16279
16280 DiagnoseFloatingImpCast(S, E, T, CC);
16281 }
16282
16283 // Detect the case where a call result is converted from floating-point to
16284 // to bool, and the final argument to the call is converted from bool, to
16285 // discover this typo:
16286 //
16287 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
16288 //
16289 // FIXME: This is an incredibly special case; is there some more general
16290 // way to detect this class of misplaced-parentheses bug?
16291 if (Target->isBooleanType() && isa<CallExpr>(E)) {
16292 // Check last argument of function call to see if it is an
16293 // implicit cast from a type matching the type the result
16294 // is being cast to.
16295 CallExpr *CEx = cast<CallExpr>(E);
16296 if (unsigned NumArgs = CEx->getNumArgs()) {
16297 Expr *LastA = CEx->getArg(NumArgs - 1);
16298 Expr *InnerE = LastA->IgnoreParenImpCasts();
16299 if (isa<ImplicitCastExpr>(LastA) &&
16300 InnerE->getType()->isBooleanType()) {
16301 // Warn on this floating-point to bool conversion
16302 DiagnoseImpCast(S, E, T, CC,
16303 diag::warn_impcast_floating_point_to_bool);
16304 }
16305 }
16306 }
16307 return;
16308 }
16309
16310 // Valid casts involving fixed point types should be accounted for here.
16311 if (Source->isFixedPointType()) {
16312 if (Target->isUnsaturatedFixedPointType()) {
16316 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
16317 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
16318 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
16319 if (Value > MaxVal || Value < MinVal) {
16321 S.PDiag(diag::warn_impcast_fixed_point_range)
16322 << Value.toString() << T
16323 << E->getSourceRange()
16324 << clang::SourceRange(CC));
16325 return;
16326 }
16327 }
16328 } else if (Target->isIntegerType()) {
16330 if (!S.isConstantEvaluatedContext() &&
16333 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
16334
16335 bool Overflowed;
16336 llvm::APSInt IntResult = FXResult.convertToInt(
16338 Target->isSignedIntegerOrEnumerationType(), &Overflowed);
16339
16340 if (Overflowed) {
16342 S.PDiag(diag::warn_impcast_fixed_point_range)
16343 << FXResult.toString() << T
16344 << E->getSourceRange()
16345 << clang::SourceRange(CC));
16346 return;
16347 }
16348 }
16349 }
16350 } else if (Target->isUnsaturatedFixedPointType()) {
16351 if (Source->isIntegerType()) {
16353 if (!S.isConstantEvaluatedContext() &&
16355 llvm::APSInt Value = Result.Val.getInt();
16356
16357 bool Overflowed;
16358 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
16359 Value, S.Context.getFixedPointSemantics(T), &Overflowed);
16360
16361 if (Overflowed) {
16363 S.PDiag(diag::warn_impcast_fixed_point_range)
16364 << toString(Value, /*Radix=*/10) << T
16365 << E->getSourceRange()
16366 << clang::SourceRange(CC));
16367 return;
16368 }
16369 }
16370 }
16371 }
16372
16373 // If we are casting an integer type to a floating point type without
16374 // initialization-list syntax, we might lose accuracy if the floating
16375 // point type has a narrower significand than the integer type.
16376 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
16377 TargetBT->isFloatingType() && !IsListInit) {
16378 // Determine the number of precision bits in the source integer type.
16379 IntRange SourceRange =
16381 /*Approximate=*/true);
16382 unsigned int SourcePrecision = SourceRange.Width;
16383
16384 // Determine the number of precision bits in the
16385 // target floating point type.
16386 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
16387 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
16388
16389 if (SourcePrecision > 0 && TargetPrecision > 0 &&
16390 SourcePrecision > TargetPrecision) {
16391
16392 if (std::optional<llvm::APSInt> SourceInt =
16394 // If the source integer is a constant, convert it to the target
16395 // floating point type. Issue a warning if the value changes
16396 // during the whole conversion.
16397 llvm::APFloat TargetFloatValue(
16398 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
16399 llvm::APFloat::opStatus ConversionStatus =
16400 TargetFloatValue.convertFromAPInt(
16401 *SourceInt, SourceBT->isSignedInteger(),
16402 llvm::APFloat::rmNearestTiesToEven);
16403
16404 if (ConversionStatus != llvm::APFloat::opOK) {
16405 SmallString<32> PrettySourceValue;
16406 SourceInt->toString(PrettySourceValue, 10);
16407 SmallString<32> PrettyTargetValue;
16408 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
16409
16411 E->getExprLoc(), E,
16412 S.PDiag(diag::warn_impcast_integer_float_precision_constant)
16413 << PrettySourceValue << PrettyTargetValue << E->getType() << T
16414 << E->getSourceRange() << clang::SourceRange(CC));
16415 }
16416 } else {
16417 // Otherwise, the implicit conversion may lose precision.
16418 DiagnoseImpCast(S, E, T, CC,
16419 diag::warn_impcast_integer_float_precision);
16420 }
16421 }
16422 }
16423
16424 DiagnoseNullConversion(S, E, T, CC);
16425
16427
16428 if (Target->isBooleanType())
16430
16431 if (!Source->isIntegerType() || !Target->isIntegerType())
16432 return;
16433
16434 // TODO: remove this early return once the false positives for constant->bool
16435 // in templates, macros, etc, are reduced or removed.
16436 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
16437 return;
16438
16439 if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
16440 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
16442 S, E,
16443 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
16444 << E->getType());
16445 }
16446
16447 IntRange SourceTypeRange =
16448 IntRange::forTargetOfCanonicalType(S.Context, Source);
16449 IntRange LikelySourceRange = GetExprRange(
16450 S.Context, E, S.isConstantEvaluatedContext(), /*Approximate=*/true);
16451 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
16452
16453 if (LikelySourceRange.Width > TargetRange.Width) {
16454 // If the source is a constant, use a default-on diagnostic.
16455 // TODO: this should happen for bitfield stores, too.
16459 llvm::APSInt Value(32);
16460 Value = Result.Val.getInt();
16461
16462 if (S.SourceMgr.isInSystemMacro(CC))
16463 return;
16464
16465 std::string PrettySourceValue = toString(Value, 10);
16466 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
16467
16469 E->getExprLoc(), E,
16470 S.PDiag(diag::warn_impcast_integer_precision_constant)
16471 << PrettySourceValue << PrettyTargetValue << E->getType() << T
16472 << E->getSourceRange() << SourceRange(CC));
16473 return;
16474 }
16475
16476 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
16477 if (S.SourceMgr.isInSystemMacro(CC))
16478 return;
16479
16480 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
16481 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
16482 /* pruneControlFlow */ true);
16483 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
16484 }
16485
16486 if (TargetRange.Width > SourceTypeRange.Width) {
16487 if (auto *UO = dyn_cast<UnaryOperator>(E))
16488 if (UO->getOpcode() == UO_Minus)
16489 if (Source->isUnsignedIntegerType()) {
16490 if (Target->isUnsignedIntegerType())
16491 return DiagnoseImpCast(S, E, T, CC,
16492 diag::warn_impcast_high_order_zero_bits);
16493 if (Target->isSignedIntegerType())
16494 return DiagnoseImpCast(S, E, T, CC,
16495 diag::warn_impcast_nonnegative_result);
16496 }
16497 }
16498
16499 if (TargetRange.Width == LikelySourceRange.Width &&
16500 !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
16501 Source->isSignedIntegerType()) {
16502 // Warn when doing a signed to signed conversion, warn if the positive
16503 // source value is exactly the width of the target type, which will
16504 // cause a negative value to be stored.
16505
16508 !S.SourceMgr.isInSystemMacro(CC)) {
16509 llvm::APSInt Value = Result.Val.getInt();
16510 if (isSameWidthConstantConversion(S, E, T, CC)) {
16511 std::string PrettySourceValue = toString(Value, 10);
16512 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
16513
16515 E->getExprLoc(), E,
16516 S.PDiag(diag::warn_impcast_integer_precision_constant)
16517 << PrettySourceValue << PrettyTargetValue << E->getType() << T
16518 << E->getSourceRange() << SourceRange(CC));
16519 return;
16520 }
16521 }
16522
16523 // Fall through for non-constants to give a sign conversion warning.
16524 }
16525
16526 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
16527 ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
16528 (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
16529 LikelySourceRange.Width == TargetRange.Width))) {
16530 if (S.SourceMgr.isInSystemMacro(CC))
16531 return;
16532
16533 if (SourceBT && SourceBT->isInteger() && TargetBT &&
16534 TargetBT->isInteger() &&
16535 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
16536 return;
16537 }
16538
16539 unsigned DiagID = diag::warn_impcast_integer_sign;
16540
16541 // Traditionally, gcc has warned about this under -Wsign-compare.
16542 // We also want to warn about it in -Wconversion.
16543 // So if -Wconversion is off, use a completely identical diagnostic
16544 // in the sign-compare group.
16545 // The conditional-checking code will
16546 if (ICContext) {
16547 DiagID = diag::warn_impcast_integer_sign_conditional;
16548 *ICContext = true;
16549 }
16550
16551 return DiagnoseImpCast(S, E, T, CC, DiagID);
16552 }
16553
16554 // Diagnose conversions between different enumeration types.
16555 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
16556 // type, to give us better diagnostics.
16557 QualType SourceType = E->getEnumCoercedType(S.Context);
16558 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
16559
16560 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
16561 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
16562 if (SourceEnum->getDecl()->hasNameForLinkage() &&
16563 TargetEnum->getDecl()->hasNameForLinkage() &&
16564 SourceEnum != TargetEnum) {
16565 if (S.SourceMgr.isInSystemMacro(CC))
16566 return;
16567
16568 return DiagnoseImpCast(S, E, SourceType, T, CC,
16569 diag::warn_impcast_different_enum_types);
16570 }
16571}
16572
16575
16577 SourceLocation CC, bool &ICContext) {
16578 E = E->IgnoreParenImpCasts();
16579 // Diagnose incomplete type for second or third operand in C.
16580 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
16581 S.RequireCompleteExprType(E, diag::err_incomplete_type);
16582
16583 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
16584 return CheckConditionalOperator(S, CO, CC, T);
16585
16587 if (E->getType() != T)
16588 return CheckImplicitConversion(S, E, T, CC, &ICContext);
16589}
16590
16594
16595 Expr *TrueExpr = E->getTrueExpr();
16596 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
16597 TrueExpr = BCO->getCommon();
16598
16599 bool Suspicious = false;
16600 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
16601 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
16602
16603 if (T->isBooleanType())
16605
16606 // If -Wconversion would have warned about either of the candidates
16607 // for a signedness conversion to the context type...
16608 if (!Suspicious) return;
16609
16610 // ...but it's currently ignored...
16611 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
16612 return;
16613
16614 // ...then check whether it would have warned about either of the
16615 // candidates for a signedness conversion to the condition type.
16616 if (E->getType() == T) return;
16617
16618 Suspicious = false;
16620 E->getType(), CC, &Suspicious);
16621 if (!Suspicious)
16623 E->getType(), CC, &Suspicious);
16624}
16625
16626/// Check conversion of given expression to boolean.
16627/// Input argument E is a logical expression.
16629 // Run the bool-like conversion checks only for C since there bools are
16630 // still not used as the return type from "boolean" operators or as the input
16631 // type for conditional operators.
16632 if (S.getLangOpts().CPlusPlus)
16633 return;
16635 return;
16637}
16638
16639namespace {
16640struct AnalyzeImplicitConversionsWorkItem {
16641 Expr *E;
16642 SourceLocation CC;
16643 bool IsListInit;
16644};
16645}
16646
16647/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
16648/// that should be visited are added to WorkList.
16650 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
16652 Expr *OrigE = Item.E;
16653 SourceLocation CC = Item.CC;
16654
16655 QualType T = OrigE->getType();
16656 Expr *E = OrigE->IgnoreParenImpCasts();
16657
16658 // Propagate whether we are in a C++ list initialization expression.
16659 // If so, we do not issue warnings for implicit int-float conversion
16660 // precision loss, because C++11 narrowing already handles it.
16661 bool IsListInit = Item.IsListInit ||
16662 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
16663
16664 if (E->isTypeDependent() || E->isValueDependent())
16665 return;
16666
16667 Expr *SourceExpr = E;
16668 // Examine, but don't traverse into the source expression of an
16669 // OpaqueValueExpr, since it may have multiple parents and we don't want to
16670 // emit duplicate diagnostics. Its fine to examine the form or attempt to
16671 // evaluate it in the context of checking the specific conversion to T though.
16672 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
16673 if (auto *Src = OVE->getSourceExpr())
16674 SourceExpr = Src;
16675
16676 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
16677 if (UO->getOpcode() == UO_Not &&
16678 UO->getSubExpr()->isKnownToHaveBooleanValue())
16679 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
16680 << OrigE->getSourceRange() << T->isBooleanType()
16681 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
16682
16683 if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
16684 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
16685 BO->getLHS()->isKnownToHaveBooleanValue() &&
16686 BO->getRHS()->isKnownToHaveBooleanValue() &&
16687 BO->getLHS()->HasSideEffects(S.Context) &&
16688 BO->getRHS()->HasSideEffects(S.Context)) {
16690 const LangOptions &LO = S.getLangOpts();
16691 SourceLocation BLoc = BO->getOperatorLoc();
16692 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
16693 StringRef SR = clang::Lexer::getSourceText(
16694 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
16695 // To reduce false positives, only issue the diagnostic if the operator
16696 // is explicitly spelled as a punctuator. This suppresses the diagnostic
16697 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
16698 // in C, along with other macro spellings the user might invent.
16699 if (SR.str() == "&" || SR.str() == "|") {
16700
16701 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
16702 << (BO->getOpcode() == BO_And ? "&" : "|")
16703 << OrigE->getSourceRange()
16705 BO->getOperatorLoc(),
16706 (BO->getOpcode() == BO_And ? "&&" : "||"));
16707 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
16708 }
16709 }
16710
16711 // For conditional operators, we analyze the arguments as if they
16712 // were being fed directly into the output.
16713 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
16714 CheckConditionalOperator(S, CO, CC, T);
16715 return;
16716 }
16717
16718 // Check implicit argument conversions for function calls.
16719 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
16721
16722 // Go ahead and check any implicit conversions we might have skipped.
16723 // The non-canonical typecheck is just an optimization;
16724 // CheckImplicitConversion will filter out dead implicit conversions.
16725 if (SourceExpr->getType() != T)
16726 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
16727
16728 // Now continue drilling into this expression.
16729
16730 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
16731 // The bound subexpressions in a PseudoObjectExpr are not reachable
16732 // as transitive children.
16733 // FIXME: Use a more uniform representation for this.
16734 for (auto *SE : POE->semantics())
16735 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
16736 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
16737 }
16738
16739 // Skip past explicit casts.
16740 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
16741 E = CE->getSubExpr()->IgnoreParenImpCasts();
16742 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
16743 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
16744 WorkList.push_back({E, CC, IsListInit});
16745 return;
16746 }
16747
16748 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
16749 // Do a somewhat different check with comparison operators.
16750 if (BO->isComparisonOp())
16751 return AnalyzeComparison(S, BO);
16752
16753 // And with simple assignments.
16754 if (BO->getOpcode() == BO_Assign)
16755 return AnalyzeAssignment(S, BO);
16756 // And with compound assignments.
16757 if (BO->isAssignmentOp())
16758 return AnalyzeCompoundAssignment(S, BO);
16759 }
16760
16761 // These break the otherwise-useful invariant below. Fortunately,
16762 // we don't really need to recurse into them, because any internal
16763 // expressions should have been analyzed already when they were
16764 // built into statements.
16765 if (isa<StmtExpr>(E)) return;
16766
16767 // Don't descend into unevaluated contexts.
16768 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
16769
16770 // Now just recurse over the expression's children.
16771 CC = E->getExprLoc();
16772 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
16773 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
16774 for (Stmt *SubStmt : E->children()) {
16775 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
16776 if (!ChildExpr)
16777 continue;
16778
16779 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
16780 if (ChildExpr == CSE->getOperand())
16781 // Do not recurse over a CoroutineSuspendExpr's operand.
16782 // The operand is also a subexpression of getCommonExpr(), and
16783 // recursing into it directly would produce duplicate diagnostics.
16784 continue;
16785
16786 if (IsLogicalAndOperator &&
16787 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
16788 // Ignore checking string literals that are in logical and operators.
16789 // This is a common pattern for asserts.
16790 continue;
16791 WorkList.push_back({ChildExpr, CC, IsListInit});
16792 }
16793
16794 if (BO && BO->isLogicalOp()) {
16795 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
16796 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
16797 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
16798
16799 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
16800 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
16801 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
16802 }
16803
16804 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
16805 if (U->getOpcode() == UO_LNot) {
16806 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
16807 } else if (U->getOpcode() != UO_AddrOf) {
16808 if (U->getSubExpr()->getType()->isAtomicType())
16809 S.Diag(U->getSubExpr()->getBeginLoc(),
16810 diag::warn_atomic_implicit_seq_cst);
16811 }
16812 }
16813}
16814
16815/// AnalyzeImplicitConversions - Find and report any interesting
16816/// implicit conversions in the given expression. There are a couple
16817/// of competing diagnostics here, -Wconversion and -Wsign-compare.
16819 bool IsListInit/*= false*/) {
16821 WorkList.push_back({OrigE, CC, IsListInit});
16822 while (!WorkList.empty())
16823 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
16824}
16825
16826/// Diagnose integer type and any valid implicit conversion to it.
16827static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
16828 // Taking into account implicit conversions,
16829 // allow any integer.
16830 if (!E->getType()->isIntegerType()) {
16831 S.Diag(E->getBeginLoc(),
16832 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
16833 return true;
16834 }
16835 // Potentially emit standard warnings for implicit conversions if enabled
16836 // using -Wconversion.
16837 CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
16838 return false;
16839}
16840
16841// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
16842// Returns true when emitting a warning about taking the address of a reference.
16843static bool CheckForReference(Sema &SemaRef, const Expr *E,
16844 const PartialDiagnostic &PD) {
16845 E = E->IgnoreParenImpCasts();
16846
16847 const FunctionDecl *FD = nullptr;
16848
16849 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16850 if (!DRE->getDecl()->getType()->isReferenceType())
16851 return false;
16852 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
16853 if (!M->getMemberDecl()->getType()->isReferenceType())
16854 return false;
16855 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
16856 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
16857 return false;
16858 FD = Call->getDirectCallee();
16859 } else {
16860 return false;
16861 }
16862
16863 SemaRef.Diag(E->getExprLoc(), PD);
16864
16865 // If possible, point to location of function.
16866 if (FD) {
16867 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
16868 }
16869
16870 return true;
16871}
16872
16873// Returns true if the SourceLocation is expanded from any macro body.
16874// Returns false if the SourceLocation is invalid, is from not in a macro
16875// expansion, or is from expanded from a top-level macro argument.
16877 if (Loc.isInvalid())
16878 return false;
16879
16880 while (Loc.isMacroID()) {
16881 if (SM.isMacroBodyExpansion(Loc))
16882 return true;
16883 Loc = SM.getImmediateMacroCallerLoc(Loc);
16884 }
16885
16886 return false;
16887}
16888
16889/// Diagnose pointers that are always non-null.
16890/// \param E the expression containing the pointer
16891/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
16892/// compared to a null pointer
16893/// \param IsEqual True when the comparison is equal to a null pointer
16894/// \param Range Extra SourceRange to highlight in the diagnostic
16897 bool IsEqual, SourceRange Range) {
16898 if (!E)
16899 return;
16900
16901 // Don't warn inside macros.
16902 if (E->getExprLoc().isMacroID()) {
16904 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
16905 IsInAnyMacroBody(SM, Range.getBegin()))
16906 return;
16907 }
16908 E = E->IgnoreImpCasts();
16909
16910 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
16911
16912 if (isa<CXXThisExpr>(E)) {
16913 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
16914 : diag::warn_this_bool_conversion;
16915 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
16916 return;
16917 }
16918
16919 bool IsAddressOf = false;
16920
16921 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
16922 if (UO->getOpcode() != UO_AddrOf)
16923 return;
16924 IsAddressOf = true;
16925 E = UO->getSubExpr();
16926 }
16927
16928 if (IsAddressOf) {
16929 unsigned DiagID = IsCompare
16930 ? diag::warn_address_of_reference_null_compare
16931 : diag::warn_address_of_reference_bool_conversion;
16932 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
16933 << IsEqual;
16934 if (CheckForReference(*this, E, PD)) {
16935 return;
16936 }
16937 }
16938
16939 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
16940 bool IsParam = isa<NonNullAttr>(NonnullAttr);
16941 std::string Str;
16942 llvm::raw_string_ostream S(Str);
16943 E->printPretty(S, nullptr, getPrintingPolicy());
16944 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
16945 : diag::warn_cast_nonnull_to_bool;
16946 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
16947 << E->getSourceRange() << Range << IsEqual;
16948 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
16949 };
16950
16951 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
16952 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
16953 if (auto *Callee = Call->getDirectCallee()) {
16954 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
16955 ComplainAboutNonnullParamOrCall(A);
16956 return;
16957 }
16958 }
16959 }
16960
16961 // Complain if we are converting a lambda expression to a boolean value
16962 // outside of instantiation.
16963 if (!inTemplateInstantiation()) {
16964 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
16965 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
16966 MRecordDecl && MRecordDecl->isLambda()) {
16967 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
16968 << /*LambdaPointerConversionOperatorType=*/3
16969 << MRecordDecl->getSourceRange() << Range << IsEqual;
16970 return;
16971 }
16972 }
16973 }
16974
16975 // Expect to find a single Decl. Skip anything more complicated.
16976 ValueDecl *D = nullptr;
16977 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
16978 D = R->getDecl();
16979 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
16980 D = M->getMemberDecl();
16981 }
16982
16983 // Weak Decls can be null.
16984 if (!D || D->isWeak())
16985 return;
16986
16987 // Check for parameter decl with nonnull attribute
16988 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
16989 if (getCurFunction() &&
16990 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
16991 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
16992 ComplainAboutNonnullParamOrCall(A);
16993 return;
16994 }
16995
16996 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
16997 // Skip function template not specialized yet.
16999 return;
17000 auto ParamIter = llvm::find(FD->parameters(), PV);
17001 assert(ParamIter != FD->param_end());
17002 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
17003
17004 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
17005 if (!NonNull->args_size()) {
17006 ComplainAboutNonnullParamOrCall(NonNull);
17007 return;
17008 }
17009
17010 for (const ParamIdx &ArgNo : NonNull->args()) {
17011 if (ArgNo.getASTIndex() == ParamNo) {
17012 ComplainAboutNonnullParamOrCall(NonNull);
17013 return;
17014 }
17015 }
17016 }
17017 }
17018 }
17019 }
17020
17021 QualType T = D->getType();
17022 const bool IsArray = T->isArrayType();
17023 const bool IsFunction = T->isFunctionType();
17024
17025 // Address of function is used to silence the function warning.
17026 if (IsAddressOf && IsFunction) {
17027 return;
17028 }
17029
17030 // Found nothing.
17031 if (!IsAddressOf && !IsFunction && !IsArray)
17032 return;
17033
17034 // Pretty print the expression for the diagnostic.
17035 std::string Str;
17036 llvm::raw_string_ostream S(Str);
17037 E->printPretty(S, nullptr, getPrintingPolicy());
17038
17039 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
17040 : diag::warn_impcast_pointer_to_bool;
17041 enum {
17042 AddressOf,
17043 FunctionPointer,
17044 ArrayPointer
17045 } DiagType;
17046 if (IsAddressOf)
17047 DiagType = AddressOf;
17048 else if (IsFunction)
17049 DiagType = FunctionPointer;
17050 else if (IsArray)
17051 DiagType = ArrayPointer;
17052 else
17053 llvm_unreachable("Could not determine diagnostic.");
17054 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
17055 << Range << IsEqual;
17056
17057 if (!IsFunction)
17058 return;
17059
17060 // Suggest '&' to silence the function warning.
17061 Diag(E->getExprLoc(), diag::note_function_warning_silence)
17063
17064 // Check to see if '()' fixit should be emitted.
17065 QualType ReturnType;
17066 UnresolvedSet<4> NonTemplateOverloads;
17067 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
17068 if (ReturnType.isNull())
17069 return;
17070
17071 if (IsCompare) {
17072 // There are two cases here. If there is null constant, the only suggest
17073 // for a pointer return type. If the null is 0, then suggest if the return
17074 // type is a pointer or an integer type.
17075 if (!ReturnType->isPointerType()) {
17076 if (NullKind == Expr::NPCK_ZeroExpression ||
17077 NullKind == Expr::NPCK_ZeroLiteral) {
17078 if (!ReturnType->isIntegerType())
17079 return;
17080 } else {
17081 return;
17082 }
17083 }
17084 } else { // !IsCompare
17085 // For function to bool, only suggest if the function pointer has bool
17086 // return type.
17087 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
17088 return;
17089 }
17090 Diag(E->getExprLoc(), diag::note_function_to_function_call)
17092}
17093
17094/// Diagnoses "dangerous" implicit conversions within the given
17095/// expression (which is a full expression). Implements -Wconversion
17096/// and -Wsign-compare.
17097///
17098/// \param CC the "context" location of the implicit conversion, i.e.
17099/// the most location of the syntactic entity requiring the implicit
17100/// conversion
17101void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
17102 // Don't diagnose in unevaluated contexts.
17104 return;
17105
17106 // Don't diagnose for value- or type-dependent expressions.
17107 if (E->isTypeDependent() || E->isValueDependent())
17108 return;
17109
17110 // Check for array bounds violations in cases where the check isn't triggered
17111 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
17112 // ArraySubscriptExpr is on the RHS of a variable initialization.
17113 CheckArrayAccess(E);
17114
17115 // This is not the right CC for (e.g.) a variable initialization.
17116 AnalyzeImplicitConversions(*this, E, CC);
17117}
17118
17119/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
17120/// Input argument E is a logical expression.
17121void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
17122 ::CheckBoolLikeConversion(*this, E, CC);
17123}
17124
17125/// Diagnose when expression is an integer constant expression and its evaluation
17126/// results in integer overflow
17127void Sema::CheckForIntOverflow (const Expr *E) {
17128 // Use a work list to deal with nested struct initializers.
17129 SmallVector<const Expr *, 2> Exprs(1, E);
17130
17131 do {
17132 const Expr *OriginalE = Exprs.pop_back_val();
17133 const Expr *E = OriginalE->IgnoreParenCasts();
17134
17135 if (isa<BinaryOperator, UnaryOperator>(E)) {
17137 continue;
17138 }
17139
17140 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
17141 Exprs.append(InitList->inits().begin(), InitList->inits().end());
17142 else if (isa<ObjCBoxedExpr>(OriginalE))
17144 else if (const auto *Call = dyn_cast<CallExpr>(E))
17145 Exprs.append(Call->arg_begin(), Call->arg_end());
17146 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
17147 Exprs.append(Message->arg_begin(), Message->arg_end());
17148 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
17149 Exprs.append(Construct->arg_begin(), Construct->arg_end());
17150 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
17151 Exprs.push_back(Temporary->getSubExpr());
17152 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
17153 Exprs.push_back(Array->getIdx());
17154 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
17155 Exprs.push_back(Compound->getInitializer());
17156 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
17157 New && New->isArray()) {
17158 if (auto ArraySize = New->getArraySize())
17159 Exprs.push_back(*ArraySize);
17160 }
17161 } while (!Exprs.empty());
17162}
17163
17164namespace {
17165
17166/// Visitor for expressions which looks for unsequenced operations on the
17167/// same object.
17168class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
17170
17171 /// A tree of sequenced regions within an expression. Two regions are
17172 /// unsequenced if one is an ancestor or a descendent of the other. When we
17173 /// finish processing an expression with sequencing, such as a comma
17174 /// expression, we fold its tree nodes into its parent, since they are
17175 /// unsequenced with respect to nodes we will visit later.
17176 class SequenceTree {
17177 struct Value {
17178 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
17179 unsigned Parent : 31;
17180 LLVM_PREFERRED_TYPE(bool)
17181 unsigned Merged : 1;
17182 };
17183 SmallVector<Value, 8> Values;
17184
17185 public:
17186 /// A region within an expression which may be sequenced with respect
17187 /// to some other region.
17188 class Seq {
17189 friend class SequenceTree;
17190
17191 unsigned Index;
17192
17193 explicit Seq(unsigned N) : Index(N) {}
17194
17195 public:
17196 Seq() : Index(0) {}
17197 };
17198
17199 SequenceTree() { Values.push_back(Value(0)); }
17200 Seq root() const { return Seq(0); }
17201
17202 /// Create a new sequence of operations, which is an unsequenced
17203 /// subset of \p Parent. This sequence of operations is sequenced with
17204 /// respect to other children of \p Parent.
17205 Seq allocate(Seq Parent) {
17206 Values.push_back(Value(Parent.Index));
17207 return Seq(Values.size() - 1);
17208 }
17209
17210 /// Merge a sequence of operations into its parent.
17211 void merge(Seq S) {
17212 Values[S.Index].Merged = true;
17213 }
17214
17215 /// Determine whether two operations are unsequenced. This operation
17216 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
17217 /// should have been merged into its parent as appropriate.
17218 bool isUnsequenced(Seq Cur, Seq Old) {
17219 unsigned C = representative(Cur.Index);
17220 unsigned Target = representative(Old.Index);
17221 while (C >= Target) {
17222 if (C == Target)
17223 return true;
17224 C = Values[C].Parent;
17225 }
17226 return false;
17227 }
17228
17229 private:
17230 /// Pick a representative for a sequence.
17231 unsigned representative(unsigned K) {
17232 if (Values[K].Merged)
17233 // Perform path compression as we go.
17234 return Values[K].Parent = representative(Values[K].Parent);
17235 return K;
17236 }
17237 };
17238
17239 /// An object for which we can track unsequenced uses.
17240 using Object = const NamedDecl *;
17241
17242 /// Different flavors of object usage which we track. We only track the
17243 /// least-sequenced usage of each kind.
17244 enum UsageKind {
17245 /// A read of an object. Multiple unsequenced reads are OK.
17246 UK_Use,
17247
17248 /// A modification of an object which is sequenced before the value
17249 /// computation of the expression, such as ++n in C++.
17250 UK_ModAsValue,
17251
17252 /// A modification of an object which is not sequenced before the value
17253 /// computation of the expression, such as n++.
17254 UK_ModAsSideEffect,
17255
17256 UK_Count = UK_ModAsSideEffect + 1
17257 };
17258
17259 /// Bundle together a sequencing region and the expression corresponding
17260 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
17261 struct Usage {
17262 const Expr *UsageExpr = nullptr;
17263 SequenceTree::Seq Seq;
17264
17265 Usage() = default;
17266 };
17267
17268 struct UsageInfo {
17269 Usage Uses[UK_Count];
17270
17271 /// Have we issued a diagnostic for this object already?
17272 bool Diagnosed = false;
17273
17274 UsageInfo();
17275 };
17276 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
17277
17278 Sema &SemaRef;
17279
17280 /// Sequenced regions within the expression.
17281 SequenceTree Tree;
17282
17283 /// Declaration modifications and references which we have seen.
17284 UsageInfoMap UsageMap;
17285
17286 /// The region we are currently within.
17287 SequenceTree::Seq Region;
17288
17289 /// Filled in with declarations which were modified as a side-effect
17290 /// (that is, post-increment operations).
17291 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
17292
17293 /// Expressions to check later. We defer checking these to reduce
17294 /// stack usage.
17296
17297 /// RAII object wrapping the visitation of a sequenced subexpression of an
17298 /// expression. At the end of this process, the side-effects of the evaluation
17299 /// become sequenced with respect to the value computation of the result, so
17300 /// we downgrade any UK_ModAsSideEffect within the evaluation to
17301 /// UK_ModAsValue.
17302 struct SequencedSubexpression {
17303 SequencedSubexpression(SequenceChecker &Self)
17304 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
17305 Self.ModAsSideEffect = &ModAsSideEffect;
17306 }
17307
17308 ~SequencedSubexpression() {
17309 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
17310 // Add a new usage with usage kind UK_ModAsValue, and then restore
17311 // the previous usage with UK_ModAsSideEffect (thus clearing it if
17312 // the previous one was empty).
17313 UsageInfo &UI = Self.UsageMap[M.first];
17314 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
17315 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
17316 SideEffectUsage = M.second;
17317 }
17318 Self.ModAsSideEffect = OldModAsSideEffect;
17319 }
17320
17321 SequenceChecker &Self;
17322 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
17323 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
17324 };
17325
17326 /// RAII object wrapping the visitation of a subexpression which we might
17327 /// choose to evaluate as a constant. If any subexpression is evaluated and
17328 /// found to be non-constant, this allows us to suppress the evaluation of
17329 /// the outer expression.
17330 class EvaluationTracker {
17331 public:
17332 EvaluationTracker(SequenceChecker &Self)
17333 : Self(Self), Prev(Self.EvalTracker) {
17334 Self.EvalTracker = this;
17335 }
17336
17337 ~EvaluationTracker() {
17338 Self.EvalTracker = Prev;
17339 if (Prev)
17340 Prev->EvalOK &= EvalOK;
17341 }
17342
17343 bool evaluate(const Expr *E, bool &Result) {
17344 if (!EvalOK || E->isValueDependent())
17345 return false;
17346 EvalOK = E->EvaluateAsBooleanCondition(
17347 Result, Self.SemaRef.Context,
17348 Self.SemaRef.isConstantEvaluatedContext());
17349 return EvalOK;
17350 }
17351
17352 private:
17353 SequenceChecker &Self;
17354 EvaluationTracker *Prev;
17355 bool EvalOK = true;
17356 } *EvalTracker = nullptr;
17357
17358 /// Find the object which is produced by the specified expression,
17359 /// if any.
17360 Object getObject(const Expr *E, bool Mod) const {
17361 E = E->IgnoreParenCasts();
17362 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
17363 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
17364 return getObject(UO->getSubExpr(), Mod);
17365 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
17366 if (BO->getOpcode() == BO_Comma)
17367 return getObject(BO->getRHS(), Mod);
17368 if (Mod && BO->isAssignmentOp())
17369 return getObject(BO->getLHS(), Mod);
17370 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
17371 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
17372 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
17373 return ME->getMemberDecl();
17374 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
17375 // FIXME: If this is a reference, map through to its value.
17376 return DRE->getDecl();
17377 return nullptr;
17378 }
17379
17380 /// Note that an object \p O was modified or used by an expression
17381 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
17382 /// the object \p O as obtained via the \p UsageMap.
17383 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
17384 // Get the old usage for the given object and usage kind.
17385 Usage &U = UI.Uses[UK];
17386 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
17387 // If we have a modification as side effect and are in a sequenced
17388 // subexpression, save the old Usage so that we can restore it later
17389 // in SequencedSubexpression::~SequencedSubexpression.
17390 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
17391 ModAsSideEffect->push_back(std::make_pair(O, U));
17392 // Then record the new usage with the current sequencing region.
17393 U.UsageExpr = UsageExpr;
17394 U.Seq = Region;
17395 }
17396 }
17397
17398 /// Check whether a modification or use of an object \p O in an expression
17399 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
17400 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
17401 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
17402 /// usage and false we are checking for a mod-use unsequenced usage.
17403 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
17404 UsageKind OtherKind, bool IsModMod) {
17405 if (UI.Diagnosed)
17406 return;
17407
17408 const Usage &U = UI.Uses[OtherKind];
17409 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
17410 return;
17411
17412 const Expr *Mod = U.UsageExpr;
17413 const Expr *ModOrUse = UsageExpr;
17414 if (OtherKind == UK_Use)
17415 std::swap(Mod, ModOrUse);
17416
17417 SemaRef.DiagRuntimeBehavior(
17418 Mod->getExprLoc(), {Mod, ModOrUse},
17419 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
17420 : diag::warn_unsequenced_mod_use)
17421 << O << SourceRange(ModOrUse->getExprLoc()));
17422 UI.Diagnosed = true;
17423 }
17424
17425 // A note on note{Pre, Post}{Use, Mod}:
17426 //
17427 // (It helps to follow the algorithm with an expression such as
17428 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
17429 // operations before C++17 and both are well-defined in C++17).
17430 //
17431 // When visiting a node which uses/modify an object we first call notePreUse
17432 // or notePreMod before visiting its sub-expression(s). At this point the
17433 // children of the current node have not yet been visited and so the eventual
17434 // uses/modifications resulting from the children of the current node have not
17435 // been recorded yet.
17436 //
17437 // We then visit the children of the current node. After that notePostUse or
17438 // notePostMod is called. These will 1) detect an unsequenced modification
17439 // as side effect (as in "k++ + k") and 2) add a new usage with the
17440 // appropriate usage kind.
17441 //
17442 // We also have to be careful that some operation sequences modification as
17443 // side effect as well (for example: || or ,). To account for this we wrap
17444 // the visitation of such a sub-expression (for example: the LHS of || or ,)
17445 // with SequencedSubexpression. SequencedSubexpression is an RAII object
17446 // which record usages which are modifications as side effect, and then
17447 // downgrade them (or more accurately restore the previous usage which was a
17448 // modification as side effect) when exiting the scope of the sequenced
17449 // subexpression.
17450
17451 void notePreUse(Object O, const Expr *UseExpr) {
17452 UsageInfo &UI = UsageMap[O];
17453 // Uses conflict with other modifications.
17454 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
17455 }
17456
17457 void notePostUse(Object O, const Expr *UseExpr) {
17458 UsageInfo &UI = UsageMap[O];
17459 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
17460 /*IsModMod=*/false);
17461 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
17462 }
17463
17464 void notePreMod(Object O, const Expr *ModExpr) {
17465 UsageInfo &UI = UsageMap[O];
17466 // Modifications conflict with other modifications and with uses.
17467 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
17468 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
17469 }
17470
17471 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
17472 UsageInfo &UI = UsageMap[O];
17473 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
17474 /*IsModMod=*/true);
17475 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
17476 }
17477
17478public:
17479 SequenceChecker(Sema &S, const Expr *E,
17481 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
17482 Visit(E);
17483 // Silence a -Wunused-private-field since WorkList is now unused.
17484 // TODO: Evaluate if it can be used, and if not remove it.
17485 (void)this->WorkList;
17486 }
17487
17488 void VisitStmt(const Stmt *S) {
17489 // Skip all statements which aren't expressions for now.
17490 }
17491
17492 void VisitExpr(const Expr *E) {
17493 // By default, just recurse to evaluated subexpressions.
17494 Base::VisitStmt(E);
17495 }
17496
17497 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
17498 for (auto *Sub : CSE->children()) {
17499 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
17500 if (!ChildExpr)
17501 continue;
17502
17503 if (ChildExpr == CSE->getOperand())
17504 // Do not recurse over a CoroutineSuspendExpr's operand.
17505 // The operand is also a subexpression of getCommonExpr(), and
17506 // recursing into it directly could confuse object management
17507 // for the sake of sequence tracking.
17508 continue;
17509
17510 Visit(Sub);
17511 }
17512 }
17513
17514 void VisitCastExpr(const CastExpr *E) {
17515 Object O = Object();
17516 if (E->getCastKind() == CK_LValueToRValue)
17517 O = getObject(E->getSubExpr(), false);
17518
17519 if (O)
17520 notePreUse(O, E);
17521 VisitExpr(E);
17522 if (O)
17523 notePostUse(O, E);
17524 }
17525
17526 void VisitSequencedExpressions(const Expr *SequencedBefore,
17527 const Expr *SequencedAfter) {
17528 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
17529 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
17530 SequenceTree::Seq OldRegion = Region;
17531
17532 {
17533 SequencedSubexpression SeqBefore(*this);
17534 Region = BeforeRegion;
17535 Visit(SequencedBefore);
17536 }
17537
17538 Region = AfterRegion;
17539 Visit(SequencedAfter);
17540
17541 Region = OldRegion;
17542
17543 Tree.merge(BeforeRegion);
17544 Tree.merge(AfterRegion);
17545 }
17546
17547 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
17548 // C++17 [expr.sub]p1:
17549 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
17550 // expression E1 is sequenced before the expression E2.
17551 if (SemaRef.getLangOpts().CPlusPlus17)
17552 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
17553 else {
17554 Visit(ASE->getLHS());
17555 Visit(ASE->getRHS());
17556 }
17557 }
17558
17559 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
17560 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
17561 void VisitBinPtrMem(const BinaryOperator *BO) {
17562 // C++17 [expr.mptr.oper]p4:
17563 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
17564 // the expression E1 is sequenced before the expression E2.
17565 if (SemaRef.getLangOpts().CPlusPlus17)
17566 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
17567 else {
17568 Visit(BO->getLHS());
17569 Visit(BO->getRHS());
17570 }
17571 }
17572
17573 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
17574 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
17575 void VisitBinShlShr(const BinaryOperator *BO) {
17576 // C++17 [expr.shift]p4:
17577 // The expression E1 is sequenced before the expression E2.
17578 if (SemaRef.getLangOpts().CPlusPlus17)
17579 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
17580 else {
17581 Visit(BO->getLHS());
17582 Visit(BO->getRHS());
17583 }
17584 }
17585
17586 void VisitBinComma(const BinaryOperator *BO) {
17587 // C++11 [expr.comma]p1:
17588 // Every value computation and side effect associated with the left
17589 // expression is sequenced before every value computation and side
17590 // effect associated with the right expression.
17591 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
17592 }
17593
17594 void VisitBinAssign(const BinaryOperator *BO) {
17595 SequenceTree::Seq RHSRegion;
17596 SequenceTree::Seq LHSRegion;
17597 if (SemaRef.getLangOpts().CPlusPlus17) {
17598 RHSRegion = Tree.allocate(Region);
17599 LHSRegion = Tree.allocate(Region);
17600 } else {
17601 RHSRegion = Region;
17602 LHSRegion = Region;
17603 }
17604 SequenceTree::Seq OldRegion = Region;
17605
17606 // C++11 [expr.ass]p1:
17607 // [...] the assignment is sequenced after the value computation
17608 // of the right and left operands, [...]
17609 //
17610 // so check it before inspecting the operands and update the
17611 // map afterwards.
17612 Object O = getObject(BO->getLHS(), /*Mod=*/true);
17613 if (O)
17614 notePreMod(O, BO);
17615
17616 if (SemaRef.getLangOpts().CPlusPlus17) {
17617 // C++17 [expr.ass]p1:
17618 // [...] The right operand is sequenced before the left operand. [...]
17619 {
17620 SequencedSubexpression SeqBefore(*this);
17621 Region = RHSRegion;
17622 Visit(BO->getRHS());
17623 }
17624
17625 Region = LHSRegion;
17626 Visit(BO->getLHS());
17627
17628 if (O && isa<CompoundAssignOperator>(BO))
17629 notePostUse(O, BO);
17630
17631 } else {
17632 // C++11 does not specify any sequencing between the LHS and RHS.
17633 Region = LHSRegion;
17634 Visit(BO->getLHS());
17635
17636 if (O && isa<CompoundAssignOperator>(BO))
17637 notePostUse(O, BO);
17638
17639 Region = RHSRegion;
17640 Visit(BO->getRHS());
17641 }
17642
17643 // C++11 [expr.ass]p1:
17644 // the assignment is sequenced [...] before the value computation of the
17645 // assignment expression.
17646 // C11 6.5.16/3 has no such rule.
17647 Region = OldRegion;
17648 if (O)
17649 notePostMod(O, BO,
17650 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
17651 : UK_ModAsSideEffect);
17652 if (SemaRef.getLangOpts().CPlusPlus17) {
17653 Tree.merge(RHSRegion);
17654 Tree.merge(LHSRegion);
17655 }
17656 }
17657
17658 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
17659 VisitBinAssign(CAO);
17660 }
17661
17662 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
17663 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
17664 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
17665 Object O = getObject(UO->getSubExpr(), true);
17666 if (!O)
17667 return VisitExpr(UO);
17668
17669 notePreMod(O, UO);
17670 Visit(UO->getSubExpr());
17671 // C++11 [expr.pre.incr]p1:
17672 // the expression ++x is equivalent to x+=1
17673 notePostMod(O, UO,
17674 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
17675 : UK_ModAsSideEffect);
17676 }
17677
17678 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
17679 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
17680 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
17681 Object O = getObject(UO->getSubExpr(), true);
17682 if (!O)
17683 return VisitExpr(UO);
17684
17685 notePreMod(O, UO);
17686 Visit(UO->getSubExpr());
17687 notePostMod(O, UO, UK_ModAsSideEffect);
17688 }
17689
17690 void VisitBinLOr(const BinaryOperator *BO) {
17691 // C++11 [expr.log.or]p2:
17692 // If the second expression is evaluated, every value computation and
17693 // side effect associated with the first expression is sequenced before
17694 // every value computation and side effect associated with the
17695 // second expression.
17696 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
17697 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
17698 SequenceTree::Seq OldRegion = Region;
17699
17700 EvaluationTracker Eval(*this);
17701 {
17702 SequencedSubexpression Sequenced(*this);
17703 Region = LHSRegion;
17704 Visit(BO->getLHS());
17705 }
17706
17707 // C++11 [expr.log.or]p1:
17708 // [...] the second operand is not evaluated if the first operand
17709 // evaluates to true.
17710 bool EvalResult = false;
17711 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
17712 bool ShouldVisitRHS = !EvalOK || !EvalResult;
17713 if (ShouldVisitRHS) {
17714 Region = RHSRegion;
17715 Visit(BO->getRHS());
17716 }
17717
17718 Region = OldRegion;
17719 Tree.merge(LHSRegion);
17720 Tree.merge(RHSRegion);
17721 }
17722
17723 void VisitBinLAnd(const BinaryOperator *BO) {
17724 // C++11 [expr.log.and]p2:
17725 // If the second expression is evaluated, every value computation and
17726 // side effect associated with the first expression is sequenced before
17727 // every value computation and side effect associated with the
17728 // second expression.
17729 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
17730 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
17731 SequenceTree::Seq OldRegion = Region;
17732
17733 EvaluationTracker Eval(*this);
17734 {
17735 SequencedSubexpression Sequenced(*this);
17736 Region = LHSRegion;
17737 Visit(BO->getLHS());
17738 }
17739
17740 // C++11 [expr.log.and]p1:
17741 // [...] the second operand is not evaluated if the first operand is false.
17742 bool EvalResult = false;
17743 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
17744 bool ShouldVisitRHS = !EvalOK || EvalResult;
17745 if (ShouldVisitRHS) {
17746 Region = RHSRegion;
17747 Visit(BO->getRHS());
17748 }
17749
17750 Region = OldRegion;
17751 Tree.merge(LHSRegion);
17752 Tree.merge(RHSRegion);
17753 }
17754
17755 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
17756 // C++11 [expr.cond]p1:
17757 // [...] Every value computation and side effect associated with the first
17758 // expression is sequenced before every value computation and side effect
17759 // associated with the second or third expression.
17760 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
17761
17762 // No sequencing is specified between the true and false expression.
17763 // However since exactly one of both is going to be evaluated we can
17764 // consider them to be sequenced. This is needed to avoid warning on
17765 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
17766 // both the true and false expressions because we can't evaluate x.
17767 // This will still allow us to detect an expression like (pre C++17)
17768 // "(x ? y += 1 : y += 2) = y".
17769 //
17770 // We don't wrap the visitation of the true and false expression with
17771 // SequencedSubexpression because we don't want to downgrade modifications
17772 // as side effect in the true and false expressions after the visition
17773 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
17774 // not warn between the two "y++", but we should warn between the "y++"
17775 // and the "y".
17776 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
17777 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
17778 SequenceTree::Seq OldRegion = Region;
17779
17780 EvaluationTracker Eval(*this);
17781 {
17782 SequencedSubexpression Sequenced(*this);
17783 Region = ConditionRegion;
17784 Visit(CO->getCond());
17785 }
17786
17787 // C++11 [expr.cond]p1:
17788 // [...] The first expression is contextually converted to bool (Clause 4).
17789 // It is evaluated and if it is true, the result of the conditional
17790 // expression is the value of the second expression, otherwise that of the
17791 // third expression. Only one of the second and third expressions is
17792 // evaluated. [...]
17793 bool EvalResult = false;
17794 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
17795 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
17796 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
17797 if (ShouldVisitTrueExpr) {
17798 Region = TrueRegion;
17799 Visit(CO->getTrueExpr());
17800 }
17801 if (ShouldVisitFalseExpr) {
17802 Region = FalseRegion;
17803 Visit(CO->getFalseExpr());
17804 }
17805
17806 Region = OldRegion;
17807 Tree.merge(ConditionRegion);
17808 Tree.merge(TrueRegion);
17809 Tree.merge(FalseRegion);
17810 }
17811
17812 void VisitCallExpr(const CallExpr *CE) {
17813 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
17814
17815 if (CE->isUnevaluatedBuiltinCall(Context))
17816 return;
17817
17818 // C++11 [intro.execution]p15:
17819 // When calling a function [...], every value computation and side effect
17820 // associated with any argument expression, or with the postfix expression
17821 // designating the called function, is sequenced before execution of every
17822 // expression or statement in the body of the function [and thus before
17823 // the value computation of its result].
17824 SequencedSubexpression Sequenced(*this);
17825 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
17826 // C++17 [expr.call]p5
17827 // The postfix-expression is sequenced before each expression in the
17828 // expression-list and any default argument. [...]
17829 SequenceTree::Seq CalleeRegion;
17830 SequenceTree::Seq OtherRegion;
17831 if (SemaRef.getLangOpts().CPlusPlus17) {
17832 CalleeRegion = Tree.allocate(Region);
17833 OtherRegion = Tree.allocate(Region);
17834 } else {
17835 CalleeRegion = Region;
17836 OtherRegion = Region;
17837 }
17838 SequenceTree::Seq OldRegion = Region;
17839
17840 // Visit the callee expression first.
17841 Region = CalleeRegion;
17842 if (SemaRef.getLangOpts().CPlusPlus17) {
17843 SequencedSubexpression Sequenced(*this);
17844 Visit(CE->getCallee());
17845 } else {
17846 Visit(CE->getCallee());
17847 }
17848
17849 // Then visit the argument expressions.
17850 Region = OtherRegion;
17851 for (const Expr *Argument : CE->arguments())
17852 Visit(Argument);
17853
17854 Region = OldRegion;
17855 if (SemaRef.getLangOpts().CPlusPlus17) {
17856 Tree.merge(CalleeRegion);
17857 Tree.merge(OtherRegion);
17858 }
17859 });
17860 }
17861
17862 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
17863 // C++17 [over.match.oper]p2:
17864 // [...] the operator notation is first transformed to the equivalent
17865 // function-call notation as summarized in Table 12 (where @ denotes one
17866 // of the operators covered in the specified subclause). However, the
17867 // operands are sequenced in the order prescribed for the built-in
17868 // operator (Clause 8).
17869 //
17870 // From the above only overloaded binary operators and overloaded call
17871 // operators have sequencing rules in C++17 that we need to handle
17872 // separately.
17873 if (!SemaRef.getLangOpts().CPlusPlus17 ||
17874 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
17875 return VisitCallExpr(CXXOCE);
17876
17877 enum {
17878 NoSequencing,
17879 LHSBeforeRHS,
17880 RHSBeforeLHS,
17881 LHSBeforeRest
17882 } SequencingKind;
17883 switch (CXXOCE->getOperator()) {
17884 case OO_Equal:
17885 case OO_PlusEqual:
17886 case OO_MinusEqual:
17887 case OO_StarEqual:
17888 case OO_SlashEqual:
17889 case OO_PercentEqual:
17890 case OO_CaretEqual:
17891 case OO_AmpEqual:
17892 case OO_PipeEqual:
17893 case OO_LessLessEqual:
17894 case OO_GreaterGreaterEqual:
17895 SequencingKind = RHSBeforeLHS;
17896 break;
17897
17898 case OO_LessLess:
17899 case OO_GreaterGreater:
17900 case OO_AmpAmp:
17901 case OO_PipePipe:
17902 case OO_Comma:
17903 case OO_ArrowStar:
17904 case OO_Subscript:
17905 SequencingKind = LHSBeforeRHS;
17906 break;
17907
17908 case OO_Call:
17909 SequencingKind = LHSBeforeRest;
17910 break;
17911
17912 default:
17913 SequencingKind = NoSequencing;
17914 break;
17915 }
17916
17917 if (SequencingKind == NoSequencing)
17918 return VisitCallExpr(CXXOCE);
17919
17920 // This is a call, so all subexpressions are sequenced before the result.
17921 SequencedSubexpression Sequenced(*this);
17922
17923 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
17924 assert(SemaRef.getLangOpts().CPlusPlus17 &&
17925 "Should only get there with C++17 and above!");
17926 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
17927 "Should only get there with an overloaded binary operator"
17928 " or an overloaded call operator!");
17929
17930 if (SequencingKind == LHSBeforeRest) {
17931 assert(CXXOCE->getOperator() == OO_Call &&
17932 "We should only have an overloaded call operator here!");
17933
17934 // This is very similar to VisitCallExpr, except that we only have the
17935 // C++17 case. The postfix-expression is the first argument of the
17936 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
17937 // are in the following arguments.
17938 //
17939 // Note that we intentionally do not visit the callee expression since
17940 // it is just a decayed reference to a function.
17941 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
17942 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
17943 SequenceTree::Seq OldRegion = Region;
17944
17945 assert(CXXOCE->getNumArgs() >= 1 &&
17946 "An overloaded call operator must have at least one argument"
17947 " for the postfix-expression!");
17948 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
17949 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
17950 CXXOCE->getNumArgs() - 1);
17951
17952 // Visit the postfix-expression first.
17953 {
17954 Region = PostfixExprRegion;
17955 SequencedSubexpression Sequenced(*this);
17956 Visit(PostfixExpr);
17957 }
17958
17959 // Then visit the argument expressions.
17960 Region = ArgsRegion;
17961 for (const Expr *Arg : Args)
17962 Visit(Arg);
17963
17964 Region = OldRegion;
17965 Tree.merge(PostfixExprRegion);
17966 Tree.merge(ArgsRegion);
17967 } else {
17968 assert(CXXOCE->getNumArgs() == 2 &&
17969 "Should only have two arguments here!");
17970 assert((SequencingKind == LHSBeforeRHS ||
17971 SequencingKind == RHSBeforeLHS) &&
17972 "Unexpected sequencing kind!");
17973
17974 // We do not visit the callee expression since it is just a decayed
17975 // reference to a function.
17976 const Expr *E1 = CXXOCE->getArg(0);
17977 const Expr *E2 = CXXOCE->getArg(1);
17978 if (SequencingKind == RHSBeforeLHS)
17979 std::swap(E1, E2);
17980
17981 return VisitSequencedExpressions(E1, E2);
17982 }
17983 });
17984 }
17985
17986 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
17987 // This is a call, so all subexpressions are sequenced before the result.
17988 SequencedSubexpression Sequenced(*this);
17989
17990 if (!CCE->isListInitialization())
17991 return VisitExpr(CCE);
17992
17993 // In C++11, list initializations are sequenced.
17994 SequenceExpressionsInOrder(
17995 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
17996 }
17997
17998 void VisitInitListExpr(const InitListExpr *ILE) {
17999 if (!SemaRef.getLangOpts().CPlusPlus11)
18000 return VisitExpr(ILE);
18001
18002 // In C++11, list initializations are sequenced.
18003 SequenceExpressionsInOrder(ILE->inits());
18004 }
18005
18006 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
18007 // C++20 parenthesized list initializations are sequenced. See C++20
18008 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
18009 SequenceExpressionsInOrder(PLIE->getInitExprs());
18010 }
18011
18012private:
18013 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
18015 SequenceTree::Seq Parent = Region;
18016 for (const Expr *E : ExpressionList) {
18017 if (!E)
18018 continue;
18019 Region = Tree.allocate(Parent);
18020 Elts.push_back(Region);
18021 Visit(E);
18022 }
18023
18024 // Forget that the initializers are sequenced.
18025 Region = Parent;
18026 for (unsigned I = 0; I < Elts.size(); ++I)
18027 Tree.merge(Elts[I]);
18028 }
18029};
18030
18031SequenceChecker::UsageInfo::UsageInfo() = default;
18032
18033} // namespace
18034
18035void Sema::CheckUnsequencedOperations(const Expr *E) {
18037 WorkList.push_back(E);
18038 while (!WorkList.empty()) {
18039 const Expr *Item = WorkList.pop_back_val();
18040 SequenceChecker(*this, Item, WorkList);
18041 }
18042}
18043
18044void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
18045 bool IsConstexpr) {
18047 IsConstexpr || isa<ConstantExpr>(E));
18048 CheckImplicitConversions(E, CheckLoc);
18049 if (!E->isInstantiationDependent())
18050 CheckUnsequencedOperations(E);
18051 if (!IsConstexpr && !E->isValueDependent())
18052 CheckForIntOverflow(E);
18054}
18055
18056void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
18057 FieldDecl *BitField,
18058 Expr *Init) {
18059 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
18060}
18061
18063 SourceLocation Loc) {
18064 if (!PType->isVariablyModifiedType())
18065 return;
18066 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
18067 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
18068 return;
18069 }
18070 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
18071 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
18072 return;
18073 }
18074 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
18075 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
18076 return;
18077 }
18078
18079 const ArrayType *AT = S.Context.getAsArrayType(PType);
18080 if (!AT)
18081 return;
18082
18085 return;
18086 }
18087
18088 S.Diag(Loc, diag::err_array_star_in_function_definition);
18089}
18090
18091/// CheckParmsForFunctionDef - Check that the parameters of the given
18092/// function are appropriate for the definition of a function. This
18093/// takes care of any checks that cannot be performed on the
18094/// declaration itself, e.g., that the types of each of the function
18095/// parameters are complete.
18097 bool CheckParameterNames) {
18098 bool HasInvalidParm = false;
18099 for (ParmVarDecl *Param : Parameters) {
18100 assert(Param && "null in a parameter list");
18101 // C99 6.7.5.3p4: the parameters in a parameter type list in a
18102 // function declarator that is part of a function definition of
18103 // that function shall not have incomplete type.
18104 //
18105 // C++23 [dcl.fct.def.general]/p2
18106 // The type of a parameter [...] for a function definition
18107 // shall not be a (possibly cv-qualified) class type that is incomplete
18108 // or abstract within the function body unless the function is deleted.
18109 if (!Param->isInvalidDecl() &&
18110 (RequireCompleteType(Param->getLocation(), Param->getType(),
18111 diag::err_typecheck_decl_incomplete_type) ||
18112 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
18113 diag::err_abstract_type_in_decl,
18115 Param->setInvalidDecl();
18116 HasInvalidParm = true;
18117 }
18118
18119 // C99 6.9.1p5: If the declarator includes a parameter type list, the
18120 // declaration of each parameter shall include an identifier.
18121 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
18122 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
18123 // Diagnose this as an extension in C17 and earlier.
18124 if (!getLangOpts().C23)
18125 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
18126 }
18127
18128 // C99 6.7.5.3p12:
18129 // If the function declarator is not part of a definition of that
18130 // function, parameters may have incomplete type and may use the [*]
18131 // notation in their sequences of declarator specifiers to specify
18132 // variable length array types.
18133 QualType PType = Param->getOriginalType();
18134 // FIXME: This diagnostic should point the '[*]' if source-location
18135 // information is added for it.
18136 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
18137
18138 // If the parameter is a c++ class type and it has to be destructed in the
18139 // callee function, declare the destructor so that it can be called by the
18140 // callee function. Do not perform any direct access check on the dtor here.
18141 if (!Param->isInvalidDecl()) {
18142 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
18143 if (!ClassDecl->isInvalidDecl() &&
18144 !ClassDecl->hasIrrelevantDestructor() &&
18145 !ClassDecl->isDependentContext() &&
18146 ClassDecl->isParamDestroyedInCallee()) {
18148 MarkFunctionReferenced(Param->getLocation(), Destructor);
18149 DiagnoseUseOfDecl(Destructor, Param->getLocation());
18150 }
18151 }
18152 }
18153
18154 // Parameters with the pass_object_size attribute only need to be marked
18155 // constant at function definitions. Because we lack information about
18156 // whether we're on a declaration or definition when we're instantiating the
18157 // attribute, we need to check for constness here.
18158 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
18159 if (!Param->getType().isConstQualified())
18160 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
18161 << Attr->getSpelling() << 1;
18162
18163 // Check for parameter names shadowing fields from the class.
18164 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
18165 // The owning context for the parameter should be the function, but we
18166 // want to see if this function's declaration context is a record.
18167 DeclContext *DC = Param->getDeclContext();
18168 if (DC && DC->isFunctionOrMethod()) {
18169 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
18170 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
18171 RD, /*DeclIsField*/ false);
18172 }
18173 }
18174
18175 if (!Param->isInvalidDecl() &&
18176 Param->getOriginalType()->isWebAssemblyTableType()) {
18177 Param->setInvalidDecl();
18178 HasInvalidParm = true;
18179 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
18180 }
18181 }
18182
18183 return HasInvalidParm;
18184}
18185
18186std::optional<std::pair<
18188 *E,
18190 &Ctx);
18191
18192/// Compute the alignment and offset of the base class object given the
18193/// derived-to-base cast expression and the alignment and offset of the derived
18194/// class object.
18195static std::pair<CharUnits, CharUnits>
18197 CharUnits BaseAlignment, CharUnits Offset,
18198 ASTContext &Ctx) {
18199 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
18200 ++PathI) {
18201 const CXXBaseSpecifier *Base = *PathI;
18202 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
18203 if (Base->isVirtual()) {
18204 // The complete object may have a lower alignment than the non-virtual
18205 // alignment of the base, in which case the base may be misaligned. Choose
18206 // the smaller of the non-virtual alignment and BaseAlignment, which is a
18207 // conservative lower bound of the complete object alignment.
18208 CharUnits NonVirtualAlignment =
18210 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
18211 Offset = CharUnits::Zero();
18212 } else {
18213 const ASTRecordLayout &RL =
18214 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
18215 Offset += RL.getBaseClassOffset(BaseDecl);
18216 }
18217 DerivedType = Base->getType();
18218 }
18219
18220 return std::make_pair(BaseAlignment, Offset);
18221}
18222
18223/// Compute the alignment and offset of a binary additive operator.
18224static std::optional<std::pair<CharUnits, CharUnits>>
18226 bool IsSub, ASTContext &Ctx) {
18227 QualType PointeeType = PtrE->getType()->getPointeeType();
18228
18229 if (!PointeeType->isConstantSizeType())
18230 return std::nullopt;
18231
18232 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
18233
18234 if (!P)
18235 return std::nullopt;
18236
18237 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
18238 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
18239 CharUnits Offset = EltSize * IdxRes->getExtValue();
18240 if (IsSub)
18241 Offset = -Offset;
18242 return std::make_pair(P->first, P->second + Offset);
18243 }
18244
18245 // If the integer expression isn't a constant expression, compute the lower
18246 // bound of the alignment using the alignment and offset of the pointer
18247 // expression and the element size.
18248 return std::make_pair(
18249 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
18250 CharUnits::Zero());
18251}
18252
18253/// This helper function takes an lvalue expression and returns the alignment of
18254/// a VarDecl and a constant offset from the VarDecl.
18255std::optional<std::pair<
18256 CharUnits,
18258 ASTContext &Ctx) {
18259 E = E->IgnoreParens();
18260 switch (E->getStmtClass()) {
18261 default:
18262 break;
18263 case Stmt::CStyleCastExprClass:
18264 case Stmt::CXXStaticCastExprClass:
18265 case Stmt::ImplicitCastExprClass: {
18266 auto *CE = cast<CastExpr>(E);
18267 const Expr *From = CE->getSubExpr();
18268 switch (CE->getCastKind()) {
18269 default:
18270 break;
18271 case CK_NoOp:
18272 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
18273 case CK_UncheckedDerivedToBase:
18274 case CK_DerivedToBase: {
18275 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
18276 if (!P)
18277 break;
18278 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
18279 P->second, Ctx);
18280 }
18281 }
18282 break;
18283 }
18284 case Stmt::ArraySubscriptExprClass: {
18285 auto *ASE = cast<ArraySubscriptExpr>(E);
18287 false, Ctx);
18288 }
18289 case Stmt::DeclRefExprClass: {
18290 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
18291 // FIXME: If VD is captured by copy or is an escaping __block variable,
18292 // use the alignment of VD's type.
18293 if (!VD->getType()->isReferenceType()) {
18294 // Dependent alignment cannot be resolved -> bail out.
18295 if (VD->hasDependentAlignment())
18296 break;
18297 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
18298 }
18299 if (VD->hasInit())
18300 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
18301 }
18302 break;
18303 }
18304 case Stmt::MemberExprClass: {
18305 auto *ME = cast<MemberExpr>(E);
18306 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
18307 if (!FD || FD->getType()->isReferenceType() ||
18308 FD->getParent()->isInvalidDecl())
18309 break;
18310 std::optional<std::pair<CharUnits, CharUnits>> P;
18311 if (ME->isArrow())
18312 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
18313 else
18314 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
18315 if (!P)
18316 break;
18317 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
18318 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
18319 return std::make_pair(P->first,
18320 P->second + CharUnits::fromQuantity(Offset));
18321 }
18322 case Stmt::UnaryOperatorClass: {
18323 auto *UO = cast<UnaryOperator>(E);
18324 switch (UO->getOpcode()) {
18325 default:
18326 break;
18327 case UO_Deref:
18329 }
18330 break;
18331 }
18332 case Stmt::BinaryOperatorClass: {
18333 auto *BO = cast<BinaryOperator>(E);
18334 auto Opcode = BO->getOpcode();
18335 switch (Opcode) {
18336 default:
18337 break;
18338 case BO_Comma:
18340 }
18341 break;
18342 }
18343 }
18344 return std::nullopt;
18345}
18346
18347/// This helper function takes a pointer expression and returns the alignment of
18348/// a VarDecl and a constant offset from the VarDecl.
18349std::optional<std::pair<
18351 *E,
18353 &Ctx) {
18354 E = E->IgnoreParens();
18355 switch (E->getStmtClass()) {
18356 default:
18357 break;
18358 case Stmt::CStyleCastExprClass:
18359 case Stmt::CXXStaticCastExprClass:
18360 case Stmt::ImplicitCastExprClass: {
18361 auto *CE = cast<CastExpr>(E);
18362 const Expr *From = CE->getSubExpr();
18363 switch (CE->getCastKind()) {
18364 default:
18365 break;
18366 case CK_NoOp:
18367 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
18368 case CK_ArrayToPointerDecay:
18369 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
18370 case CK_UncheckedDerivedToBase:
18371 case CK_DerivedToBase: {
18372 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
18373 if (!P)
18374 break;
18376 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
18377 }
18378 }
18379 break;
18380 }
18381 case Stmt::CXXThisExprClass: {
18382 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
18384 return std::make_pair(Alignment, CharUnits::Zero());
18385 }
18386 case Stmt::UnaryOperatorClass: {
18387 auto *UO = cast<UnaryOperator>(E);
18388 if (UO->getOpcode() == UO_AddrOf)
18390 break;
18391 }
18392 case Stmt::BinaryOperatorClass: {
18393 auto *BO = cast<BinaryOperator>(E);
18394 auto Opcode = BO->getOpcode();
18395 switch (Opcode) {
18396 default:
18397 break;
18398 case BO_Add:
18399 case BO_Sub: {
18400 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
18401 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
18402 std::swap(LHS, RHS);
18403 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
18404 Ctx);
18405 }
18406 case BO_Comma:
18407 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
18408 }
18409 break;
18410 }
18411 }
18412 return std::nullopt;
18413}
18414
18416 // See if we can compute the alignment of a VarDecl and an offset from it.
18417 std::optional<std::pair<CharUnits, CharUnits>> P =
18419
18420 if (P)
18421 return P->first.alignmentAtOffset(P->second);
18422
18423 // If that failed, return the type's alignment.
18425}
18426
18427/// CheckCastAlign - Implements -Wcast-align, which warns when a
18428/// pointer cast increases the alignment requirements.
18430 // This is actually a lot of work to potentially be doing on every
18431 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
18432 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
18433 return;
18434
18435 // Ignore dependent types.
18436 if (T->isDependentType() || Op->getType()->isDependentType())
18437 return;
18438
18439 // Require that the destination be a pointer type.
18440 const PointerType *DestPtr = T->getAs<PointerType>();
18441 if (!DestPtr) return;
18442
18443 // If the destination has alignment 1, we're done.
18444 QualType DestPointee = DestPtr->getPointeeType();
18445 if (DestPointee->isIncompleteType()) return;
18446 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
18447 if (DestAlign.isOne()) return;
18448
18449 // Require that the source be a pointer type.
18450 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
18451 if (!SrcPtr) return;
18452 QualType SrcPointee = SrcPtr->getPointeeType();
18453
18454 // Explicitly allow casts from cv void*. We already implicitly
18455 // allowed casts to cv void*, since they have alignment 1.
18456 // Also allow casts involving incomplete types, which implicitly
18457 // includes 'void'.
18458 if (SrcPointee->isIncompleteType()) return;
18459
18460 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
18461
18462 if (SrcAlign >= DestAlign) return;
18463
18464 Diag(TRange.getBegin(), diag::warn_cast_align)
18465 << Op->getType() << T
18466 << static_cast<unsigned>(SrcAlign.getQuantity())
18467 << static_cast<unsigned>(DestAlign.getQuantity())
18468 << TRange << Op->getSourceRange();
18469}
18470
18471void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
18472 const ArraySubscriptExpr *ASE,
18473 bool AllowOnePastEnd, bool IndexNegated) {
18474 // Already diagnosed by the constant evaluator.
18476 return;
18477
18478 IndexExpr = IndexExpr->IgnoreParenImpCasts();
18479 if (IndexExpr->isValueDependent())
18480 return;
18481
18482 const Type *EffectiveType =
18484 BaseExpr = BaseExpr->IgnoreParenCasts();
18485 const ConstantArrayType *ArrayTy =
18487
18489 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
18490
18491 const Type *BaseType =
18492 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
18493 bool IsUnboundedArray =
18494 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
18495 Context, StrictFlexArraysLevel,
18496 /*IgnoreTemplateOrMacroSubstitution=*/true);
18497 if (EffectiveType->isDependentType() ||
18498 (!IsUnboundedArray && BaseType->isDependentType()))
18499 return;
18500
18503 return;
18504
18505 llvm::APSInt index = Result.Val.getInt();
18506 if (IndexNegated) {
18507 index.setIsUnsigned(false);
18508 index = -index;
18509 }
18510
18511 if (IsUnboundedArray) {
18512 if (EffectiveType->isFunctionType())
18513 return;
18514 if (index.isUnsigned() || !index.isNegative()) {
18515 const auto &ASTC = getASTContext();
18516 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
18517 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
18518 if (index.getBitWidth() < AddrBits)
18519 index = index.zext(AddrBits);
18520 std::optional<CharUnits> ElemCharUnits =
18521 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
18522 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
18523 // pointer) bounds-checking isn't meaningful.
18524 if (!ElemCharUnits || ElemCharUnits->isZero())
18525 return;
18526 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
18527 // If index has more active bits than address space, we already know
18528 // we have a bounds violation to warn about. Otherwise, compute
18529 // address of (index + 1)th element, and warn about bounds violation
18530 // only if that address exceeds address space.
18531 if (index.getActiveBits() <= AddrBits) {
18532 bool Overflow;
18533 llvm::APInt Product(index);
18534 Product += 1;
18535 Product = Product.umul_ov(ElemBytes, Overflow);
18536 if (!Overflow && Product.getActiveBits() <= AddrBits)
18537 return;
18538 }
18539
18540 // Need to compute max possible elements in address space, since that
18541 // is included in diag message.
18542 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
18543 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
18544 MaxElems += 1;
18545 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
18546 MaxElems = MaxElems.udiv(ElemBytes);
18547
18548 unsigned DiagID =
18549 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
18550 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
18551
18552 // Diag message shows element size in bits and in "bytes" (platform-
18553 // dependent CharUnits)
18554 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
18555 PDiag(DiagID)
18556 << toString(index, 10, true) << AddrBits
18557 << (unsigned)ASTC.toBits(*ElemCharUnits)
18558 << toString(ElemBytes, 10, false)
18559 << toString(MaxElems, 10, false)
18560 << (unsigned)MaxElems.getLimitedValue(~0U)
18561 << IndexExpr->getSourceRange());
18562
18563 const NamedDecl *ND = nullptr;
18564 // Try harder to find a NamedDecl to point at in the note.
18565 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
18566 BaseExpr = ASE->getBase()->IgnoreParenCasts();
18567 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
18568 ND = DRE->getDecl();
18569 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
18570 ND = ME->getMemberDecl();
18571
18572 if (ND)
18573 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
18574 PDiag(diag::note_array_declared_here) << ND);
18575 }
18576 return;
18577 }
18578
18579 if (index.isUnsigned() || !index.isNegative()) {
18580 // It is possible that the type of the base expression after
18581 // IgnoreParenCasts is incomplete, even though the type of the base
18582 // expression before IgnoreParenCasts is complete (see PR39746 for an
18583 // example). In this case we have no information about whether the array
18584 // access exceeds the array bounds. However we can still diagnose an array
18585 // access which precedes the array bounds.
18586 if (BaseType->isIncompleteType())
18587 return;
18588
18589 llvm::APInt size = ArrayTy->getSize();
18590
18591 if (BaseType != EffectiveType) {
18592 // Make sure we're comparing apples to apples when comparing index to
18593 // size.
18594 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
18595 uint64_t array_typesize = Context.getTypeSize(BaseType);
18596
18597 // Handle ptrarith_typesize being zero, such as when casting to void*.
18598 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
18599 if (!ptrarith_typesize)
18600 ptrarith_typesize = Context.getCharWidth();
18601
18602 if (ptrarith_typesize != array_typesize) {
18603 // There's a cast to a different size type involved.
18604 uint64_t ratio = array_typesize / ptrarith_typesize;
18605
18606 // TODO: Be smarter about handling cases where array_typesize is not a
18607 // multiple of ptrarith_typesize.
18608 if (ptrarith_typesize * ratio == array_typesize)
18609 size *= llvm::APInt(size.getBitWidth(), ratio);
18610 }
18611 }
18612
18613 if (size.getBitWidth() > index.getBitWidth())
18614 index = index.zext(size.getBitWidth());
18615 else if (size.getBitWidth() < index.getBitWidth())
18616 size = size.zext(index.getBitWidth());
18617
18618 // For array subscripting the index must be less than size, but for pointer
18619 // arithmetic also allow the index (offset) to be equal to size since
18620 // computing the next address after the end of the array is legal and
18621 // commonly done e.g. in C++ iterators and range-based for loops.
18622 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
18623 return;
18624
18625 // Suppress the warning if the subscript expression (as identified by the
18626 // ']' location) and the index expression are both from macro expansions
18627 // within a system header.
18628 if (ASE) {
18630 ASE->getRBracketLoc());
18631 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
18632 SourceLocation IndexLoc =
18633 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
18634 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
18635 return;
18636 }
18637 }
18638
18639 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
18640 : diag::warn_ptr_arith_exceeds_bounds;
18641 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
18642 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
18643
18645 BaseExpr->getBeginLoc(), BaseExpr,
18646 PDiag(DiagID) << toString(index, 10, true) << ArrayTy->desugar()
18647 << CastMsg << CastMsgTy << IndexExpr->getSourceRange());
18648 } else {
18649 unsigned DiagID = diag::warn_array_index_precedes_bounds;
18650 if (!ASE) {
18651 DiagID = diag::warn_ptr_arith_precedes_bounds;
18652 if (index.isNegative()) index = -index;
18653 }
18654
18655 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
18656 PDiag(DiagID) << toString(index, 10, true)
18657 << IndexExpr->getSourceRange());
18658 }
18659
18660 const NamedDecl *ND = nullptr;
18661 // Try harder to find a NamedDecl to point at in the note.
18662 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
18663 BaseExpr = ASE->getBase()->IgnoreParenCasts();
18664 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
18665 ND = DRE->getDecl();
18666 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
18667 ND = ME->getMemberDecl();
18668
18669 if (ND)
18670 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
18671 PDiag(diag::note_array_declared_here) << ND);
18672}
18673
18674void Sema::CheckArrayAccess(const Expr *expr) {
18675 int AllowOnePastEnd = 0;
18676 while (expr) {
18677 expr = expr->IgnoreParenImpCasts();
18678 switch (expr->getStmtClass()) {
18679 case Stmt::ArraySubscriptExprClass: {
18680 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
18681 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
18682 AllowOnePastEnd > 0);
18683 expr = ASE->getBase();
18684 break;
18685 }
18686 case Stmt::MemberExprClass: {
18687 expr = cast<MemberExpr>(expr)->getBase();
18688 break;
18689 }
18690 case Stmt::OMPArraySectionExprClass: {
18691 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
18692 if (ASE->getLowerBound())
18693 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
18694 /*ASE=*/nullptr, AllowOnePastEnd > 0);
18695 return;
18696 }
18697 case Stmt::UnaryOperatorClass: {
18698 // Only unwrap the * and & unary operators
18699 const UnaryOperator *UO = cast<UnaryOperator>(expr);
18700 expr = UO->getSubExpr();
18701 switch (UO->getOpcode()) {
18702 case UO_AddrOf:
18703 AllowOnePastEnd++;
18704 break;
18705 case UO_Deref:
18706 AllowOnePastEnd--;
18707 break;
18708 default:
18709 return;
18710 }
18711 break;
18712 }
18713 case Stmt::ConditionalOperatorClass: {
18714 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
18715 if (const Expr *lhs = cond->getLHS())
18716 CheckArrayAccess(lhs);
18717 if (const Expr *rhs = cond->getRHS())
18718 CheckArrayAccess(rhs);
18719 return;
18720 }
18721 case Stmt::CXXOperatorCallExprClass: {
18722 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
18723 for (const auto *Arg : OCE->arguments())
18724 CheckArrayAccess(Arg);
18725 return;
18726 }
18727 default:
18728 return;
18729 }
18730 }
18731}
18732
18733//===--- CHECK: Objective-C retain cycles ----------------------------------//
18734
18735namespace {
18736
18737struct RetainCycleOwner {
18738 VarDecl *Variable = nullptr;
18740 SourceLocation Loc;
18741 bool Indirect = false;
18742
18743 RetainCycleOwner() = default;
18744
18745 void setLocsFrom(Expr *e) {
18746 Loc = e->getExprLoc();
18747 Range = e->getSourceRange();
18748 }
18749};
18750
18751} // namespace
18752
18753/// Consider whether capturing the given variable can possibly lead to
18754/// a retain cycle.
18755static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
18756 // In ARC, it's captured strongly iff the variable has __strong
18757 // lifetime. In MRR, it's captured strongly if the variable is
18758 // __block and has an appropriate type.
18760 return false;
18761
18762 owner.Variable = var;
18763 if (ref)
18764 owner.setLocsFrom(ref);
18765 return true;
18766}
18767
18768static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
18769 while (true) {
18770 e = e->IgnoreParens();
18771 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
18772 switch (cast->getCastKind()) {
18773 case CK_BitCast:
18774 case CK_LValueBitCast:
18775 case CK_LValueToRValue:
18776 case CK_ARCReclaimReturnedObject:
18777 e = cast->getSubExpr();
18778 continue;
18779
18780 default:
18781 return false;
18782 }
18783 }
18784
18785 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
18786 ObjCIvarDecl *ivar = ref->getDecl();
18788 return false;
18789
18790 // Try to find a retain cycle in the base.
18791 if (!findRetainCycleOwner(S, ref->getBase(), owner))
18792 return false;
18793
18794 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
18795 owner.Indirect = true;
18796 return true;
18797 }
18798
18799 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
18800 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
18801 if (!var) return false;
18802 return considerVariable(var, ref, owner);
18803 }
18804
18805 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
18806 if (member->isArrow()) return false;
18807
18808 // Don't count this as an indirect ownership.
18809 e = member->getBase();
18810 continue;
18811 }
18812
18813 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
18814 // Only pay attention to pseudo-objects on property references.
18816 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
18817 ->IgnoreParens());
18818 if (!pre) return false;
18819 if (pre->isImplicitProperty()) return false;
18820 ObjCPropertyDecl *property = pre->getExplicitProperty();
18821 if (!property->isRetaining() &&
18822 !(property->getPropertyIvarDecl() &&
18823 property->getPropertyIvarDecl()->getType()
18824 .getObjCLifetime() == Qualifiers::OCL_Strong))
18825 return false;
18826
18827 owner.Indirect = true;
18828 if (pre->isSuperReceiver()) {
18829 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
18830 if (!owner.Variable)
18831 return false;
18832 owner.Loc = pre->getLocation();
18833 owner.Range = pre->getSourceRange();
18834 return true;
18835 }
18836 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
18837 ->getSourceExpr());
18838 continue;
18839 }
18840
18841 // Array ivars?
18842
18843 return false;
18844 }
18845}
18846
18847namespace {
18848
18849 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
18851 Expr *Capturer = nullptr;
18852 bool VarWillBeReased = false;
18853
18854 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
18855 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
18856 Variable(variable) {}
18857
18858 void VisitDeclRefExpr(DeclRefExpr *ref) {
18859 if (ref->getDecl() == Variable && !Capturer)
18860 Capturer = ref;
18861 }
18862
18863 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
18864 if (Capturer) return;
18865 Visit(ref->getBase());
18866 if (Capturer && ref->isFreeIvar())
18867 Capturer = ref;
18868 }
18869
18870 void VisitBlockExpr(BlockExpr *block) {
18871 // Look inside nested blocks
18872 if (block->getBlockDecl()->capturesVariable(Variable))
18873 Visit(block->getBlockDecl()->getBody());
18874 }
18875
18876 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
18877 if (Capturer) return;
18878 if (OVE->getSourceExpr())
18879 Visit(OVE->getSourceExpr());
18880 }
18881
18882 void VisitBinaryOperator(BinaryOperator *BinOp) {
18883 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
18884 return;
18885 Expr *LHS = BinOp->getLHS();
18886 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
18887 if (DRE->getDecl() != Variable)
18888 return;
18889 if (Expr *RHS = BinOp->getRHS()) {
18890 RHS = RHS->IgnoreParenCasts();
18891 std::optional<llvm::APSInt> Value;
18892 VarWillBeReased =
18893 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
18894 *Value == 0);
18895 }
18896 }
18897 }
18898 };
18899
18900} // namespace
18901
18902/// Check whether the given argument is a block which captures a
18903/// variable.
18904static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
18905 assert(owner.Variable && owner.Loc.isValid());
18906
18907 e = e->IgnoreParenCasts();
18908
18909 // Look through [^{...} copy] and Block_copy(^{...}).
18910 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
18911 Selector Cmd = ME->getSelector();
18912 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
18913 e = ME->getInstanceReceiver();
18914 if (!e)
18915 return nullptr;
18916 e = e->IgnoreParenCasts();
18917 }
18918 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
18919 if (CE->getNumArgs() == 1) {
18920 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
18921 if (Fn) {
18922 const IdentifierInfo *FnI = Fn->getIdentifier();
18923 if (FnI && FnI->isStr("_Block_copy")) {
18924 e = CE->getArg(0)->IgnoreParenCasts();
18925 }
18926 }
18927 }
18928 }
18929
18930 BlockExpr *block = dyn_cast<BlockExpr>(e);
18931 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
18932 return nullptr;
18933
18934 FindCaptureVisitor visitor(S.Context, owner.Variable);
18935 visitor.Visit(block->getBlockDecl()->getBody());
18936 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
18937}
18938
18939static void diagnoseRetainCycle(Sema &S, Expr *capturer,
18940 RetainCycleOwner &owner) {
18941 assert(capturer);
18942 assert(owner.Variable && owner.Loc.isValid());
18943
18944 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
18945 << owner.Variable << capturer->getSourceRange();
18946 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
18947 << owner.Indirect << owner.Range;
18948}
18949
18950/// Check for a keyword selector that starts with the word 'add' or
18951/// 'set'.
18953 if (sel.isUnarySelector()) return false;
18954
18955 StringRef str = sel.getNameForSlot(0);
18956 str = str.ltrim('_');
18957 if (str.starts_with("set"))
18958 str = str.substr(3);
18959 else if (str.starts_with("add")) {
18960 // Specially allow 'addOperationWithBlock:'.
18961 if (sel.getNumArgs() == 1 && str.starts_with("addOperationWithBlock"))
18962 return false;
18963 str = str.substr(3);
18964 } else
18965 return false;
18966
18967 if (str.empty()) return true;
18968 return !isLowercase(str.front());
18969}
18970
18971static std::optional<int>
18973 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
18974 Message->getReceiverInterface(),
18976 if (!IsMutableArray) {
18977 return std::nullopt;
18978 }
18979
18980 Selector Sel = Message->getSelector();
18981
18982 std::optional<NSAPI::NSArrayMethodKind> MKOpt =
18983 S.NSAPIObj->getNSArrayMethodKind(Sel);
18984 if (!MKOpt) {
18985 return std::nullopt;
18986 }
18987
18988 NSAPI::NSArrayMethodKind MK = *MKOpt;
18989
18990 switch (MK) {
18994 return 0;
18996 return 1;
18997
18998 default:
18999 return std::nullopt;
19000 }
19001
19002 return std::nullopt;
19003}
19004
19005static std::optional<int>
19007 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
19008 Message->getReceiverInterface(),
19010 if (!IsMutableDictionary) {
19011 return std::nullopt;
19012 }
19013
19014 Selector Sel = Message->getSelector();
19015
19016 std::optional<NSAPI::NSDictionaryMethodKind> MKOpt =
19017 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
19018 if (!MKOpt) {
19019 return std::nullopt;
19020 }
19021
19023
19024 switch (MK) {
19028 return 0;
19029
19030 default:
19031 return std::nullopt;
19032 }
19033
19034 return std::nullopt;
19035}
19036
19037static std::optional<int> GetNSSetArgumentIndex(Sema &S,
19038 ObjCMessageExpr *Message) {
19039 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
19040 Message->getReceiverInterface(),
19042
19043 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
19044 Message->getReceiverInterface(),
19046 if (!IsMutableSet && !IsMutableOrderedSet) {
19047 return std::nullopt;
19048 }
19049
19050 Selector Sel = Message->getSelector();
19051
19052 std::optional<NSAPI::NSSetMethodKind> MKOpt =
19053 S.NSAPIObj->getNSSetMethodKind(Sel);
19054 if (!MKOpt) {
19055 return std::nullopt;
19056 }
19057
19058 NSAPI::NSSetMethodKind MK = *MKOpt;
19059
19060 switch (MK) {
19065 return 0;
19067 return 1;
19068 }
19069
19070 return std::nullopt;
19071}
19072
19073void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
19074 if (!Message->isInstanceMessage()) {
19075 return;
19076 }
19077
19078 std::optional<int> ArgOpt;
19079
19080 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
19081 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
19082 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
19083 return;
19084 }
19085
19086 int ArgIndex = *ArgOpt;
19087
19088 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
19089 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
19090 Arg = OE->getSourceExpr()->IgnoreImpCasts();
19091 }
19092
19093 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
19094 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
19095 if (ArgRE->isObjCSelfExpr()) {
19096 Diag(Message->getSourceRange().getBegin(),
19097 diag::warn_objc_circular_container)
19098 << ArgRE->getDecl() << StringRef("'super'");
19099 }
19100 }
19101 } else {
19102 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
19103
19104 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
19105 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
19106 }
19107
19108 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
19109 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
19110 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
19111 ValueDecl *Decl = ReceiverRE->getDecl();
19112 Diag(Message->getSourceRange().getBegin(),
19113 diag::warn_objc_circular_container)
19114 << Decl << Decl;
19115 if (!ArgRE->isObjCSelfExpr()) {
19117 diag::note_objc_circular_container_declared_here)
19118 << Decl;
19119 }
19120 }
19121 }
19122 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
19123 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
19124 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
19125 ObjCIvarDecl *Decl = IvarRE->getDecl();
19126 Diag(Message->getSourceRange().getBegin(),
19127 diag::warn_objc_circular_container)
19128 << Decl << Decl;
19130 diag::note_objc_circular_container_declared_here)
19131 << Decl;
19132 }
19133 }
19134 }
19135 }
19136}
19137
19138/// Check a message send to see if it's likely to cause a retain cycle.
19140 // Only check instance methods whose selector looks like a setter.
19141 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
19142 return;
19143
19144 // Try to find a variable that the receiver is strongly owned by.
19145 RetainCycleOwner owner;
19147 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
19148 return;
19149 } else {
19151 owner.Variable = getCurMethodDecl()->getSelfDecl();
19152 owner.Loc = msg->getSuperLoc();
19153 owner.Range = msg->getSuperLoc();
19154 }
19155
19156 // Check whether the receiver is captured by any of the arguments.
19157 const ObjCMethodDecl *MD = msg->getMethodDecl();
19158 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
19159 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
19160 // noescape blocks should not be retained by the method.
19161 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
19162 continue;
19163 return diagnoseRetainCycle(*this, capturer, owner);
19164 }
19165 }
19166}
19167
19168/// Check a property assign to see if it's likely to cause a retain cycle.
19169void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
19170 RetainCycleOwner owner;
19171 if (!findRetainCycleOwner(*this, receiver, owner))
19172 return;
19173
19174 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
19175 diagnoseRetainCycle(*this, capturer, owner);
19176}
19177
19179 RetainCycleOwner Owner;
19180 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
19181 return;
19182
19183 // Because we don't have an expression for the variable, we have to set the
19184 // location explicitly here.
19185 Owner.Loc = Var->getLocation();
19186 Owner.Range = Var->getSourceRange();
19187
19188 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
19189 diagnoseRetainCycle(*this, Capturer, Owner);
19190}
19191
19193 Expr *RHS, bool isProperty) {
19194 // Check if RHS is an Objective-C object literal, which also can get
19195 // immediately zapped in a weak reference. Note that we explicitly
19196 // allow ObjCStringLiterals, since those are designed to never really die.
19197 RHS = RHS->IgnoreParenImpCasts();
19198
19199 // This enum needs to match with the 'select' in
19200 // warn_objc_arc_literal_assign (off-by-1).
19202 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
19203 return false;
19204
19205 S.Diag(Loc, diag::warn_arc_literal_assign)
19206 << (unsigned) Kind
19207 << (isProperty ? 0 : 1)
19208 << RHS->getSourceRange();
19209
19210 return true;
19211}
19212
19215 Expr *RHS, bool isProperty) {
19216 // Strip off any implicit cast added to get to the one ARC-specific.
19217 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
19218 if (cast->getCastKind() == CK_ARCConsumeObject) {
19219 S.Diag(Loc, diag::warn_arc_retained_assign)
19221 << (isProperty ? 0 : 1)
19222 << RHS->getSourceRange();
19223 return true;
19224 }
19225 RHS = cast->getSubExpr();
19226 }
19227
19228 if (LT == Qualifiers::OCL_Weak &&
19229 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
19230 return true;
19231
19232 return false;
19233}
19234
19236 QualType LHS, Expr *RHS) {
19238
19240 return false;
19241
19242 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
19243 return true;
19244
19245 return false;
19246}
19247
19249 Expr *LHS, Expr *RHS) {
19250 QualType LHSType;
19251 // PropertyRef on LHS type need be directly obtained from
19252 // its declaration as it has a PseudoType.
19254 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
19255 if (PRE && !PRE->isImplicitProperty()) {
19256 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
19257 if (PD)
19258 LHSType = PD->getType();
19259 }
19260
19261 if (LHSType.isNull())
19262 LHSType = LHS->getType();
19263
19265
19266 if (LT == Qualifiers::OCL_Weak) {
19267 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
19269 }
19270
19271 if (checkUnsafeAssigns(Loc, LHSType, RHS))
19272 return;
19273
19274 // FIXME. Check for other life times.
19275 if (LT != Qualifiers::OCL_None)
19276 return;
19277
19278 if (PRE) {
19279 if (PRE->isImplicitProperty())
19280 return;
19281 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
19282 if (!PD)
19283 return;
19284
19285 unsigned Attributes = PD->getPropertyAttributes();
19286 if (Attributes & ObjCPropertyAttribute::kind_assign) {
19287 // when 'assign' attribute was not explicitly specified
19288 // by user, ignore it and rely on property type itself
19289 // for lifetime info.
19290 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
19291 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
19292 LHSType->isObjCRetainableType())
19293 return;
19294
19295 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
19296 if (cast->getCastKind() == CK_ARCConsumeObject) {
19297 Diag(Loc, diag::warn_arc_retained_property_assign)
19298 << RHS->getSourceRange();
19299 return;
19300 }
19301 RHS = cast->getSubExpr();
19302 }
19303 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
19304 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
19305 return;
19306 }
19307 }
19308}
19309
19310//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
19311
19312static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
19313 SourceLocation StmtLoc,
19314 const NullStmt *Body) {
19315 // Do not warn if the body is a macro that expands to nothing, e.g:
19316 //
19317 // #define CALL(x)
19318 // if (condition)
19319 // CALL(0);
19320 if (Body->hasLeadingEmptyMacro())
19321 return false;
19322
19323 // Get line numbers of statement and body.
19324 bool StmtLineInvalid;
19325 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
19326 &StmtLineInvalid);
19327 if (StmtLineInvalid)
19328 return false;
19329
19330 bool BodyLineInvalid;
19331 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
19332 &BodyLineInvalid);
19333 if (BodyLineInvalid)
19334 return false;
19335
19336 // Warn if null statement and body are on the same line.
19337 if (StmtLine != BodyLine)
19338 return false;
19339
19340 return true;
19341}
19342
19344 const Stmt *Body,
19345 unsigned DiagID) {
19346 // Since this is a syntactic check, don't emit diagnostic for template
19347 // instantiations, this just adds noise.
19349 return;
19350
19351 // The body should be a null statement.
19352 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
19353 if (!NBody)
19354 return;
19355
19356 // Do the usual checks.
19357 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
19358 return;
19359
19360 Diag(NBody->getSemiLoc(), DiagID);
19361 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
19362}
19363
19365 const Stmt *PossibleBody) {
19366 assert(!CurrentInstantiationScope); // Ensured by caller
19367
19368 SourceLocation StmtLoc;
19369 const Stmt *Body;
19370 unsigned DiagID;
19371 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
19372 StmtLoc = FS->getRParenLoc();
19373 Body = FS->getBody();
19374 DiagID = diag::warn_empty_for_body;
19375 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
19376 StmtLoc = WS->getRParenLoc();
19377 Body = WS->getBody();
19378 DiagID = diag::warn_empty_while_body;
19379 } else
19380 return; // Neither `for' nor `while'.
19381
19382 // The body should be a null statement.
19383 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
19384 if (!NBody)
19385 return;
19386
19387 // Skip expensive checks if diagnostic is disabled.
19388 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
19389 return;
19390
19391 // Do the usual checks.
19392 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
19393 return;
19394
19395 // `for(...);' and `while(...);' are popular idioms, so in order to keep
19396 // noise level low, emit diagnostics only if for/while is followed by a
19397 // CompoundStmt, e.g.:
19398 // for (int i = 0; i < n; i++);
19399 // {
19400 // a(i);
19401 // }
19402 // or if for/while is followed by a statement with more indentation
19403 // than for/while itself:
19404 // for (int i = 0; i < n; i++);
19405 // a(i);
19406 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
19407 if (!ProbableTypo) {
19408 bool BodyColInvalid;
19409 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
19410 PossibleBody->getBeginLoc(), &BodyColInvalid);
19411 if (BodyColInvalid)
19412 return;
19413
19414 bool StmtColInvalid;
19415 unsigned StmtCol =
19416 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
19417 if (StmtColInvalid)
19418 return;
19419
19420 if (BodyCol > StmtCol)
19421 ProbableTypo = true;
19422 }
19423
19424 if (ProbableTypo) {
19425 Diag(NBody->getSemiLoc(), DiagID);
19426 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
19427 }
19428}
19429
19430//===--- CHECK: Warn on self move with std::move. -------------------------===//
19431
19432/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
19433void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
19434 SourceLocation OpLoc) {
19435 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
19436 return;
19437
19439 return;
19440
19441 // Strip parens and casts away.
19442 LHSExpr = LHSExpr->IgnoreParenImpCasts();
19443 RHSExpr = RHSExpr->IgnoreParenImpCasts();
19444
19445 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
19446 // which we can treat as an inlined std::move
19447 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
19448 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
19449 RHSExpr = CE->getArg(0);
19450 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
19451 CXXSCE && CXXSCE->isXValue())
19452 RHSExpr = CXXSCE->getSubExpr();
19453 else
19454 return;
19455
19456 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
19457 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
19458
19459 // Two DeclRefExpr's, check that the decls are the same.
19460 if (LHSDeclRef && RHSDeclRef) {
19461 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
19462 return;
19463 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
19464 RHSDeclRef->getDecl()->getCanonicalDecl())
19465 return;
19466
19467 auto D = Diag(OpLoc, diag::warn_self_move)
19468 << LHSExpr->getType() << LHSExpr->getSourceRange()
19469 << RHSExpr->getSourceRange();
19470 if (const FieldDecl *F =
19472 D << 1 << F
19473 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
19474 else
19475 D << 0;
19476 return;
19477 }
19478
19479 // Member variables require a different approach to check for self moves.
19480 // MemberExpr's are the same if every nested MemberExpr refers to the same
19481 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
19482 // the base Expr's are CXXThisExpr's.
19483 const Expr *LHSBase = LHSExpr;
19484 const Expr *RHSBase = RHSExpr;
19485 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
19486 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
19487 if (!LHSME || !RHSME)
19488 return;
19489
19490 while (LHSME && RHSME) {
19491 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
19492 RHSME->getMemberDecl()->getCanonicalDecl())
19493 return;
19494
19495 LHSBase = LHSME->getBase();
19496 RHSBase = RHSME->getBase();
19497 LHSME = dyn_cast<MemberExpr>(LHSBase);
19498 RHSME = dyn_cast<MemberExpr>(RHSBase);
19499 }
19500
19501 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
19502 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
19503 if (LHSDeclRef && RHSDeclRef) {
19504 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
19505 return;
19506 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
19507 RHSDeclRef->getDecl()->getCanonicalDecl())
19508 return;
19509
19510 Diag(OpLoc, diag::warn_self_move)
19511 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
19512 << RHSExpr->getSourceRange();
19513 return;
19514 }
19515
19516 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
19517 Diag(OpLoc, diag::warn_self_move)
19518 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
19519 << RHSExpr->getSourceRange();
19520}
19521
19522//===--- Layout compatibility ----------------------------------------------//
19523
19524static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
19525
19526/// Check if two enumeration types are layout-compatible.
19528 // C++11 [dcl.enum] p8:
19529 // Two enumeration types are layout-compatible if they have the same
19530 // underlying type.
19531 return ED1->isComplete() && ED2->isComplete() &&
19532 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
19533}
19534
19535/// Check if two fields are layout-compatible.
19536/// Can be used on union members, which are exempt from alignment requirement
19537/// of common initial sequence.
19539 FieldDecl *Field2,
19540 bool AreUnionMembers = false) {
19541 [[maybe_unused]] const Type *Field1Parent =
19542 Field1->getParent()->getTypeForDecl();
19543 [[maybe_unused]] const Type *Field2Parent =
19544 Field2->getParent()->getTypeForDecl();
19545 assert(((Field1Parent->isStructureOrClassType() &&
19546 Field2Parent->isStructureOrClassType()) ||
19547 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
19548 "Can't evaluate layout compatibility between a struct field and a "
19549 "union field.");
19550 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
19551 (AreUnionMembers && Field1Parent->isUnionType())) &&
19552 "AreUnionMembers should be 'true' for union fields (only).");
19553
19554 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
19555 return false;
19556
19557 if (Field1->isBitField() != Field2->isBitField())
19558 return false;
19559
19560 if (Field1->isBitField()) {
19561 // Make sure that the bit-fields are the same length.
19562 unsigned Bits1 = Field1->getBitWidthValue(C);
19563 unsigned Bits2 = Field2->getBitWidthValue(C);
19564
19565 if (Bits1 != Bits2)
19566 return false;
19567 }
19568
19569 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
19570 Field2->hasAttr<clang::NoUniqueAddressAttr>())
19571 return false;
19572
19573 if (!AreUnionMembers &&
19574 Field1->getMaxAlignment() != Field2->getMaxAlignment())
19575 return false;
19576
19577 return true;
19578}
19579
19580/// Check if two standard-layout structs are layout-compatible.
19581/// (C++11 [class.mem] p17)
19583 RecordDecl *RD2) {
19584 // If both records are C++ classes, check that base classes match.
19585 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
19586 // If one of records is a CXXRecordDecl we are in C++ mode,
19587 // thus the other one is a CXXRecordDecl, too.
19588 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
19589 // Check number of base classes.
19590 if (D1CXX->getNumBases() != D2CXX->getNumBases())
19591 return false;
19592
19593 // Check the base classes.
19595 Base1 = D1CXX->bases_begin(),
19596 BaseEnd1 = D1CXX->bases_end(),
19597 Base2 = D2CXX->bases_begin();
19598 Base1 != BaseEnd1;
19599 ++Base1, ++Base2) {
19600 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
19601 return false;
19602 }
19603 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
19604 // If only RD2 is a C++ class, it should have zero base classes.
19605 if (D2CXX->getNumBases() > 0)
19606 return false;
19607 }
19608
19609 // Check the fields.
19611 Field2End = RD2->field_end(),
19612 Field1 = RD1->field_begin(),
19613 Field1End = RD1->field_end();
19614 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
19615 if (!isLayoutCompatible(C, *Field1, *Field2))
19616 return false;
19617 }
19618 if (Field1 != Field1End || Field2 != Field2End)
19619 return false;
19620
19621 return true;
19622}
19623
19624/// Check if two standard-layout unions are layout-compatible.
19625/// (C++11 [class.mem] p18)
19627 RecordDecl *RD2) {
19628 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
19629 for (auto *Field2 : RD2->fields())
19630 UnmatchedFields.insert(Field2);
19631
19632 for (auto *Field1 : RD1->fields()) {
19634 I = UnmatchedFields.begin(),
19635 E = UnmatchedFields.end();
19636
19637 for ( ; I != E; ++I) {
19638 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
19639 bool Result = UnmatchedFields.erase(*I);
19640 (void) Result;
19641 assert(Result);
19642 break;
19643 }
19644 }
19645 if (I == E)
19646 return false;
19647 }
19648
19649 return UnmatchedFields.empty();
19650}
19651
19653 RecordDecl *RD2) {
19654 if (RD1->isUnion() != RD2->isUnion())
19655 return false;
19656
19657 if (RD1->isUnion())
19658 return isLayoutCompatibleUnion(C, RD1, RD2);
19659 else
19660 return isLayoutCompatibleStruct(C, RD1, RD2);
19661}
19662
19663/// Check if two types are layout-compatible in C++11 sense.
19665 if (T1.isNull() || T2.isNull())
19666 return false;
19667
19668 // C++20 [basic.types] p11:
19669 // Two types cv1 T1 and cv2 T2 are layout-compatible types
19670 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
19671 // or layout-compatible standard-layout class types (11.4).
19674
19675 if (C.hasSameType(T1, T2))
19676 return true;
19677
19678 const Type::TypeClass TC1 = T1->getTypeClass();
19679 const Type::TypeClass TC2 = T2->getTypeClass();
19680
19681 if (TC1 != TC2)
19682 return false;
19683
19684 if (TC1 == Type::Enum) {
19685 return isLayoutCompatible(C,
19686 cast<EnumType>(T1)->getDecl(),
19687 cast<EnumType>(T2)->getDecl());
19688 } else if (TC1 == Type::Record) {
19689 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
19690 return false;
19691
19692 return isLayoutCompatible(C,
19693 cast<RecordType>(T1)->getDecl(),
19694 cast<RecordType>(T2)->getDecl());
19695 }
19696
19697 return false;
19698}
19699
19701 return isLayoutCompatible(getASTContext(), T1, T2);
19702}
19703
19704//===-------------- Pointer interconvertibility ----------------------------//
19705
19707 const TypeSourceInfo *Derived) {
19708 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
19709 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
19710
19711 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
19712 getASTContext().hasSameType(BaseT, DerivedT))
19713 return true;
19714
19715 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
19716 return false;
19717
19718 // Per [basic.compound]/4.3, containing object has to be standard-layout.
19719 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
19720 return true;
19721
19722 return false;
19723}
19724
19725//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
19726
19727/// Given a type tag expression find the type tag itself.
19728///
19729/// \param TypeExpr Type tag expression, as it appears in user's code.
19730///
19731/// \param VD Declaration of an identifier that appears in a type tag.
19732///
19733/// \param MagicValue Type tag magic value.
19734///
19735/// \param isConstantEvaluated whether the evalaution should be performed in
19736
19737/// constant context.
19738static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
19739 const ValueDecl **VD, uint64_t *MagicValue,
19740 bool isConstantEvaluated) {
19741 while(true) {
19742 if (!TypeExpr)
19743 return false;
19744
19745 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
19746
19747 switch (TypeExpr->getStmtClass()) {
19748 case Stmt::UnaryOperatorClass: {
19749 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
19750 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
19751 TypeExpr = UO->getSubExpr();
19752 continue;
19753 }
19754 return false;
19755 }
19756
19757 case Stmt::DeclRefExprClass: {
19758 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
19759 *VD = DRE->getDecl();
19760 return true;
19761 }
19762
19763 case Stmt::IntegerLiteralClass: {
19764 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
19765 llvm::APInt MagicValueAPInt = IL->getValue();
19766 if (MagicValueAPInt.getActiveBits() <= 64) {
19767 *MagicValue = MagicValueAPInt.getZExtValue();
19768 return true;
19769 } else
19770 return false;
19771 }
19772
19773 case Stmt::BinaryConditionalOperatorClass:
19774 case Stmt::ConditionalOperatorClass: {
19775 const AbstractConditionalOperator *ACO =
19776 cast<AbstractConditionalOperator>(TypeExpr);
19777 bool Result;
19778 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
19779 isConstantEvaluated)) {
19780 if (Result)
19781 TypeExpr = ACO->getTrueExpr();
19782 else
19783 TypeExpr = ACO->getFalseExpr();
19784 continue;
19785 }
19786 return false;
19787 }
19788
19789 case Stmt::BinaryOperatorClass: {
19790 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
19791 if (BO->getOpcode() == BO_Comma) {
19792 TypeExpr = BO->getRHS();
19793 continue;
19794 }
19795 return false;
19796 }
19797
19798 default:
19799 return false;
19800 }
19801 }
19802}
19803
19804/// Retrieve the C type corresponding to type tag TypeExpr.
19805///
19806/// \param TypeExpr Expression that specifies a type tag.
19807///
19808/// \param MagicValues Registered magic values.
19809///
19810/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
19811/// kind.
19812///
19813/// \param TypeInfo Information about the corresponding C type.
19814///
19815/// \param isConstantEvaluated whether the evalaution should be performed in
19816/// constant context.
19817///
19818/// \returns true if the corresponding C type was found.
19820 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
19821 const ASTContext &Ctx,
19822 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
19823 *MagicValues,
19824 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
19825 bool isConstantEvaluated) {
19826 FoundWrongKind = false;
19827
19828 // Variable declaration that has type_tag_for_datatype attribute.
19829 const ValueDecl *VD = nullptr;
19830
19831 uint64_t MagicValue;
19832
19833 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
19834 return false;
19835
19836 if (VD) {
19837 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
19838 if (I->getArgumentKind() != ArgumentKind) {
19839 FoundWrongKind = true;
19840 return false;
19841 }
19842 TypeInfo.Type = I->getMatchingCType();
19843 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
19844 TypeInfo.MustBeNull = I->getMustBeNull();
19845 return true;
19846 }
19847 return false;
19848 }
19849
19850 if (!MagicValues)
19851 return false;
19852
19853 llvm::DenseMap<Sema::TypeTagMagicValue,
19854 Sema::TypeTagData>::const_iterator I =
19855 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
19856 if (I == MagicValues->end())
19857 return false;
19858
19859 TypeInfo = I->second;
19860 return true;
19861}
19862
19864 uint64_t MagicValue, QualType Type,
19865 bool LayoutCompatible,
19866 bool MustBeNull) {
19867 if (!TypeTagForDatatypeMagicValues)
19868 TypeTagForDatatypeMagicValues.reset(
19869 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
19870
19871 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
19872 (*TypeTagForDatatypeMagicValues)[Magic] =
19873 TypeTagData(Type, LayoutCompatible, MustBeNull);
19874}
19875
19876static bool IsSameCharType(QualType T1, QualType T2) {
19877 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
19878 if (!BT1)
19879 return false;
19880
19881 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
19882 if (!BT2)
19883 return false;
19884
19885 BuiltinType::Kind T1Kind = BT1->getKind();
19886 BuiltinType::Kind T2Kind = BT2->getKind();
19887
19888 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
19889 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
19890 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
19891 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
19892}
19893
19894void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
19895 const ArrayRef<const Expr *> ExprArgs,
19896 SourceLocation CallSiteLoc) {
19897 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
19898 bool IsPointerAttr = Attr->getIsPointer();
19899
19900 // Retrieve the argument representing the 'type_tag'.
19901 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
19902 if (TypeTagIdxAST >= ExprArgs.size()) {
19903 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
19904 << 0 << Attr->getTypeTagIdx().getSourceIndex();
19905 return;
19906 }
19907 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
19908 bool FoundWrongKind;
19909 TypeTagData TypeInfo;
19910 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
19911 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
19913 if (FoundWrongKind)
19914 Diag(TypeTagExpr->getExprLoc(),
19915 diag::warn_type_tag_for_datatype_wrong_kind)
19916 << TypeTagExpr->getSourceRange();
19917 return;
19918 }
19919
19920 // Retrieve the argument representing the 'arg_idx'.
19921 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
19922 if (ArgumentIdxAST >= ExprArgs.size()) {
19923 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
19924 << 1 << Attr->getArgumentIdx().getSourceIndex();
19925 return;
19926 }
19927 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
19928 if (IsPointerAttr) {
19929 // Skip implicit cast of pointer to `void *' (as a function argument).
19930 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
19931 if (ICE->getType()->isVoidPointerType() &&
19932 ICE->getCastKind() == CK_BitCast)
19933 ArgumentExpr = ICE->getSubExpr();
19934 }
19935 QualType ArgumentType = ArgumentExpr->getType();
19936
19937 // Passing a `void*' pointer shouldn't trigger a warning.
19938 if (IsPointerAttr && ArgumentType->isVoidPointerType())
19939 return;
19940
19941 if (TypeInfo.MustBeNull) {
19942 // Type tag with matching void type requires a null pointer.
19943 if (!ArgumentExpr->isNullPointerConstant(Context,
19945 Diag(ArgumentExpr->getExprLoc(),
19946 diag::warn_type_safety_null_pointer_required)
19947 << ArgumentKind->getName()
19948 << ArgumentExpr->getSourceRange()
19949 << TypeTagExpr->getSourceRange();
19950 }
19951 return;
19952 }
19953
19954 QualType RequiredType = TypeInfo.Type;
19955 if (IsPointerAttr)
19956 RequiredType = Context.getPointerType(RequiredType);
19957
19958 bool mismatch = false;
19959 if (!TypeInfo.LayoutCompatible) {
19960 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
19961
19962 // C++11 [basic.fundamental] p1:
19963 // Plain char, signed char, and unsigned char are three distinct types.
19964 //
19965 // But we treat plain `char' as equivalent to `signed char' or `unsigned
19966 // char' depending on the current char signedness mode.
19967 if (mismatch)
19968 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
19969 RequiredType->getPointeeType())) ||
19970 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
19971 mismatch = false;
19972 } else
19973 if (IsPointerAttr)
19974 mismatch = !isLayoutCompatible(Context,
19975 ArgumentType->getPointeeType(),
19976 RequiredType->getPointeeType());
19977 else
19978 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
19979
19980 if (mismatch)
19981 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
19982 << ArgumentType << ArgumentKind
19983 << TypeInfo.LayoutCompatible << RequiredType
19984 << ArgumentExpr->getSourceRange()
19985 << TypeTagExpr->getSourceRange();
19986}
19987
19988void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
19989 CharUnits Alignment) {
19990 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
19991}
19992
19994 for (MisalignedMember &m : MisalignedMembers) {
19995 const NamedDecl *ND = m.RD;
19996 if (ND->getName().empty()) {
19997 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
19998 ND = TD;
19999 }
20000 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
20001 << m.MD << ND << m.E->getSourceRange();
20002 }
20003 MisalignedMembers.clear();
20004}
20005
20007 E = E->IgnoreParens();
20008 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
20009 return;
20010 if (isa<UnaryOperator>(E) &&
20011 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
20012 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
20013 if (isa<MemberExpr>(Op)) {
20014 auto *MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
20015 if (MA != MisalignedMembers.end() &&
20016 (T->isDependentType() || T->isIntegerType() ||
20019 T->getPointeeType()) <= MA->Alignment))))
20020 MisalignedMembers.erase(MA);
20021 }
20022 }
20023}
20024
20026 Expr *E,
20027 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
20028 Action) {
20029 const auto *ME = dyn_cast<MemberExpr>(E);
20030 if (!ME)
20031 return;
20032
20033 // No need to check expressions with an __unaligned-qualified type.
20034 if (E->getType().getQualifiers().hasUnaligned())
20035 return;
20036
20037 // For a chain of MemberExpr like "a.b.c.d" this list
20038 // will keep FieldDecl's like [d, c, b].
20039 SmallVector<FieldDecl *, 4> ReverseMemberChain;
20040 const MemberExpr *TopME = nullptr;
20041 bool AnyIsPacked = false;
20042 do {
20043 QualType BaseType = ME->getBase()->getType();
20044 if (BaseType->isDependentType())
20045 return;
20046 if (ME->isArrow())
20047 BaseType = BaseType->getPointeeType();
20048 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
20049 if (RD->isInvalidDecl())
20050 return;
20051
20052 ValueDecl *MD = ME->getMemberDecl();
20053 auto *FD = dyn_cast<FieldDecl>(MD);
20054 // We do not care about non-data members.
20055 if (!FD || FD->isInvalidDecl())
20056 return;
20057
20058 AnyIsPacked =
20059 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
20060 ReverseMemberChain.push_back(FD);
20061
20062 TopME = ME;
20063 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
20064 } while (ME);
20065 assert(TopME && "We did not compute a topmost MemberExpr!");
20066
20067 // Not the scope of this diagnostic.
20068 if (!AnyIsPacked)
20069 return;
20070
20071 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
20072 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
20073 // TODO: The innermost base of the member expression may be too complicated.
20074 // For now, just disregard these cases. This is left for future
20075 // improvement.
20076 if (!DRE && !isa<CXXThisExpr>(TopBase))
20077 return;
20078
20079 // Alignment expected by the whole expression.
20080 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
20081
20082 // No need to do anything else with this case.
20083 if (ExpectedAlignment.isOne())
20084 return;
20085
20086 // Synthesize offset of the whole access.
20087 CharUnits Offset;
20088 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
20090
20091 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
20092 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
20093 ReverseMemberChain.back()->getParent()->getTypeForDecl());
20094
20095 // The base expression of the innermost MemberExpr may give
20096 // stronger guarantees than the class containing the member.
20097 if (DRE && !TopME->isArrow()) {
20098 const ValueDecl *VD = DRE->getDecl();
20099 if (!VD->getType()->isReferenceType())
20100 CompleteObjectAlignment =
20101 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
20102 }
20103
20104 // Check if the synthesized offset fulfills the alignment.
20105 if (Offset % ExpectedAlignment != 0 ||
20106 // It may fulfill the offset it but the effective alignment may still be
20107 // lower than the expected expression alignment.
20108 CompleteObjectAlignment < ExpectedAlignment) {
20109 // If this happens, we want to determine a sensible culprit of this.
20110 // Intuitively, watching the chain of member expressions from right to
20111 // left, we start with the required alignment (as required by the field
20112 // type) but some packed attribute in that chain has reduced the alignment.
20113 // It may happen that another packed structure increases it again. But if
20114 // we are here such increase has not been enough. So pointing the first
20115 // FieldDecl that either is packed or else its RecordDecl is,
20116 // seems reasonable.
20117 FieldDecl *FD = nullptr;
20118 CharUnits Alignment;
20119 for (FieldDecl *FDI : ReverseMemberChain) {
20120 if (FDI->hasAttr<PackedAttr>() ||
20121 FDI->getParent()->hasAttr<PackedAttr>()) {
20122 FD = FDI;
20123 Alignment = std::min(
20126 break;
20127 }
20128 }
20129 assert(FD && "We did not find a packed FieldDecl!");
20130 Action(E, FD->getParent(), FD, Alignment);
20131 }
20132}
20133
20134void Sema::CheckAddressOfPackedMember(Expr *rhs) {
20135 using namespace std::placeholders;
20136
20138 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
20139 _2, _3, _4));
20140}
20141
20142bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) {
20143 if (checkArgCount(*this, TheCall, 1))
20144 return true;
20145
20146 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
20147 if (A.isInvalid())
20148 return true;
20149
20150 TheCall->setArg(0, A.get());
20151 QualType TyA = A.get()->getType();
20152
20153 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA, 1))
20154 return true;
20155
20156 TheCall->setType(TyA);
20157 return false;
20158}
20159
20160bool Sema::BuiltinElementwiseMath(CallExpr *TheCall) {
20161 QualType Res;
20162 if (BuiltinVectorMath(TheCall, Res))
20163 return true;
20164 TheCall->setType(Res);
20165 return false;
20166}
20167
20169 QualType Res;
20170 if (BuiltinVectorMath(TheCall, Res))
20171 return true;
20172
20173 if (auto *VecTy0 = Res->getAs<VectorType>())
20174 TheCall->setType(VecTy0->getElementType());
20175 else
20176 TheCall->setType(Res);
20177
20178 return false;
20179}
20180
20182 if (checkArgCount(*this, TheCall, 2))
20183 return true;
20184
20185 ExprResult A = TheCall->getArg(0);
20186 ExprResult B = TheCall->getArg(1);
20187 // Do standard promotions between the two arguments, returning their common
20188 // type.
20189 Res = UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
20190 if (A.isInvalid() || B.isInvalid())
20191 return true;
20192
20193 QualType TyA = A.get()->getType();
20194 QualType TyB = B.get()->getType();
20195
20196 if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
20197 return Diag(A.get()->getBeginLoc(),
20198 diag::err_typecheck_call_different_arg_types)
20199 << TyA << TyB;
20200
20201 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA, 1))
20202 return true;
20203
20204 TheCall->setArg(0, A.get());
20205 TheCall->setArg(1, B.get());
20206 return false;
20207}
20208
20209bool Sema::BuiltinElementwiseTernaryMath(CallExpr *TheCall,
20210 bool CheckForFloatArgs) {
20211 if (checkArgCount(*this, TheCall, 3))
20212 return true;
20213
20214 Expr *Args[3];
20215 for (int I = 0; I < 3; ++I) {
20216 ExprResult Converted = UsualUnaryConversions(TheCall->getArg(I));
20217 if (Converted.isInvalid())
20218 return true;
20219 Args[I] = Converted.get();
20220 }
20221
20222 if (CheckForFloatArgs) {
20223 int ArgOrdinal = 1;
20224 for (Expr *Arg : Args) {
20226 Arg->getType(), ArgOrdinal++))
20227 return true;
20228 }
20229 } else {
20230 int ArgOrdinal = 1;
20231 for (Expr *Arg : Args) {
20232 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
20233 ArgOrdinal++))
20234 return true;
20235 }
20236 }
20237
20238 for (int I = 1; I < 3; ++I) {
20239 if (Args[0]->getType().getCanonicalType() !=
20240 Args[I]->getType().getCanonicalType()) {
20241 return Diag(Args[0]->getBeginLoc(),
20242 diag::err_typecheck_call_different_arg_types)
20243 << Args[0]->getType() << Args[I]->getType();
20244 }
20245
20246 TheCall->setArg(I, Args[I]);
20247 }
20248
20249 TheCall->setType(Args[0]->getType());
20250 return false;
20251}
20252
20253bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
20254 if (checkArgCount(*this, TheCall, 1))
20255 return true;
20256
20257 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
20258 if (A.isInvalid())
20259 return true;
20260
20261 TheCall->setArg(0, A.get());
20262 return false;
20263}
20264
20265bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
20266 if (checkArgCount(*this, TheCall, 1))
20267 return true;
20268
20269 ExprResult Arg = TheCall->getArg(0);
20270 QualType TyArg = Arg.get()->getType();
20271
20272 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
20273 return Diag(TheCall->getArg(0)->getBeginLoc(), diag::err_builtin_invalid_arg_type)
20274 << 1 << /*vector, integer or floating point ty*/ 0 << TyArg;
20275
20276 TheCall->setType(TyArg);
20277 return false;
20278}
20279
20280ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
20281 ExprResult CallResult) {
20282 if (checkArgCount(*this, TheCall, 1))
20283 return ExprError();
20284
20285 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
20286 if (MatrixArg.isInvalid())
20287 return MatrixArg;
20288 Expr *Matrix = MatrixArg.get();
20289
20290 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
20291 if (!MType) {
20292 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
20293 << 1 << /* matrix ty*/ 1 << Matrix->getType();
20294 return ExprError();
20295 }
20296
20297 // Create returned matrix type by swapping rows and columns of the argument
20298 // matrix type.
20300 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
20301
20302 // Change the return type to the type of the returned matrix.
20303 TheCall->setType(ResultType);
20304
20305 // Update call argument to use the possibly converted matrix argument.
20306 TheCall->setArg(0, Matrix);
20307 return CallResult;
20308}
20309
20310// Get and verify the matrix dimensions.
20311static std::optional<unsigned>
20313 SourceLocation ErrorPos;
20314 std::optional<llvm::APSInt> Value =
20315 Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
20316 if (!Value) {
20317 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
20318 << Name;
20319 return {};
20320 }
20321 uint64_t Dim = Value->getZExtValue();
20323 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
20325 return {};
20326 }
20327 return Dim;
20328}
20329
20330ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
20331 ExprResult CallResult) {
20332 if (!getLangOpts().MatrixTypes) {
20333 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
20334 return ExprError();
20335 }
20336
20337 if (checkArgCount(*this, TheCall, 4))
20338 return ExprError();
20339
20340 unsigned PtrArgIdx = 0;
20341 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
20342 Expr *RowsExpr = TheCall->getArg(1);
20343 Expr *ColumnsExpr = TheCall->getArg(2);
20344 Expr *StrideExpr = TheCall->getArg(3);
20345
20346 bool ArgError = false;
20347
20348 // Check pointer argument.
20349 {
20351 if (PtrConv.isInvalid())
20352 return PtrConv;
20353 PtrExpr = PtrConv.get();
20354 TheCall->setArg(0, PtrExpr);
20355 if (PtrExpr->isTypeDependent()) {
20356 TheCall->setType(Context.DependentTy);
20357 return TheCall;
20358 }
20359 }
20360
20361 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
20362 QualType ElementTy;
20363 if (!PtrTy) {
20364 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
20365 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
20366 ArgError = true;
20367 } else {
20368 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
20369
20371 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
20372 << PtrArgIdx + 1 << /* pointer to element ty*/ 2
20373 << PtrExpr->getType();
20374 ArgError = true;
20375 }
20376 }
20377
20378 // Apply default Lvalue conversions and convert the expression to size_t.
20379 auto ApplyArgumentConversions = [this](Expr *E) {
20381 if (Conv.isInvalid())
20382 return Conv;
20383
20384 return tryConvertExprToType(Conv.get(), Context.getSizeType());
20385 };
20386
20387 // Apply conversion to row and column expressions.
20388 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
20389 if (!RowsConv.isInvalid()) {
20390 RowsExpr = RowsConv.get();
20391 TheCall->setArg(1, RowsExpr);
20392 } else
20393 RowsExpr = nullptr;
20394
20395 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
20396 if (!ColumnsConv.isInvalid()) {
20397 ColumnsExpr = ColumnsConv.get();
20398 TheCall->setArg(2, ColumnsExpr);
20399 } else
20400 ColumnsExpr = nullptr;
20401
20402 // If any part of the result matrix type is still pending, just use
20403 // Context.DependentTy, until all parts are resolved.
20404 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
20405 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
20406 TheCall->setType(Context.DependentTy);
20407 return CallResult;
20408 }
20409
20410 // Check row and column dimensions.
20411 std::optional<unsigned> MaybeRows;
20412 if (RowsExpr)
20413 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
20414
20415 std::optional<unsigned> MaybeColumns;
20416 if (ColumnsExpr)
20417 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
20418
20419 // Check stride argument.
20420 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
20421 if (StrideConv.isInvalid())
20422 return ExprError();
20423 StrideExpr = StrideConv.get();
20424 TheCall->setArg(3, StrideExpr);
20425
20426 if (MaybeRows) {
20427 if (std::optional<llvm::APSInt> Value =
20428 StrideExpr->getIntegerConstantExpr(Context)) {
20429 uint64_t Stride = Value->getZExtValue();
20430 if (Stride < *MaybeRows) {
20431 Diag(StrideExpr->getBeginLoc(),
20432 diag::err_builtin_matrix_stride_too_small);
20433 ArgError = true;
20434 }
20435 }
20436 }
20437
20438 if (ArgError || !MaybeRows || !MaybeColumns)
20439 return ExprError();
20440
20441 TheCall->setType(
20442 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
20443 return CallResult;
20444}
20445
20446ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
20447 ExprResult CallResult) {
20448 if (checkArgCount(*this, TheCall, 3))
20449 return ExprError();
20450
20451 unsigned PtrArgIdx = 1;
20452 Expr *MatrixExpr = TheCall->getArg(0);
20453 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
20454 Expr *StrideExpr = TheCall->getArg(2);
20455
20456 bool ArgError = false;
20457
20458 {
20459 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
20460 if (MatrixConv.isInvalid())
20461 return MatrixConv;
20462 MatrixExpr = MatrixConv.get();
20463 TheCall->setArg(0, MatrixExpr);
20464 }
20465 if (MatrixExpr->isTypeDependent()) {
20466 TheCall->setType(Context.DependentTy);
20467 return TheCall;
20468 }
20469
20470 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
20471 if (!MatrixTy) {
20472 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
20473 << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
20474 ArgError = true;
20475 }
20476
20477 {
20479 if (PtrConv.isInvalid())
20480 return PtrConv;
20481 PtrExpr = PtrConv.get();
20482 TheCall->setArg(1, PtrExpr);
20483 if (PtrExpr->isTypeDependent()) {
20484 TheCall->setType(Context.DependentTy);
20485 return TheCall;
20486 }
20487 }
20488
20489 // Check pointer argument.
20490 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
20491 if (!PtrTy) {
20492 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
20493 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
20494 ArgError = true;
20495 } else {
20496 QualType ElementTy = PtrTy->getPointeeType();
20497 if (ElementTy.isConstQualified()) {
20498 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
20499 ArgError = true;
20500 }
20501 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
20502 if (MatrixTy &&
20503 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
20504 Diag(PtrExpr->getBeginLoc(),
20505 diag::err_builtin_matrix_pointer_arg_mismatch)
20506 << ElementTy << MatrixTy->getElementType();
20507 ArgError = true;
20508 }
20509 }
20510
20511 // Apply default Lvalue conversions and convert the stride expression to
20512 // size_t.
20513 {
20514 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
20515 if (StrideConv.isInvalid())
20516 return StrideConv;
20517
20518 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
20519 if (StrideConv.isInvalid())
20520 return StrideConv;
20521 StrideExpr = StrideConv.get();
20522 TheCall->setArg(2, StrideExpr);
20523 }
20524
20525 // Check stride argument.
20526 if (MatrixTy) {
20527 if (std::optional<llvm::APSInt> Value =
20528 StrideExpr->getIntegerConstantExpr(Context)) {
20529 uint64_t Stride = Value->getZExtValue();
20530 if (Stride < MatrixTy->getNumRows()) {
20531 Diag(StrideExpr->getBeginLoc(),
20532 diag::err_builtin_matrix_stride_too_small);
20533 ArgError = true;
20534 }
20535 }
20536 }
20537
20538 if (ArgError)
20539 return ExprError();
20540
20541 return CallResult;
20542}
20543
20544/// Checks the argument at the given index is a WebAssembly table and if it
20545/// is, sets ElTy to the element type.
20546static bool CheckWasmBuiltinArgIsTable(Sema &S, CallExpr *E, unsigned ArgIndex,
20547 QualType &ElTy) {
20548 Expr *ArgExpr = E->getArg(ArgIndex);
20549 const auto *ATy = dyn_cast<ArrayType>(ArgExpr->getType());
20550 if (!ATy || !ATy->getElementType().isWebAssemblyReferenceType()) {
20551 return S.Diag(ArgExpr->getBeginLoc(),
20552 diag::err_wasm_builtin_arg_must_be_table_type)
20553 << ArgIndex + 1 << ArgExpr->getSourceRange();
20554 }
20555 ElTy = ATy->getElementType();
20556 return false;
20557}
20558
20559/// Checks the argument at the given index is an integer.
20561 unsigned ArgIndex) {
20562 Expr *ArgExpr = E->getArg(ArgIndex);
20563 if (!ArgExpr->getType()->isIntegerType()) {
20564 return S.Diag(ArgExpr->getBeginLoc(),
20565 diag::err_wasm_builtin_arg_must_be_integer_type)
20566 << ArgIndex + 1 << ArgExpr->getSourceRange();
20567 }
20568 return false;
20569}
20570
20571/// Check that the first argument is a WebAssembly table, and the second
20572/// is an index to use as index into the table.
20573bool Sema::BuiltinWasmTableGet(CallExpr *TheCall) {
20574 if (checkArgCount(*this, TheCall, 2))
20575 return true;
20576
20577 QualType ElTy;
20578 if (CheckWasmBuiltinArgIsTable(*this, TheCall, 0, ElTy))
20579 return true;
20580
20581 if (CheckWasmBuiltinArgIsInteger(*this, TheCall, 1))
20582 return true;
20583
20584 // If all is well, we set the type of TheCall to be the type of the
20585 // element of the table.
20586 // i.e. a table.get on an externref table has type externref,
20587 // or whatever the type of the table element is.
20588 TheCall->setType(ElTy);
20589
20590 return false;
20591}
20592
20593/// Check that the first argumnet is a WebAssembly table, the second is
20594/// an index to use as index into the table and the third is the reference
20595/// type to set into the table.
20596bool Sema::BuiltinWasmTableSet(CallExpr *TheCall) {
20597 if (checkArgCount(*this, TheCall, 3))
20598 return true;
20599
20600 QualType ElTy;
20601 if (CheckWasmBuiltinArgIsTable(*this, TheCall, 0, ElTy))
20602 return true;
20603
20604 if (CheckWasmBuiltinArgIsInteger(*this, TheCall, 1))
20605 return true;
20606
20607 if (!Context.hasSameType(ElTy, TheCall->getArg(2)->getType()))
20608 return true;
20609
20610 return false;
20611}
20612
20613/// Check that the argument is a WebAssembly table.
20614bool Sema::BuiltinWasmTableSize(CallExpr *TheCall) {
20615 if (checkArgCount(*this, TheCall, 1))
20616 return true;
20617
20618 QualType ElTy;
20619 if (CheckWasmBuiltinArgIsTable(*this, TheCall, 0, ElTy))
20620 return true;
20621
20622 return false;
20623}
20624
20625/// Check that the first argument is a WebAssembly table, the second is the
20626/// value to use for new elements (of a type matching the table type), the
20627/// third value is an integer.
20628bool Sema::BuiltinWasmTableGrow(CallExpr *TheCall) {
20629 if (checkArgCount(*this, TheCall, 3))
20630 return true;
20631
20632 QualType ElTy;
20633 if (CheckWasmBuiltinArgIsTable(*this, TheCall, 0, ElTy))
20634 return true;
20635
20636 Expr *NewElemArg = TheCall->getArg(1);
20637 if (!Context.hasSameType(ElTy, NewElemArg->getType())) {
20638 return Diag(NewElemArg->getBeginLoc(),
20639 diag::err_wasm_builtin_arg_must_match_table_element_type)
20640 << 2 << 1 << NewElemArg->getSourceRange();
20641 }
20642
20643 if (CheckWasmBuiltinArgIsInteger(*this, TheCall, 2))
20644 return true;
20645
20646 return false;
20647}
20648
20649/// Check that the first argument is a WebAssembly table, the second is an
20650/// integer, the third is the value to use to fill the table (of a type
20651/// matching the table type), and the fourth is an integer.
20652bool Sema::BuiltinWasmTableFill(CallExpr *TheCall) {
20653 if (checkArgCount(*this, TheCall, 4))
20654 return true;
20655
20656 QualType ElTy;
20657 if (CheckWasmBuiltinArgIsTable(*this, TheCall, 0, ElTy))
20658 return true;
20659
20660 if (CheckWasmBuiltinArgIsInteger(*this, TheCall, 1))
20661 return true;
20662
20663 Expr *NewElemArg = TheCall->getArg(2);
20664 if (!Context.hasSameType(ElTy, NewElemArg->getType())) {
20665 return Diag(NewElemArg->getBeginLoc(),
20666 diag::err_wasm_builtin_arg_must_match_table_element_type)
20667 << 3 << 1 << NewElemArg->getSourceRange();
20668 }
20669
20670 if (CheckWasmBuiltinArgIsInteger(*this, TheCall, 3))
20671 return true;
20672
20673 return false;
20674}
20675
20676/// Check that the first argument is a WebAssembly table, the second is also a
20677/// WebAssembly table (of the same element type), and the third to fifth
20678/// arguments are integers.
20679bool Sema::BuiltinWasmTableCopy(CallExpr *TheCall) {
20680 if (checkArgCount(*this, TheCall, 5))
20681 return true;
20682
20683 QualType XElTy;
20684 if (CheckWasmBuiltinArgIsTable(*this, TheCall, 0, XElTy))
20685 return true;
20686
20687 QualType YElTy;
20688 if (CheckWasmBuiltinArgIsTable(*this, TheCall, 1, YElTy))
20689 return true;
20690
20691 Expr *TableYArg = TheCall->getArg(1);
20692 if (!Context.hasSameType(XElTy, YElTy)) {
20693 return Diag(TableYArg->getBeginLoc(),
20694 diag::err_wasm_builtin_arg_must_match_table_element_type)
20695 << 2 << 1 << TableYArg->getSourceRange();
20696 }
20697
20698 for (int I = 2; I <= 4; I++) {
20699 if (CheckWasmBuiltinArgIsInteger(*this, TheCall, I))
20700 return true;
20701 }
20702
20703 return false;
20704}
20705
20706/// \brief Enforce the bounds of a TCB
20707/// CheckTCBEnforcement - Enforces that every function in a named TCB only
20708/// directly calls other functions in the same TCB as marked by the enforce_tcb
20709/// and enforce_tcb_leaf attributes.
20710void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc,
20711 const NamedDecl *Callee) {
20712 // This warning does not make sense in code that has no runtime behavior.
20714 return;
20715
20716 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
20717
20718 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
20719 return;
20720
20721 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
20722 // all TCBs the callee is a part of.
20723 llvm::StringSet<> CalleeTCBs;
20724 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
20725 CalleeTCBs.insert(A->getTCBName());
20726 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
20727 CalleeTCBs.insert(A->getTCBName());
20728
20729 // Go through the TCBs the caller is a part of and emit warnings if Caller
20730 // is in a TCB that the Callee is not.
20731 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
20732 StringRef CallerTCB = A->getTCBName();
20733 if (CalleeTCBs.count(CallerTCB) == 0) {
20734 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
20735 << Callee << CallerTCB;
20736 }
20737 }
20738}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3273
NodeId Parent
Definition: ASTDiff.cpp:191
SyntaxTree::Impl & Tree
Definition: ASTDiff.cpp:192
ASTImporterLookupTable & LT
StringRef P
Provides definitions for the various language-specific address spaces.
#define SM(sm)
Definition: Cuda.cpp:82
Defines the Diagnostic-related interfaces.
static constexpr Builtin::Info BuiltinInfo[]
Definition: Builtins.cpp:32
static bool getTypeString(SmallStringEnc &Enc, const Decl *D, const CodeGen::CodeGenModule &CGM, TypeStringCache &TSC)
The XCore ABI includes a type information section that communicates symbol type information to the li...
Definition: XCore.cpp:632
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1109
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
CompileCommand Cmd
LangStandard::Kind Std
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition: MachO.h:48
Defines the clang::OpenCLOptions class.
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
static bool BuiltinReserveRWPipe(Sema &S, CallExpr *Call)
static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, const ValueDecl **VD, uint64_t *MagicValue, bool isConstantEvaluated)
Given a type tag expression find the type tag itself.
static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, bool InConstantContext, bool Approximate)
Pseudo-evaluate the given integer expression, estimating the range of values it might take.
static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, SourceLocation CC, QualType T)
static QualType getSizeOfArgType(const Expr *E)
If E is a sizeof expression, returns its argument type.
static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, SourceLocation CallSiteLoc)
static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, IdentifierInfo *FnName, SourceLocation FnLoc, SourceLocation RParenLoc)
Takes the expression passed to the size_t parameter of functions such as memcmp, strncat,...
static const CXXRecordDecl * getContainedDynamicClass(QualType T, bool &IsContained)
Determine whether the given type is or contains a dynamic class type (e.g., whether it has a vtable).
static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call)
static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext)
Diagnose an implicit cast from a floating point value to an integer value.
static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type, bool inFunctionCall, Sema::VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, bool IgnoreStringsWithoutSpecifiers)
static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call)
static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner)
Consider whether capturing the given variable can possibly lead to a retain cycle.
static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, bool *ICContext=nullptr, bool IsListInit=false)
static bool IsSameFloatAfterCast(const llvm::APFloat &value, const llvm::fltSemantics &Src, const llvm::fltSemantics &Tgt)
Checks whether the given value, which currently has the given source semantics, has the same value wh...
static StringLiteralCheckType checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type, Sema::VariadicCallType CallType, bool InFunctionCall, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset, bool IgnoreStringsWithoutSpecifiers=false)
static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth)
static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool)
static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, SourceLocation CContext, unsigned diag, bool pruneControlFlow=false)
Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg)
OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local void*, which is a requirem...
static bool isX86_32Builtin(unsigned BuiltinID)
static void AnalyzeComparison(Sema &S, BinaryOperator *E)
Implements -Wsign-compare.
static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, BinaryOperatorKind BinOpKind, bool AddendIsRight)
static std::pair< QualType, StringRef > shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy, const Expr *E)
static QualType GetExprType(const Expr *E)
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx)
This helper function takes an lvalue expression and returns the alignment of a VarDecl and a constant...
static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, SourceLocation CC)
static bool OpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall)
OpenCL C v2.0, s6.13.17.6 - Check the argument to the get_kernel_work_group_size and get_kernel_prefe...
static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant, Expr *Other, const llvm::APSInt &Value, bool RhsConstant)
static AbsoluteValueKind getAbsoluteValueKind(QualType T)
bool CheckNoDoubleVectors(Sema *S, CallExpr *TheCall)
static bool isKnownToHaveUnsignedValue(Expr *E)
static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall)
static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2)
Check if two standard-layout structs are layout-compatible.
bool CheckUnsignedIntRepresentation(Sema *S, CallExpr *TheCall)
bool CheckVectorElementCallArgs(Sema *S, CallExpr *TheCall)
static unsigned RFT(unsigned t, bool shift=false, bool ForceQuad=false)
static bool hasArmZAState(const FunctionDecl *FD)
static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntType)
Diagnose integer type and any valid implicit conversion to it.
static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op)
static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, Scope::ScopeFlags NeededScopeFlags, unsigned DiagID)
static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E)
Analyze the given compound assignment for the possible losing of floating-point precision.
static bool doesExprLikelyComputeSize(const Expr *SizeofExpr)
Detect if SizeofExpr is likely to calculate the sizeof an object.
static bool isObjCSignedCharBool(Sema &S, QualType Ty)
static bool OpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, CallExpr *Call)
static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall)
Check the number of arguments and set the result type to the argument type.
bool CheckFloatOrHalfRepresentations(Sema *S, CallExpr *TheCall)
static bool isValidBPFPreserveTypeInfoArg(Expr *Arg)
static bool CheckForReference(Sema &SemaRef, const Expr *E, const PartialDiagnostic &PD)
static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy, int ArgIndex)
static const UnaryExprOrTypeTraitExpr * getAsSizeOfExpr(const Expr *E)
static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID)
Check that the value argument for __builtin_is_aligned(value, alignment) and __builtin_aligned_{up,...
static bool BuiltinRWPipe(Sema &S, CallExpr *Call)
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
Check conversion of given expression to boolean.
static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind)
static Expr * findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner)
Check whether the given argument is a block which captures a variable.
static bool checkArgCountAtLeast(Sema &S, CallExpr *Call, unsigned MinArgCount)
Checks that a call expression's argument count is at least the desired number.
static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call)
Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the last two arguments transpose...
static bool checkPointerAuthEnabled(Sema &S, Expr *E)
static std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range)
AbsoluteValueKind
@ AVK_Complex
@ AVK_Floating
@ AVK_Integer
static const Expr * getStrlenExprArg(const Expr *E)
static void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, ObjCDictionaryLiteral *DictionaryLiteral)
Check an Objective-C dictionary literal being converted to the given target type.
static void checkArmStreamingBuiltin(Sema &S, CallExpr *TheCall, const FunctionDecl *FD, ArmStreamingType BuiltinType)
static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, ASTContext &Context)
static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall, const TargetInfo *AuxTI, unsigned BuiltinID)
BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
static bool isBlockPointer(Expr *Arg)
static bool isSetterLikeSelector(Selector sel)
Check for a keyword selector that starts with the word 'add' or 'set'.
static bool CheckWasmBuiltinArgIsTable(Sema &S, CallExpr *E, unsigned ArgIndex, QualType &ElTy)
Checks the argument at the given index is a WebAssembly table and if it is, sets ElTy to the element ...
static std::optional< int > GetNSMutableDictionaryArgumentIndex(Sema &S, ObjCMessageExpr *Message)
static void adornObjCBoolConversionDiagWithTernaryFixit(Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder)
static bool OpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall)
OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different overload formats specified ...
static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, Expr *BlockArg, unsigned NumNonVarArgs)
OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 'local void*' parameter of passed blo...
static bool BuiltinCommitRWPipe(Sema &S, CallExpr *Call)
static bool IsSameCharType(QualType T1, QualType T2)
bool CheckAllArgsHaveFloatRepresentation(Sema *S, CallExpr *TheCall)
static OpenCLAccessAttr * getOpenCLArgAccess(const Decl *D)
Returns OpenCL access qual.
static bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Checks if a the given expression evaluates to null.
static bool isArgumentExpandedFromMacro(SourceManager &SM, SourceLocation CallLoc, SourceLocation ArgLoc)
Check if the ArgLoc originated from a macro passed to the call at CallLoc.
static const IntegerLiteral * getIntegerLiteral(Expr *E)
static ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD)
static const Expr * maybeConstEvalStringLiteral(ASTContext &Context, const Expr *E)
static bool IsStdFunction(const FunctionDecl *FDecl, const char(&Str)[StrLen])
static void AnalyzeAssignment(Sema &S, BinaryOperator *E)
Analyze the given simple or compound assignment for warning-worthy operations.
static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_function_start is a function.
static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall)
static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, SourceLocation StmtLoc, const NullStmt *Body)
static std::pair< CharUnits, CharUnits > getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, CharUnits BaseAlignment, CharUnits Offset, ASTContext &Ctx)
Compute the alignment and offset of the base class object given the derived-to-base cast expression a...
static void diagnoseArrayStarInParamType(Sema &S, QualType PType, SourceLocation Loc)
static ArmSMEState getSMEState(unsigned BuiltinID)
static unsigned changeAbsFunction(unsigned AbsKind, AbsoluteValueKind ValueKind)
static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool &ICContext)
static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2)
Check if two types are layout-compatible in C++11 sense.
static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool isValidBPFPreserveFieldInfoArg(Expr *Arg)
static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, Expr *RHS, bool isProperty)
static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall)
static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx)
Returns true if pipe element type is different from the pointer.
static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call)
static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, SourceLocation InitLoc)
Analyzes an attempt to assign the given value to a bitfield.
static int classifyConstantValue(Expr *Constant)
static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc)
static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, unsigned AbsKind, QualType ArgType)
static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call)
Returns true if pipe element type is different from the pointer.
static bool checkPointerAuthKey(Sema &S, Expr *&Arg)
static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, Qualifiers::ObjCLifetime LT, Expr *RHS, bool isProperty)
static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID)
static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl)
static void diagnoseRetainCycle(Sema &S, Expr *capturer, RetainCycleOwner &owner)
static llvm::SmallPtrSet< MemberKind *, 1 > CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty)
static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, bool IsPolyUnsigned, bool IsInt64Long)
getNeonEltType - Return the QualType corresponding to the elements of the vector type specified by th...
static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool CheckBuiltinTargetInSupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall, ArrayRef< llvm::Triple::ArchType > SupportedArchs)
static void CheckNonNullArguments(Sema &S, const NamedDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< const Expr * > Args, SourceLocation CallSiteLoc)
static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction)
static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner)
static bool hasArmZT0State(const FunctionDecl *FD)
static analyze_format_string::ArgType::MatchKind handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match, DiagnosticsEngine &Diags, SourceLocation Loc)
static std::optional< int > GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message)
static bool referToTheSameDecl(const Expr *E1, const Expr *E2)
Check if two expressions refer to the same declaration.
static bool OpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall)
#define BUILTIN_ROW(x)
static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_{clzg,ctzg} was called with a first argument, which is an unsigned integer,...
static bool requiresParensToAddCast(const Expr *E)
static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call)
static const Expr * ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx)
static void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, Expr *Element, unsigned ElementKind)
Check a single element within a collection literal against the target element type.
static bool BuiltinPipePackets(Sema &S, CallExpr *Call)
static bool CheckWasmBuiltinArgIsInteger(Sema &S, CallExpr *E, unsigned ArgIndex)
Checks the argument at the given index is an integer.
static std::optional< unsigned > getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S)
static bool checkArgCountRange(Sema &S, CallExpr *Call, unsigned MinArgCount, unsigned MaxArgCount)
Checks that a call expression's argument count is in the desired range.
static bool convertArgumentToType(Sema &S, Expr *&Value, QualType Ty)
static bool ProcessFormatStringLiteral(const Expr *FormatExpr, StringRef &FormatStrRef, size_t &StrLen, ASTContext &Context)
static bool checkArgCount(Sema &S, CallExpr *Call, unsigned DesiredArgCount)
Checks that a call expression's argument count is the desired number.
static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall)
Checks that __builtin_popcountg was called with a single argument, which is an unsigned integer.
void SetElementTypeAsReturnType(Sema *S, CallExpr *TheCall, QualType ReturnType)
static const Expr * getSizeOfExprArg(const Expr *E)
If E is a sizeof expression, returns its argument expression, otherwise returns NULL.
static void DiagnoseIntInBoolContext(Sema &S, Expr *E)
static bool CheckBuiltinTargetNotInUnsupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall, ArrayRef< llvm::Triple::ObjectFormatType > UnsupportedObjectFormatTypes)
static bool BuiltinAddressof(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_addressof is a glvalue, and set the result type to the correspon...
static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S)
static ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call, PointerAuthOpKind OpKind)
static std::optional< int > GetNSMutableArrayArgumentIndex(Sema &S, ObjCMessageExpr *Message)
static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn)
Check that the user is calling the appropriate va_start builtin for the target and calling convention...
static bool IsEnumConstOrFromMacro(Sema &S, Expr *E)
ArmStreamingType
@ ArmStreamingOrSVE2p1
@ ArmStreaming
@ ArmStreamingCompatible
@ ArmNonStreaming
@ TileRegHigh
@ TileRegLow
static bool CheckInvalidVLENandLMUL(const TargetInfo &TI, CallExpr *TheCall, Sema &S, QualType Type, int EGW)
static bool GetMatchingCType(const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, const ASTContext &Ctx, const llvm::DenseMap< Sema::TypeTagMagicValue, Sema::TypeTagData > *MagicValues, bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, bool isConstantEvaluated)
Retrieve the C type corresponding to type tag TypeExpr.
static void checkObjCArrayLiteral(Sema &S, QualType TargetType, ObjCArrayLiteral *ArrayLiteral)
Check an Objective-C array literal being converted to the given target type.
static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2)
Check if two standard-layout unions are layout-compatible.
static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, unsigned &Mask)
DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, advancing the pointer ov...
static QualType getAbsoluteValueArgumentType(ASTContext &Context, unsigned AbsType)
static void DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, const NamedDecl *FDecl, Expr **Args, unsigned NumArgs)
Diagnose use of s directive in an NSString which is being passed as formatting string to formatting m...
static bool isNonNullType(QualType type)
Determine whether the given type has a non-null nullability annotation.
static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A, Sema::FormatArgumentPassingKind B)
static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall)
Check that the first argument to __builtin_annotation is an integer and the second argument is a non-...
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx)
This helper function takes a pointer expression and returns the alignment of a VarDecl and a constant...
static bool IsShiftedByte(llvm::APSInt Value)
static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, unsigned AbsFunctionKind)
static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex)
checkBuiltinArgument - Given a call to a builtin function, perform normal type-checking on the given ...
static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E)
Analyze the operands of the given comparison.
static bool isPPC_64Builtin(unsigned BuiltinID)
static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call)
static bool isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE)
Return true if ICE is an implicit argument promotion of an arithmetic type.
static bool isValidBPFPreserveEnumValueArg(Expr *Arg)
static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, bool IsListInit=false)
AnalyzeImplicitConversions - Find and report any interesting implicit conversions in the given expres...
static bool HasEnumType(Expr *E)
static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, unsigned Start, unsigned End)
static std::optional< std::pair< CharUnits, CharUnits > > getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, bool IsSub, ASTContext &Ctx)
Compute the alignment and offset of a binary additive operator.
static bool checkFPMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy, int ArgIndex)
ArmSMEState
@ ArmInOutZA
@ ArmOutZA
@ ArmInZT0
@ ArmNoState
@ ArmZT0Mask
@ ArmZAMask
@ ArmOutZT0
@ ArmInOutZT0
@ ArmInZA
static bool checkArgCountAtMost(Sema &S, CallExpr *Call, unsigned MaxArgCount)
Checks that a call expression's argument count is at most the desired number.
static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall)
static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, ParmVarDecl **LastParam=nullptr)
bool CheckArgsTypesAreCorrect(Sema *S, CallExpr *TheCall, QualType ExpectedType, llvm::function_ref< bool(clang::QualType PassedType)> Check)
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Provides definitions for the atomic synchronization scopes.
Enumerates target-specific builtins in their own namespaces within namespace clang.
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::TypeLoc interface and its subclasses.
Defines enumerations for the type traits support.
C Language Family Type Representation.
const NestedNameSpecifier * Specifier
std::string Label
__DEVICE__ int min(int __a, int __b)
__device__ int
__device__ __2f16 float __ockl_bool s
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
APSInt & getInt()
Definition: APValue.h:423
bool isVector() const
Definition: APValue.h:407
APSInt & getComplexIntImag()
Definition: APValue.h:461
bool isComplexInt() const
Definition: APValue.h:404
bool isFloat() const
Definition: APValue.h:402
bool isComplexFloat() const
Definition: APValue.h:405
APValue & getVectorElt(unsigned I)
Definition: APValue.h:497
unsigned getVectorLength() const
Definition: APValue.h:505
bool isLValue() const
Definition: APValue.h:406
bool isInt() const
Definition: APValue.h:401
APSInt & getComplexIntReal()
Definition: APValue.h:453
APFloat & getComplexFloatImag()
Definition: APValue.h:477
APFloat & getComplexFloatReal()
Definition: APValue.h:469
APFloat & getFloat()
Definition: APValue.h:437
bool isAddrLabelDiff() const
Definition: APValue.h:412
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2756
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
CanQualType LongTy
Definition: ASTContext.h:1100
unsigned getIntWidth(QualType T) const
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
QualType getRecordType(const RecordDecl *Decl) const
CanQualType FloatTy
Definition: ASTContext.h:1103
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2563
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2579
CanQualType DoubleTy
Definition: ASTContext.h:1103
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
CanQualType LongDoubleTy
Definition: ASTContext.h:1103
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
Definition: ASTContext.h:1118
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1119
IdentifierTable & Idents
Definition: ASTContext.h:644
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:646
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
Definition: ASTContext.h:1092
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:758
CanQualType Float128Ty
Definition: ASTContext.h:1103
CanQualType UnsignedLongTy
Definition: ASTContext.h:1101
llvm::APFixedPoint getFixedPointMin(QualType Ty) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType CharTy
Definition: ASTContext.h:1093
CanQualType IntTy
Definition: ASTContext.h:1100
QualType getWebAssemblyExternrefType() const
Return a WebAssembly externref type.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2155
CanQualType SignedCharTy
Definition: ASTContext.h:1100
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
CanQualType OCLClkEventTy
Definition: ASTContext.h:1127
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:697
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2606
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2329
CanQualType BuiltinFnTy
Definition: ASTContext.h:1120
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1091
CanQualType UnsignedCharTy
Definition: ASTContext.h:1101
CanQualType UnsignedIntTy
Definition: ASTContext.h:1101
QualType getExceptionObjectType(QualType T) const
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1102
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1128
CanQualType UnsignedShortTy
Definition: ASTContext.h:1101
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1567
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
CanQualType ShortTy
Definition: ASTContext.h:1100
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
llvm::APFixedPoint getFixedPointMax(QualType Ty) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:757
CanQualType OCLQueueTy
Definition: ASTContext.h:1128
CanQualType BFloat16Ty
Definition: ASTContext.h:1116
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
CanQualType getNSIntegerType() const
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType LongLongTy
Definition: ASTContext.h:1100
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Underlying=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
QualType DecodeTypeStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequireICE, bool AllowTypeModifiers) const
@ GE_None
No error.
Definition: ASTContext.h:2231
CanQualType HalfTy
Definition: ASTContext.h:1115
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
CanQualType getNSUIntegerType() const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2333
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
CharUnits getNonVirtualAlignment() const
getNonVirtualAlignment - Get the non-virtual alignment (in chars) of an object, which is the alignmen...
Definition: RecordLayout.h:218
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition: Expr.h:4141
Expr * getCond() const
getCond - Return the expression representing the condition for the ?: operator.
Definition: Expr.h:4319
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition: Expr.h:4325
SourceLocation getQuestionLoc() const
Definition: Expr.h:4168
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition: Expr.h:4331
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2664
SourceLocation getRBracketLoc() const
Definition: Expr.h:2712
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition: Expr.h:2693
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3308
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3322
QualType getElementType() const
Definition: Type.h:3320
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition: Expr.h:6437
std::unique_ptr< AtomicScopeModel > getScopeModel() const
Get atomic scope model.
Definition: Expr.h:6578
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:6544
Attr - This represents one attribute.
Definition: Attr.h:42
const char * getSpelling() const
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3840
static bool isLogicalOp(Opcode Opc)
Definition: Expr.h:3972
Expr * getLHS() const
Definition: Expr.h:3889
SourceLocation getOperatorLoc() const
Definition: Expr.h:3881
SourceLocation getExprLoc() const
Definition: Expr.h:3880
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition: Expr.cpp:2134
Expr * getRHS() const
Definition: Expr.h:3891
bool isEqualityOp() const
Definition: Expr.h:3937
static bool isAdditiveOp(Opcode Opc)
Definition: Expr.h:3925
Opcode getOpcode() const
Definition: Expr.h:3884
static bool isEqualityOp(Opcode Opc)
Definition: Expr.h:3936
A fixed int type of a specified bitwidth.
Definition: Type.h:7032
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4495
Stmt * getBody() const override
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition: Decl.h:4574
bool capturesVariable(const VarDecl *var) const
Definition: Decl.cpp:5254
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:4601
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6173
const BlockDecl * getBlockDecl() const
Definition: Expr.h:6185
Pointer to a block type.
Definition: Type.h:3139
QualType getPointeeType() const
Definition: Type.h:3151
This class is used for builtin types like 'int'.
Definition: Type.h:2771
bool isInteger() const
Definition: Type.h:2826
bool isFloatingPoint() const
Definition: Type.h:2838
bool isSignedInteger() const
Definition: Type.h:2830
bool isUnsignedInteger() const
Definition: Type.h:2834
Kind getKind() const
Definition: Type.h:2813
bool isAuxBuiltinID(unsigned ID) const
Return true if builtin ID belongs to AuxTarget.
Definition: Builtins.h:262
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition: Builtins.h:222
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:103
unsigned getAuxBuiltinID(unsigned ID) const
Return real builtin ID (i.e.
Definition: Builtins.h:268
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:111
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition: Expr.h:3771
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1540
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition: ExprCXX.h:1622
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition: ExprCXX.h:1680
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2796
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2057
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
SourceLocation getExprLoc() const LLVM_READONLY
Definition: ExprCXX.h:151
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition: ExprCXX.h:111
Represents a list-initialization with parenthesis.
Definition: ExprCXX.h:4923
ArrayRef< Expr * > getInitExprs()
Definition: ExprCXX.h:4963
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition: DeclCXX.h:1225
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:612
base_class_iterator bases_begin()
Definition: DeclCXX.h:625
bool isDynamicClass() const
Definition: DeclCXX.h:584
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:73
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2820
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3011
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:3024
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1638
arg_iterator arg_begin()
Definition: Expr.h:3064
arg_iterator arg_end()
Definition: Expr.h:3067
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2990
bool isCallToStdMove() const
Definition: Expr.cpp:3510
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:1647
Expr * getCallee()
Definition: Expr.h:2970
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2998
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition: Expr.h:3096
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:3001
arg_range arguments()
Definition: Expr.h:3059
SourceLocation getRParenLoc() const
Definition: Expr.h:3130
Decl * getCalleeDecl()
Definition: Expr.h:2984
bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const
Returns true if this is a call to a builtin which does not evaluate side-effects within its arguments...
Definition: Expr.cpp:1584
void setCallee(Expr *F)
Definition: Expr.h:2972
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3483
path_iterator path_begin()
Definition: Expr.h:3553
CastKind getCastKind() const
Definition: Expr.h:3527
path_iterator path_end()
Definition: Expr.h:3554
Expr * getSubExpr()
Definition: Expr.h:3533
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
bool isOne() const
isOne - Test whether the quantity equals one.
Definition: CharUnits.h:125
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
void setExprNeedsCleanups(bool SideEffects)
Definition: CleanupInfo.h:28
Complex values, per C99 6.2.5p11.
Definition: Type.h:2876
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:4088
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4179
Expr * getLHS() const
Definition: Expr.h:4213
Expr * getRHS() const
Definition: Expr.h:4214
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3346
QualType desugar() const
Definition: Type.h:3447
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3402
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:3957
static constexpr unsigned getMaxElementsPerDimension()
Returns the maximum number of elements per dimension.
Definition: Type.h:3991
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition: Type.h:3986
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition: Expr.h:4499
Represents an expression that might suspend coroutine execution; either a co_await or co_yield expres...
Definition: ExprCXX.h:5040
Expr * getOperand() const
Definition: ExprCXX.h:5109
child_range children()
Definition: ExprCXX.h:5139
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2341
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1435
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2065
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1264
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2321
bool isFunctionOrMethod() const
Definition: DeclBase.h:2117
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:551
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:488
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition: Expr.h:1347
ValueDecl * getDecl()
Definition: Expr.h:1328
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition: Expr.h:1452
SourceLocation getLocation() const
Definition: Expr.h:1336
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
bool isInStdNamespace() const
Definition: DeclBase.cpp:403
T * getAttr() const
Definition: DeclBase.h:578
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition: DeclBase.cpp:515
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
Definition: DeclBase.cpp:1116
bool isInvalidDecl() const
Definition: DeclBase.h:593
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:564
SourceLocation getLocation() const
Definition: DeclBase.h:444
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:436
bool hasAttr() const
Definition: DeclBase.h:582
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:967
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:432
The name of a declaration.
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1985
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
RAII class that determines when any errors have occurred between the time the instance was created an...
Definition: Diagnostic.h:1077
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Definition: Diagnostic.h:1088
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3298
Represents an enum.
Definition: Decl.h:3868
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition: Decl.h:4065
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4087
TypeSourceInfo * getIntegerTypeSourceInfo() const
Return the type source info for the underlying integer type, if no type source info exists,...
Definition: Decl.h:4044
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4028
unsigned getNumPositiveBits() const
Returns the width in bits required to store all the non-negative enumerators of this enum.
Definition: Decl.h:4054
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5365
EvaluatedExprVisitor - This class visits 'Expr *'s.
This represents one expression.
Definition: Expr.h:110
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition: Expr.h:671
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition: Expr.h:668
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3064
void setType(QualType t)
Definition: Expr.h:143
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3059
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3047
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3055
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4079
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:821
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:825
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:444
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3051
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3556
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:221
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3039
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition: Expr.h:792
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition: Expr.h:801
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:804
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition: Expr.h:794
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:3918
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition: Expr.cpp:266
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition: Expr.h:454
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition: Expr.h:457
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isFlexibleArrayMemberLike(ASTContext &Context, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution=false) const
Check whether this array fits the idiom of a flexible array member, depending on the value of -fstric...
Definition: Expr.cpp:206
QualType getType() const
Definition: Expr.h:142
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
const ValueDecl * getAsBuiltinConstantDeclRef(const ASTContext &Context) const
If this expression is an unambiguous reference to a single declaration, in the style of __builtin_fun...
Definition: Expr.cpp:226
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition: Expr.cpp:136
void EvaluateForOverflow(const ASTContext &Ctx) const
ExtVectorType - Extended vector type.
Definition: Type.h:3851
Represents a member of a struct/union/class.
Definition: Decl.h:3058
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3149
unsigned getBitWidthValue(const ASTContext &Ctx) const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4594
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3271
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition: Decl.h:3162
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
llvm::APFloat getValue() const
Definition: Expr.h:1647
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition: Stmt.h:2786
Represents a function declaration or definition.
Definition: Decl.h:1971
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition: Decl.cpp:4401
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2707
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3713
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3632
param_iterator param_end()
Definition: Decl.h:2697
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3731
QualType getReturnType() const
Definition: Decl.h:2755
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2684
param_iterator param_begin()
Definition: Decl.h:2696
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3089
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4178
bool isStatic() const
Definition: Decl.h:2839
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3993
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3979
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3692
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4446
unsigned getNumParams() const
Definition: Type.h:4679
QualType getParamType(unsigned i) const
Definition: Type.h:4681
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition: Type.h:4884
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4802
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4690
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.h:4797
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4686
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4046
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition: Type.h:4333
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition: Type.h:4329
@ SME_PStateSMEnabledMask
Definition: Type.h:4307
@ SME_PStateSMCompatibleMask
Definition: Type.h:4308
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3655
Describes an C or C++ initializer list.
Definition: Expr.h:4847
ArrayRef< Expr * > inits()
Definition: Expr.h:4887
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:977
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:449
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition: Lexer.cpp:1024
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:1060
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
Definition: Lexer.cpp:499
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:1107
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Definition: Lexer.cpp:850
Represents the results of name lookup.
Definition: Lookup.h:46
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:566
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:632
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition: Type.h:3942
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3172
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3255
Expr * getBase() const
Definition: Expr.h:3249
bool isArrow() const
Definition: Expr.h:3356
@ ClassId_NSMutableArray
Definition: NSAPI.h:33
@ ClassId_NSMutableOrderedSet
Definition: NSAPI.h:38
@ ClassId_NSMutableSet
Definition: NSAPI.h:37
@ ClassId_NSMutableDictionary
Definition: NSAPI.h:35
NSSetMethodKind
Enumerates the NSMutableSet/NSOrderedSet methods used to apply some checks.
Definition: NSAPI.h:121
@ NSOrderedSet_setObjectAtIndex
Definition: NSAPI.h:124
@ NSMutableSet_addObject
Definition: NSAPI.h:122
@ NSOrderedSet_replaceObjectAtIndexWithObject
Definition: NSAPI.h:126
@ NSOrderedSet_setObjectAtIndexedSubscript
Definition: NSAPI.h:125
@ NSOrderedSet_insertObjectAtIndex
Definition: NSAPI.h:123
NSDictionaryMethodKind
Enumerates the NSDictionary/NSMutableDictionary methods used to generate literals and to apply some c...
Definition: NSAPI.h:96
@ NSMutableDict_setValueForKey
Definition: NSAPI.h:109
@ NSMutableDict_setObjectForKey
Definition: NSAPI.h:107
@ NSMutableDict_setObjectForKeyedSubscript
Definition: NSAPI.h:108
NSArrayMethodKind
Enumerates the NSArray/NSMutableArray methods used to generate literals and to apply some checks.
Definition: NSAPI.h:72
@ NSMutableArr_setObjectAtIndexedSubscript
Definition: NSAPI.h:84
@ NSMutableArr_insertObjectAtIndex
Definition: NSAPI.h:83
@ NSMutableArr_addObject
Definition: NSAPI.h:82
@ NSMutableArr_replaceObjectAtIndex
Definition: NSAPI.h:81
This represents a decl that may have a name.
Definition: Decl.h:249
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
ObjCStringFormatFamily getObjCFStringFormattingFamily() const
Definition: Decl.cpp:1156
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1927
Represent a C++ namespace.
Definition: Decl.h:547
Flags to identify the types for overloaded Neon builtins.
bool isUnsigned() const
EltType getEltType() const
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition: Stmt.h:1574
bool hasLeadingEmptyMacro() const
Definition: Stmt.h:1588
SourceLocation getSemiLoc() const
Definition: Stmt.h:1585
OpenMP 5.0 [2.1.5, Array Sections].
Definition: ExprOpenMP.h:56
Expr * getBase()
An array section can be written only as Base[LowerBound:Length].
Definition: ExprOpenMP.h:85
Expr * getLowerBound()
Get lower bound of array section.
Definition: ExprOpenMP.h:94
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp,...
Definition: ExprObjC.h:191
Expr * getElement(unsigned Index)
getElement - Return the Element at the specified index.
Definition: ExprObjC.h:231
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c array literal.
Definition: ExprObjC.h:228
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
Definition: ExprObjC.h:309
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c dictionary literal.
Definition: ExprObjC.h:360
ObjCDictionaryElement getKeyValueElement(unsigned Index) const
Definition: ExprObjC.h:362
Represents an ObjC class declaration.
Definition: DeclObjC.h:1152
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition: DeclObjC.h:1911
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1948
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:549
bool isFreeIvar() const
Definition: ExprObjC.h:588
const Expr * getBase() const
Definition: ExprObjC.h:583
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:945
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: ExprObjC.h:1395
Expr * getInstanceReceiver()
Returns the object expression (receiver) for an instance message, or null for a message that is not a...
Definition: ExprObjC.h:1260
SourceLocation getSuperLoc() const
Retrieve the location of the 'super' keyword for a class or instance message to 'super',...
Definition: ExprObjC.h:1301
Selector getSelector() const
Definition: ExprObjC.cpp:293
@ SuperInstance
The receiver is the instance of the superclass object.
Definition: ExprObjC.h:959
@ Instance
The receiver is an object instance.
Definition: ExprObjC.h:953
bool isInstanceMessage() const
Determine whether this is an instance message to either a computed object or to super.
Definition: ExprObjC.h:1248
const ObjCMethodDecl * getMethodDecl() const
Definition: ExprObjC.h:1356
ReceiverKind getReceiverKind() const
Determine the kind of receiver that this message is being sent to.
Definition: ExprObjC.h:1234
unsigned getNumArgs() const
Return the number of actual arguments in this message, not counting the receiver.
Definition: ExprObjC.h:1382
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:418
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:373
bool isVariadic() const
Definition: DeclObjC.h:431
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: DeclObjC.h:284
Represents a pointer to an Objective C object.
Definition: Type.h:6798
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments for this type.
Definition: Type.h:6902
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:729
QualType getType() const
Definition: DeclObjC.h:802
ObjCPropertyAttribute::Kind getPropertyAttributesAsWritten() const
Definition: DeclObjC.h:825
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition: DeclObjC.h:813
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition: ExprObjC.h:617
ObjCPropertyDecl * getExplicitProperty() const
Definition: ExprObjC.h:706
const Expr * getBase() const
Definition: ExprObjC.h:755
bool isImplicitProperty() const
Definition: ExprObjC.h:703
SourceLocation getLocation() const
Definition: ExprObjC.h:762
bool isSuperReceiver() const
Definition: ExprObjC.h:775
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:51
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition: Expr.h:1218
bool isSupported(llvm::StringRef Ext, const LangOptions &LO) const
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:250
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:2130
Represents a parameter to a function.
Definition: Decl.h:1761
PipeType - OpenCL20.
Definition: Type.h:6998
QualType getElementType() const
Definition: Type.h:7009
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2929
QualType getPointeeType() const
Definition: Type.h:2939
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6305
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition: Expr.cpp:4875
A (possibly-)qualified type.
Definition: Type.h:738
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7233
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:7227
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2716
PrimitiveDefaultInitializeKind
Definition: Type.h:1245
QualType withoutLocalFastQualifiers() const
Definition: Type.h:1007
QualType withConst() const
Definition: Type.h:952
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:949
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:7331
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:805
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7149
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7275
bool isConstant(const ASTContext &Ctx) const
Definition: Type.h:898
QualType withVolatile() const
Definition: Type.h:960
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7189
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1230
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
Definition: Type.h:7201
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7243
void removeLocalVolatile()
Definition: Type.h:7265
void removeLocalConst()
Definition: Type.h:7257
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7222
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1125
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1234
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:176
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:169
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:165
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:179
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:182
bool hasUnaligned() const
Definition: Type.h:319
Represents a struct/union/class.
Definition: Decl.h:4169
field_iterator field_end() const
Definition: Decl.h:4378
field_range fields() const
Definition: Decl.h:4375
field_iterator field_begin() const
Definition: Decl.cpp:5070
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5339
RecordDecl * getDecl() const
Definition: Type.h:5349
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
ScopeFlags
ScopeFlags - These are bitfields that are or'd together when creating a scope, which defines the sort...
Definition: Scope.h:45
@ SEHFilterScope
We are currently in the filter expression of an SEH except block.
Definition: Scope.h:131
@ SEHExceptScope
This scope corresponds to an SEH except.
Definition: Scope.h:128
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
bool isUnarySelector() const
unsigned getNumArgs() const
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:110
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:56
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:457
const FieldDecl * getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned)
Returns a field in a CXXRecordDecl that has the same name as the decl SelfAssigned when inside a CXXM...
Definition: SemaExpr.cpp:14853
bool IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base, const TypeSourceInfo *Derived)
bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef< const Expr * > Args, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any non-ArgDependent DiagnoseIf...
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:9779
void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:698
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
Definition: Sema.cpp:2453
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7368
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7376
@ LookupAnyName
Look up any declaration with any name.
Definition: Sema.h:7413
VariadicCallType
Definition: Sema.h:2013
@ VariadicDoesNotApply
Definition: Sema.h:2018
@ VariadicFunction
Definition: Sema.h:2014
@ VariadicMethod
Definition: Sema.h:2016
@ VariadicConstructor
Definition: Sema.h:2017
@ VariadicBlock
Definition: Sema.h:2015
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull)
Register a magic integral constant to be used as a type tag.
bool isValidPointerAttrType(QualType T, bool RefOkay=false)
Determine if type T is a valid subject for a nonnull and similar attributes.
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
bool FormatStringHasSArg(const StringLiteral *FExpr)
ObjCInterfaceDecl * NSDictionaryDecl
The declaration of the Objective-C NSDictionary class.
Definition: Sema.h:12215
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6....
Definition: SemaExpr.cpp:1561
static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, bool IsVariadic, FormatStringInfo *FSI)
Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo parameter with the Format...
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: Sema.h:12179
void RefersToMemberWithReducedAlignment(Expr *E, llvm::function_ref< void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action)
This function calls Action when it determines that E designates a misaligned member due to the packed...
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
Definition: SemaExpr.cpp:12036
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition: Sema.cpp:1499
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition: SemaExpr.cpp:796
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but will create a trap if the resul...
Definition: SemaExpr.cpp:1046
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
Definition: SemaExpr.cpp:5237
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:14494
ASTContext & Context
Definition: Sema.h:858
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:524
static FormatStringType GetFormatStringType(const FormatAttr *Format)
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:762
ASTContext & getASTContext() const
Definition: Sema.h:527
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:16036
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:645
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition: Sema.h:1862
bool BuiltinVectorToScalarMath(CallExpr *TheCall)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:775
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1504
bool CheckHLSLBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
Warn if a value is moved to itself.
AtomicArgumentOrder
Definition: Sema.h:1962
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:63
bool IsLayoutCompatible(QualType T1, QualType T2) const
const LangOptions & getLangOpts() const
Definition: Sema.h:520
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
Definition: SemaType.cpp:9246
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange)
CheckCastAlign - Implements -Wcast-align, which warns when a pointer cast increases the alignment req...
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
Definition: SemaExpr.cpp:5915
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6655
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
bool hasCStrMethod(const Expr *E)
Check to see if a given expression could have '.c_str()' called on it.
const LangOptions & LangOpts
Definition: Sema.h:856
static const uint64_t MaximumAlignment
Definition: Sema.h:798
SemaHLSL & HLSL()
Definition: Sema.h:1003
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
ObjCLiteralKind
Definition: Sema.h:5719
@ LK_String
Definition: Sema.h:5724
@ LK_None
Definition: Sema.h:5726
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type.
static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx)
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:5187
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition: Sema.cpp:1511
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:944
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op)
Definition: SemaCast.cpp:3340
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:892
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
Definition: Sema.h:1940
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
Definition: SemaExpr.cpp:10023
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition: Sema.cpp:2079
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID)
Emit DiagID if statement located on StmtLoc has a suspicious null statement as a Body,...
void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody)
Warn if a for/while loop statement S, which is followed by PossibleBody, has a suspicious null statem...
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:651
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
bool BuiltinVectorMath(CallExpr *TheCall, QualType &Res)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:996
@ VAK_Invalid
Definition: Sema.h:6052
@ VAK_Valid
Definition: Sema.h:6048
@ VAK_ValidInCXX11
Definition: Sema.h:6049
@ VAK_MSVCUndefined
Definition: Sema.h:6051
@ VAK_Undefined
Definition: Sema.h:6050
FormatArgumentPassingKind
Definition: Sema.h:1872
@ FAPK_Fixed
Definition: Sema.h:1873
@ FAPK_Variadic
Definition: Sema.h:1874
@ FAPK_VAList
Definition: Sema.h:1875
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:6286
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:6090
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:6092
@ ACK_Comparison
A comparison.
Definition: Sema.h:5939
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:21225
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:10476
SourceManager & getSourceManager() const
Definition: Sema.h:525
@ AA_Assigning
Definition: Sema.h:5196
@ AA_Passing
Definition: Sema.h:5197
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
ObjCInterfaceDecl * NSArrayDecl
The declaration of the Objective-C NSArray class.
Definition: Sema.h:12209
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20503
ExprResult BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl=DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr=nullptr, SourceLocation opLoc=SourceLocation())
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:227
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
bool isConstantEvaluatedContext() const
Definition: Sema.h:1864
ExprResult BuiltinShuffleVector(CallExpr *TheCall)
BuiltinShuffleVector - Handle __builtin_shufflevector.
QualType GetSignedVectorType(QualType V)
Definition: SemaExpr.cpp:13027
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9276
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:830
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
SourceManager & SourceMgr
Definition: Sema.h:861
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
DiagnosticsEngine & Diags
Definition: Sema.h:860
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:521
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10662
void checkVariadicArgument(const Expr *E, VariadicCallType CT)
Check to see if the given expression is a valid argument to a variadic function, issuing a diagnostic...
Definition: SemaExpr.cpp:999
FormatStringType
Definition: Sema.h:1895
@ FST_NSString
Definition: Sema.h:1898
@ FST_Unknown
Definition: Sema.h:1905
@ FST_Strftime
Definition: Sema.h:1899
@ FST_Printf
Definition: Sema.h:1897
@ FST_FreeBSDKPrintf
Definition: Sema.h:1902
@ FST_Scanf
Definition: Sema.h:1896
@ FST_Strfmon
Definition: Sema.h:1900
@ FST_OSLog
Definition: Sema.h:1904
@ FST_Kprintf
Definition: Sema.h:1901
@ FST_OSTrace
Definition: Sema.h:1903
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:520
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
Definition: SemaExpr.cpp:17129
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:18358
@ AbstractParamType
Definition: Sema.h:4585
ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder=AtomicArgumentOrder::API)
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E)
CheckCXXThrowOperand - Validate the operand of a throw.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition: Expr.h:4431
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
SourceLocation getTopMacroCallerLoc(SourceLocation Loc) const
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isWrittenInSameFile(SourceLocation Loc1, SourceLocation Loc2) const
Returns true if the spelling locations for both SourceLocations are part of the same file buffer.
unsigned getPresumedColumnNumber(SourceLocation Loc, bool *Invalid=nullptr) const
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
child_range children()
Definition: Stmt.cpp:287
StmtClass getStmtClass() const
Definition: Stmt.h:1363
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1954
bool isUTF8() const
Definition: Expr.h:1899
bool isWide() const
Definition: Expr.h:1898
bool isPascal() const
Definition: Expr.h:1903
unsigned getLength() const
Definition: Expr.h:1890
StringLiteralKind getKind() const
Definition: Expr.h:1893
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
getLocationOfByte - Return a source location that points to the specified byte of this string literal...
Definition: Expr.cpp:1329
bool isUTF32() const
Definition: Expr.h:1901
unsigned getByteLength() const
Definition: Expr.h:1889
StringRef getString() const
Definition: Expr.h:1850
bool isUTF16() const
Definition: Expr.h:1900
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.h:1955
bool isOrdinary() const
Definition: Expr.h:1897
unsigned getCharByteWidth() const
Definition: Expr.h:1891
bool isUnion() const
Definition: Decl.h:3791
Exposes information about the current target.
Definition: TargetInfo.h:213
virtual bool validatePointerAuthKey(const llvm::APSInt &value) const
Determine whether the given pointer-authentication key is valid.
Definition: TargetInfo.cpp:929
virtual bool supportsCpuSupports() const
Definition: TargetInfo.h:1477
virtual bool validateCpuIs(StringRef Name) const
Definition: TargetInfo.h:1497
virtual bool supportsCpuInit() const
Definition: TargetInfo.h:1479
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1235
IntType getInt64Type() const
Definition: TargetInfo.h:400
virtual bool useFP16ConversionIntrinsics() const
Check whether llvm intrinsics such as llvm.convert.to.fp16 should be used to convert to and from __fp...
Definition: TargetInfo.h:971
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
Definition: TargetInfo.cpp:270
IntType getSizeType() const
Definition: TargetInfo.h:366
IntType getIntPtrType() const
Definition: TargetInfo.h:392
uint32_t getARMCDECoprocMask() const
For ARM targets returns a mask defining which coprocessors are configured as Custom Datapath.
Definition: TargetInfo.h:1031
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1483
virtual bool supportsCpuIs() const
Definition: TargetInfo.h:1478
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:764
virtual bool checkArithmeticFenceSupported() const
Controls if __arithmetic_fence is supported in the targeted backend.
Definition: TargetInfo.h:1636
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1451
virtual bool hasSjLjLowering() const
Controls if __builtin_longjmp / __builtin_setjmp can be lowered to llvm.eh.sjlj.longjmp / llvm....
Definition: TargetInfo.h:1685
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
Definition: DeclTemplate.h:265
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
const Type * getTypeForDecl() const
Definition: Decl.h:3415
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition: Type.h:5064
A container of type source information.
Definition: Type.h:7120
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7131
The base class of the type hierarchy.
Definition: Type.h:1607
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1870
bool isBlockPointerType() const
Definition: Type.h:7410
bool isVoidType() const
Definition: Type.h:7695
bool isBooleanType() const
Definition: Type.h:7823
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:7870
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:729
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2134
bool isFloat16Type() const
Definition: Type.h:7704
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2205
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2059
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:7850
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition: Type.cpp:2009
bool isVoidPointerType() const
Definition: Type.cpp:654
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2340
bool isArrayType() const
Definition: Type.h:7468
bool isCharType() const
Definition: Type.cpp:2077
bool isFunctionPointerType() const
Definition: Type.h:7436
bool isPointerType() const
Definition: Type.h:7402
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7735
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7980
bool isReferenceType() const
Definition: Type.h:7414
bool isEnumeralType() const
Definition: Type.h:7500
bool isScalarType() const
Definition: Type.h:7794
bool isVariableArrayType() const
Definition: Type.h:7480
bool isClkEventT() const
Definition: Type.h:7607
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2487
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2046
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:694
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:7810
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2224
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2513
bool isPipeType() const
Definition: Type.h:7626
bool isBitIntType() const
Definition: Type.h:7630
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7664
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:7492
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2443
bool isFloat32Type() const
Definition: Type.h:7708
bool isAnyComplexType() const
Definition: Type.h:7504
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7748
bool isHalfType() const
Definition: Type.h:7699
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:7677
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2174
QualType getCanonicalTypeInternal() const
Definition: Type.h:2726
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2444
bool isQueueT() const
Definition: Type.h:7611
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:7863
bool isMemberPointerType() const
Definition: Type.h:7450
bool isAtomicType() const
Definition: Type.h:7547
bool isFunctionProtoType() const
Definition: Type.h:2284
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition: Type.cpp:2961
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2461
bool isObjCObjectType() const
Definition: Type.h:7538
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:7966
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:7829
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2195
bool isBFloat16Type() const
Definition: Type.h:7716
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2350
bool isFunctionType() const
Definition: Type.h:7398
bool isObjCObjectPointerType() const
Definition: Type.h:7534
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition: Type.cpp:2246
bool isStructureOrClassType() const
Definition: Type.cpp:646
bool isVectorType() const
Definition: Type.h:7508
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2254
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2474
bool isFloatingType() const
Definition: Type.cpp:2237
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:2184
bool isAnyPointerType() const
Definition: Type.h:7406
TypeClass getTypeClass() const
Definition: Type.h:2094
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:2120
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7913
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:604
bool isNullPtrType() const
Definition: Type.h:7728
bool isRecordType() const
Definition: Type.h:7496
bool isObjCRetainableType() const
Definition: Type.cpp:4862
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4610
bool isUnionType() const
Definition: Type.cpp:660
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1874
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3433
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2568
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2183
Expr * getSubExpr() const
Definition: Expr.h:2228
Opcode getOpcode() const
Definition: Expr.h:2223
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:2305
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3317
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
QualType getType() const
Definition: Decl.h:717
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5366
Represents a variable declaration or definition.
Definition: Decl.h:918
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2187
Represents a GCC generic vector type.
Definition: Type.h:3759
unsigned getNumElements() const
Definition: Type.h:3774
WhileStmt - This represents a 'while' stmt.
Definition: Stmt.h:2589
MatchKind
How well a given conversion specifier matches its argument.
Definition: FormatString.h:271
@ NoMatch
The conversion specifier and the argument types are incompatible.
Definition: FormatString.h:274
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
Definition: FormatString.h:286
@ Match
The conversion specifier and the argument type are compatible.
Definition: FormatString.h:277
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
Definition: FormatString.h:288
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
std::optional< ConversionSpecifier > getStandardSpecifier() const
ArgType getArgType(ASTContext &Ctx) const
Class representing optional flags with location and representation information.
Definition: FormatString.h:34
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
Definition: ScopeInfo.cpp:160
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition: larchintrin.h:181
bool evaluateRequiredTargetFeatures(llvm::StringRef RequiredFatures, const llvm::StringMap< bool > &TargetFetureMap)
Returns true if the required target features of a builtin function are enabled.
bool parseFormatStringHasFormattingSpecifiers(const char *Begin, const char *End, const LangOptions &LO, const TargetInfo &Target)
Return true if the given string has at least one formatting specifier.
bool ParsePrintfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target, bool isFreeBSDKPrintf)
bool ParseScanfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
bool ParseFormatStringHasSArg(const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
const AstTypeMatcher< PointerType > pointerType
Matches pointer types, but does not match Objective-C object pointer types.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
ComparisonResult
Indicates the result of a tentative comparison.
uint32_t Literal
Literals are represented as positive integers.
uint32_t Variable
Boolean variables are represented as positive integers.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:68
@ After
Like System, but searched after the system directories.
@ FixIt
Parse and apply any fixits to the source.
bool GT(InterpState &S, CodePtr OpPC)
Definition: Interp.h:890
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:868
bool LE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:882
bool InRange(InterpState &S, CodePtr OpPC)
Definition: Interp.h:909
bool Cast(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1706
bool EQ(InterpState &S, CodePtr OpPC)
Definition: Interp.h:837
bool GE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:897
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:32
The JSON file list parser is used to communicate input to InstallAPI.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
ObjCStringFormatFamily
@ CPlusPlus
Definition: LangStandard.h:55
Expr * IgnoreElidableImplicitConstructorSingleStep(Expr *E)
Definition: IgnoreExpr.h:125
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ NonNull
Values of this type can never be null.
Expr * IgnoreExprNodes(Expr *E, FnTys &&... Fns)
Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *, Recursively apply each of the f...
Definition: IgnoreExpr.h:34
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:146
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:148
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:151
BinaryOperatorKind
@ SC_Register
Definition: Specifiers.h:254
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ Result
The result type of a method or function.
LLVM_READONLY bool isLowercase(unsigned char c)
Return true if this character is a lowercase ASCII letter: [a-z].
Definition: CharInfo.h:121
ExprResult ExprError()
Definition: Ownership.h:264
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
CastKind
CastKind - The kind of operation required for a conversion.
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:250
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
for(const auto &A :T->param_types())
const FunctionProtoType * T
Expr * IgnoreImplicitAsWrittenSingleStep(Expr *E)
Definition: IgnoreExpr.h:137
StringLiteralKind
Definition: Expr.h:1744
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ Success
Template argument deduction was successful.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_Win64
Definition: Specifiers.h:282
@ CC_C
Definition: Specifiers.h:276
@ CC_X86_64SysV
Definition: Specifiers.h:283
@ AltiVecVector
is AltiVec vector
@ Generic
not a target-specific vector type
U cast(CodeGen::Address addr)
Definition: Address.h:291
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Other
Other implicit parameter.
@ AS_public
Definition: Specifiers.h:121
unsigned long uint64_t
long int64_t
Definition: Format.h:5394
#define true
Definition: stdbool.h:21
#define false
Definition: stdbool.h:22
#define bool
Definition: stdbool.h:20
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:630
Extra information about a function prototype.
Definition: Type.h:4525
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
unsigned AnonymousTagLocations
When printing an anonymous tag name, also print the location of that entity (e.g.,...
unsigned Indentation
The number of spaces to use to indent each line.
Definition: PrettyPrinter.h:93
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:9796
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:9913
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition: Sema.h:9939
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition: Sema.h:9929
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition: Sema.h:9894
FormatArgumentPassingKind ArgPassingKind
Definition: Sema.h:1883
#define log2(__x)
Definition: tgmath.h:970