clang 20.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 "CheckExprLifetime.h"
15#include "clang/AST/APValue.h"
17#include "clang/AST/Attr.h"
19#include "clang/AST/CharUnits.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclBase.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclObjC.h"
26#include "clang/AST/Expr.h"
27#include "clang/AST/ExprCXX.h"
28#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"
43#include "clang/Basic/LLVM.h"
54#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
56#include "clang/Sema/Lookup.h"
58#include "clang/Sema/Scope.h"
60#include "clang/Sema/Sema.h"
62#include "clang/Sema/SemaARM.h"
63#include "clang/Sema/SemaBPF.h"
64#include "clang/Sema/SemaHLSL.h"
67#include "clang/Sema/SemaMIPS.h"
69#include "clang/Sema/SemaObjC.h"
71#include "clang/Sema/SemaPPC.h"
74#include "clang/Sema/SemaWasm.h"
75#include "clang/Sema/SemaX86.h"
76#include "llvm/ADT/APFloat.h"
77#include "llvm/ADT/APInt.h"
78#include "llvm/ADT/APSInt.h"
79#include "llvm/ADT/ArrayRef.h"
80#include "llvm/ADT/DenseMap.h"
81#include "llvm/ADT/FoldingSet.h"
82#include "llvm/ADT/STLExtras.h"
83#include "llvm/ADT/SmallBitVector.h"
84#include "llvm/ADT/SmallPtrSet.h"
85#include "llvm/ADT/SmallString.h"
86#include "llvm/ADT/SmallVector.h"
87#include "llvm/ADT/StringExtras.h"
88#include "llvm/ADT/StringRef.h"
89#include "llvm/ADT/StringSet.h"
90#include "llvm/ADT/StringSwitch.h"
91#include "llvm/Support/AtomicOrdering.h"
92#include "llvm/Support/Compiler.h"
93#include "llvm/Support/ConvertUTF.h"
94#include "llvm/Support/ErrorHandling.h"
95#include "llvm/Support/Format.h"
96#include "llvm/Support/Locale.h"
97#include "llvm/Support/MathExtras.h"
98#include "llvm/Support/SaveAndRestore.h"
99#include "llvm/Support/raw_ostream.h"
100#include "llvm/TargetParser/RISCVTargetParser.h"
101#include "llvm/TargetParser/Triple.h"
102#include <algorithm>
103#include <cassert>
104#include <cctype>
105#include <cstddef>
106#include <cstdint>
107#include <functional>
108#include <limits>
109#include <optional>
110#include <string>
111#include <tuple>
112#include <utility>
113
114using namespace clang;
115using namespace sema;
116
118 unsigned ByteNo) const {
119 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
121}
122
123static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
125 return (A << 8) | B;
126}
127
128bool Sema::checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount) {
129 unsigned ArgCount = Call->getNumArgs();
130 if (ArgCount >= MinArgCount)
131 return false;
132
133 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
134 << 0 /*function call*/ << MinArgCount << ArgCount
135 << /*is non object*/ 0 << Call->getSourceRange();
136}
137
138bool Sema::checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount) {
139 unsigned ArgCount = Call->getNumArgs();
140 if (ArgCount <= MaxArgCount)
141 return false;
142 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_many_args_at_most)
143 << 0 /*function call*/ << MaxArgCount << ArgCount
144 << /*is non object*/ 0 << Call->getSourceRange();
145}
146
147bool Sema::checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
148 unsigned MaxArgCount) {
149 return checkArgCountAtLeast(Call, MinArgCount) ||
150 checkArgCountAtMost(Call, MaxArgCount);
151}
152
153bool Sema::checkArgCount(CallExpr *Call, unsigned DesiredArgCount) {
154 unsigned ArgCount = Call->getNumArgs();
155 if (ArgCount == DesiredArgCount)
156 return false;
157
158 if (checkArgCountAtLeast(Call, DesiredArgCount))
159 return true;
160 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
161
162 // Highlight all the excess arguments.
163 SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
164 Call->getArg(ArgCount - 1)->getEndLoc());
165
166 return Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
167 << 0 /*function call*/ << DesiredArgCount << ArgCount
168 << /*is non object*/ 0 << Call->getArg(1)->getSourceRange();
169}
170
172 bool HasError = false;
173
174 for (unsigned I = 0; I < Call->getNumArgs(); ++I) {
175 Expr *Arg = Call->getArg(I);
176
177 if (Arg->isValueDependent())
178 continue;
179
180 std::optional<std::string> ArgString = Arg->tryEvaluateString(S.Context);
181 int DiagMsgKind = -1;
182 // Arguments must be pointers to constant strings and cannot use '$'.
183 if (!ArgString.has_value())
184 DiagMsgKind = 0;
185 else if (ArgString->find('$') != std::string::npos)
186 DiagMsgKind = 1;
187
188 if (DiagMsgKind >= 0) {
189 S.Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg)
190 << DiagMsgKind << Arg->getSourceRange();
191 HasError = true;
192 }
193 }
194
195 return !HasError;
196}
197
199 if (Value->isTypeDependent())
200 return false;
201
202 InitializedEntity Entity =
206 if (Result.isInvalid())
207 return true;
208 Value = Result.get();
209 return false;
210}
211
212/// Check that the first argument to __builtin_annotation is an integer
213/// and the second argument is a non-wide string literal.
214static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
215 if (S.checkArgCount(TheCall, 2))
216 return true;
217
218 // First argument should be an integer.
219 Expr *ValArg = TheCall->getArg(0);
220 QualType Ty = ValArg->getType();
221 if (!Ty->isIntegerType()) {
222 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
223 << ValArg->getSourceRange();
224 return true;
225 }
226
227 // Second argument should be a constant string.
228 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
229 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
230 if (!Literal || !Literal->isOrdinary()) {
231 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
232 << StrArg->getSourceRange();
233 return true;
234 }
235
236 TheCall->setType(Ty);
237 return false;
238}
239
240static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
241 // We need at least one argument.
242 if (TheCall->getNumArgs() < 1) {
243 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
244 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
245 << TheCall->getCallee()->getSourceRange();
246 return true;
247 }
248
249 // All arguments should be wide string literals.
250 for (Expr *Arg : TheCall->arguments()) {
251 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
252 if (!Literal || !Literal->isWide()) {
253 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
254 << Arg->getSourceRange();
255 return true;
256 }
257 }
258
259 return false;
260}
261
262/// Check that the argument to __builtin_addressof is a glvalue, and set the
263/// result type to the corresponding pointer type.
264static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
265 if (S.checkArgCount(TheCall, 1))
266 return true;
267
268 ExprResult Arg(TheCall->getArg(0));
269 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
270 if (ResultType.isNull())
271 return true;
272
273 TheCall->setArg(0, Arg.get());
274 TheCall->setType(ResultType);
275 return false;
276}
277
278/// Check that the argument to __builtin_function_start is a function.
279static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
280 if (S.checkArgCount(TheCall, 1))
281 return true;
282
284 if (Arg.isInvalid())
285 return true;
286
287 TheCall->setArg(0, Arg.get());
288 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
290
291 if (!FD) {
292 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
293 << TheCall->getSourceRange();
294 return true;
295 }
296
297 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
298 TheCall->getBeginLoc());
299}
300
301/// Check the number of arguments and set the result type to
302/// the argument type.
303static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
304 if (S.checkArgCount(TheCall, 1))
305 return true;
306
307 TheCall->setType(TheCall->getArg(0)->getType());
308 return false;
309}
310
311/// Check that the value argument for __builtin_is_aligned(value, alignment) and
312/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
313/// type (but not a function pointer) and that the alignment is a power-of-two.
314static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
315 if (S.checkArgCount(TheCall, 2))
316 return true;
317
318 clang::Expr *Source = TheCall->getArg(0);
319 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
320
321 auto IsValidIntegerType = [](QualType Ty) {
322 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
323 };
324 QualType SrcTy = Source->getType();
325 // We should also be able to use it with arrays (but not functions!).
326 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
327 SrcTy = S.Context.getDecayedType(SrcTy);
328 }
329 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
330 SrcTy->isFunctionPointerType()) {
331 // FIXME: this is not quite the right error message since we don't allow
332 // floating point types, or member pointers.
333 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
334 << SrcTy;
335 return true;
336 }
337
338 clang::Expr *AlignOp = TheCall->getArg(1);
339 if (!IsValidIntegerType(AlignOp->getType())) {
340 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
341 << AlignOp->getType();
342 return true;
343 }
344 Expr::EvalResult AlignResult;
345 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
346 // We can't check validity of alignment if it is value dependent.
347 if (!AlignOp->isValueDependent() &&
348 AlignOp->EvaluateAsInt(AlignResult, S.Context,
350 llvm::APSInt AlignValue = AlignResult.Val.getInt();
351 llvm::APSInt MaxValue(
352 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
353 if (AlignValue < 1) {
354 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
355 return true;
356 }
357 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
358 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
359 << toString(MaxValue, 10);
360 return true;
361 }
362 if (!AlignValue.isPowerOf2()) {
363 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
364 return true;
365 }
366 if (AlignValue == 1) {
367 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
368 << IsBooleanAlignBuiltin;
369 }
370 }
371
374 SourceLocation(), Source);
375 if (SrcArg.isInvalid())
376 return true;
377 TheCall->setArg(0, SrcArg.get());
378 ExprResult AlignArg =
380 S.Context, AlignOp->getType(), false),
381 SourceLocation(), AlignOp);
382 if (AlignArg.isInvalid())
383 return true;
384 TheCall->setArg(1, AlignArg.get());
385 // For align_up/align_down, the return type is the same as the (potentially
386 // decayed) argument type including qualifiers. For is_aligned(), the result
387 // is always bool.
388 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
389 return false;
390}
391
392static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
393 if (S.checkArgCount(TheCall, 3))
394 return true;
395
396 std::pair<unsigned, const char *> Builtins[] = {
397 { Builtin::BI__builtin_add_overflow, "ckd_add" },
398 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
399 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
400 };
401
402 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
403 const char *> &P) {
404 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
406 S.getSourceManager(), S.getLangOpts()) == P.second;
407 });
408
409 auto ValidCkdIntType = [](QualType QT) {
410 // A valid checked integer type is an integer type other than a plain char,
411 // bool, a bit-precise type, or an enumeration type.
412 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
413 return (BT->getKind() >= BuiltinType::Short &&
414 BT->getKind() <= BuiltinType::Int128) || (
415 BT->getKind() >= BuiltinType::UShort &&
416 BT->getKind() <= BuiltinType::UInt128) ||
417 BT->getKind() == BuiltinType::UChar ||
418 BT->getKind() == BuiltinType::SChar;
419 return false;
420 };
421
422 // First two arguments should be integers.
423 for (unsigned I = 0; I < 2; ++I) {
425 if (Arg.isInvalid()) return true;
426 TheCall->setArg(I, Arg.get());
427
428 QualType Ty = Arg.get()->getType();
429 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
430 if (!IsValid) {
431 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
432 << CkdOperation << Ty << Arg.get()->getSourceRange();
433 return true;
434 }
435 }
436
437 // Third argument should be a pointer to a non-const integer.
438 // IRGen correctly handles volatile, restrict, and address spaces, and
439 // the other qualifiers aren't possible.
440 {
442 if (Arg.isInvalid()) return true;
443 TheCall->setArg(2, Arg.get());
444
445 QualType Ty = Arg.get()->getType();
446 const auto *PtrTy = Ty->getAs<PointerType>();
447 if (!PtrTy ||
448 !PtrTy->getPointeeType()->isIntegerType() ||
449 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
450 PtrTy->getPointeeType().isConstQualified()) {
451 S.Diag(Arg.get()->getBeginLoc(),
452 diag::err_overflow_builtin_must_be_ptr_int)
453 << CkdOperation << Ty << Arg.get()->getSourceRange();
454 return true;
455 }
456 }
457
458 // Disallow signed bit-precise integer args larger than 128 bits to mul
459 // function until we improve backend support.
460 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
461 for (unsigned I = 0; I < 3; ++I) {
462 const auto Arg = TheCall->getArg(I);
463 // Third argument will be a pointer.
464 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
465 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
466 S.getASTContext().getIntWidth(Ty) > 128)
467 return S.Diag(Arg->getBeginLoc(),
468 diag::err_overflow_builtin_bit_int_max_size)
469 << 128;
470 }
471 }
472
473 return false;
474}
475
476namespace {
477struct BuiltinDumpStructGenerator {
478 Sema &S;
479 CallExpr *TheCall;
480 SourceLocation Loc = TheCall->getBeginLoc();
482 DiagnosticErrorTrap ErrorTracker;
483 PrintingPolicy Policy;
484
485 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
486 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
487 Policy(S.Context.getPrintingPolicy()) {
488 Policy.AnonymousTagLocations = false;
489 }
490
491 Expr *makeOpaqueValueExpr(Expr *Inner) {
492 auto *OVE = new (S.Context)
493 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
494 Inner->getObjectKind(), Inner);
495 Actions.push_back(OVE);
496 return OVE;
497 }
498
499 Expr *getStringLiteral(llvm::StringRef Str) {
501 // Wrap the literal in parentheses to attach a source location.
502 return new (S.Context) ParenExpr(Loc, Loc, Lit);
503 }
504
505 bool callPrintFunction(llvm::StringRef Format,
506 llvm::ArrayRef<Expr *> Exprs = {}) {
508 assert(TheCall->getNumArgs() >= 2);
509 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
510 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
511 Args.push_back(getStringLiteral(Format));
512 Args.insert(Args.end(), Exprs.begin(), Exprs.end());
513
514 // Register a note to explain why we're performing the call.
518 Ctx.CallArgs = Args.data();
519 Ctx.NumCallArgs = Args.size();
521
522 ExprResult RealCall =
523 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
524 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
525
527 if (!RealCall.isInvalid())
528 Actions.push_back(RealCall.get());
529 // Bail out if we've hit any errors, even if we managed to build the
530 // call. We don't want to produce more than one error.
531 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
532 }
533
534 Expr *getIndentString(unsigned Depth) {
535 if (!Depth)
536 return nullptr;
537
539 Indent.resize(Depth * Policy.Indentation, ' ');
540 return getStringLiteral(Indent);
541 }
542
544 return getStringLiteral(T.getAsString(Policy));
545 }
546
547 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
548 llvm::raw_svector_ostream OS(Str);
549
550 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
551 // than trying to print a single character.
552 if (auto *BT = T->getAs<BuiltinType>()) {
553 switch (BT->getKind()) {
554 case BuiltinType::Bool:
555 OS << "%d";
556 return true;
557 case BuiltinType::Char_U:
558 case BuiltinType::UChar:
559 OS << "%hhu";
560 return true;
561 case BuiltinType::Char_S:
562 case BuiltinType::SChar:
563 OS << "%hhd";
564 return true;
565 default:
566 break;
567 }
568 }
569
571 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
572 // We were able to guess how to format this.
573 if (Specifier.getConversionSpecifier().getKind() ==
574 analyze_printf::PrintfConversionSpecifier::sArg) {
575 // Wrap double-quotes around a '%s' specifier and limit its maximum
576 // length. Ideally we'd also somehow escape special characters in the
577 // contents but printf doesn't support that.
578 // FIXME: '%s' formatting is not safe in general.
579 OS << '"';
580 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
581 Specifier.toString(OS);
582 OS << '"';
583 // FIXME: It would be nice to include a '...' if the string doesn't fit
584 // in the length limit.
585 } else {
586 Specifier.toString(OS);
587 }
588 return true;
589 }
590
591 if (T->isPointerType()) {
592 // Format all pointers with '%p'.
593 OS << "%p";
594 return true;
595 }
596
597 return false;
598 }
599
600 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
601 Expr *IndentLit = getIndentString(Depth);
602 Expr *TypeLit = getTypeString(S.Context.getRecordType(RD));
603 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
604 : callPrintFunction("%s", {TypeLit}))
605 return true;
606
607 return dumpRecordValue(RD, E, IndentLit, Depth);
608 }
609
610 // Dump a record value. E should be a pointer or lvalue referring to an RD.
611 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
612 unsigned Depth) {
613 // FIXME: Decide what to do if RD is a union. At least we should probably
614 // turn off printing `const char*` members with `%s`, because that is very
615 // likely to crash if that's not the active member. Whatever we decide, we
616 // should document it.
617
618 // Build an OpaqueValueExpr so we can refer to E more than once without
619 // triggering re-evaluation.
620 Expr *RecordArg = makeOpaqueValueExpr(E);
621 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
622
623 if (callPrintFunction(" {\n"))
624 return true;
625
626 // Dump each base class, regardless of whether they're aggregates.
627 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
628 for (const auto &Base : CXXRD->bases()) {
629 QualType BaseType =
630 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
631 : S.Context.getLValueReferenceType(Base.getType());
634 RecordArg);
635 if (BasePtr.isInvalid() ||
636 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
637 Depth + 1))
638 return true;
639 }
640 }
641
642 Expr *FieldIndentArg = getIndentString(Depth + 1);
643
644 // Dump each field.
645 for (auto *D : RD->decls()) {
646 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
647 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
648 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
649 continue;
650
651 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
652 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
653 getTypeString(FD->getType()),
654 getStringLiteral(FD->getName())};
655
656 if (FD->isBitField()) {
657 Format += ": %zu ";
659 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
660 FD->getBitWidthValue(S.Context));
661 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
662 }
663
664 Format += "=";
665
668 CXXScopeSpec(), Loc, IFD,
669 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
671 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
673 DeclarationNameInfo(FD->getDeclName(), Loc));
674 if (Field.isInvalid())
675 return true;
676
677 auto *InnerRD = FD->getType()->getAsRecordDecl();
678 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
679 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
680 // Recursively print the values of members of aggregate record type.
681 if (callPrintFunction(Format, Args) ||
682 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
683 return true;
684 } else {
685 Format += " ";
686 if (appendFormatSpecifier(FD->getType(), Format)) {
687 // We know how to print this field.
688 Args.push_back(Field.get());
689 } else {
690 // We don't know how to print this field. Print out its address
691 // with a format specifier that a smart tool will be able to
692 // recognize and treat specially.
693 Format += "*%p";
694 ExprResult FieldAddr =
695 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
696 if (FieldAddr.isInvalid())
697 return true;
698 Args.push_back(FieldAddr.get());
699 }
700 Format += "\n";
701 if (callPrintFunction(Format, Args))
702 return true;
703 }
704 }
705
706 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
707 : callPrintFunction("}\n");
708 }
709
710 Expr *buildWrapper() {
711 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
713 TheCall->setType(Wrapper->getType());
714 TheCall->setValueKind(Wrapper->getValueKind());
715 return Wrapper;
716 }
717};
718} // namespace
719
721 if (S.checkArgCountAtLeast(TheCall, 2))
722 return ExprError();
723
724 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
725 if (PtrArgResult.isInvalid())
726 return ExprError();
727 TheCall->setArg(0, PtrArgResult.get());
728
729 // First argument should be a pointer to a struct.
730 QualType PtrArgType = PtrArgResult.get()->getType();
731 if (!PtrArgType->isPointerType() ||
732 !PtrArgType->getPointeeType()->isRecordType()) {
733 S.Diag(PtrArgResult.get()->getBeginLoc(),
734 diag::err_expected_struct_pointer_argument)
735 << 1 << TheCall->getDirectCallee() << PtrArgType;
736 return ExprError();
737 }
738 QualType Pointee = PtrArgType->getPointeeType();
739 const RecordDecl *RD = Pointee->getAsRecordDecl();
740 // Try to instantiate the class template as appropriate; otherwise, access to
741 // its data() may lead to a crash.
742 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
743 diag::err_incomplete_type))
744 return ExprError();
745 // Second argument is a callable, but we can't fully validate it until we try
746 // calling it.
747 QualType FnArgType = TheCall->getArg(1)->getType();
748 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
749 !FnArgType->isBlockPointerType() &&
750 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
751 auto *BT = FnArgType->getAs<BuiltinType>();
752 switch (BT ? BT->getKind() : BuiltinType::Void) {
753 case BuiltinType::Dependent:
754 case BuiltinType::Overload:
755 case BuiltinType::BoundMember:
756 case BuiltinType::PseudoObject:
757 case BuiltinType::UnknownAny:
758 case BuiltinType::BuiltinFn:
759 // This might be a callable.
760 break;
761
762 default:
763 S.Diag(TheCall->getArg(1)->getBeginLoc(),
764 diag::err_expected_callable_argument)
765 << 2 << TheCall->getDirectCallee() << FnArgType;
766 return ExprError();
767 }
768 }
769
770 BuiltinDumpStructGenerator Generator(S, TheCall);
771
772 // Wrap parentheses around the given pointer. This is not necessary for
773 // correct code generation, but it means that when we pretty-print the call
774 // arguments in our diagnostics we will produce '(&s)->n' instead of the
775 // incorrect '&s->n'.
776 Expr *PtrArg = PtrArgResult.get();
777 PtrArg = new (S.Context)
778 ParenExpr(PtrArg->getBeginLoc(),
779 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
780 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
781 return ExprError();
782
783 return Generator.buildWrapper();
784}
785
786static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
787 if (S.checkArgCount(BuiltinCall, 2))
788 return true;
789
790 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
791 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
792 Expr *Call = BuiltinCall->getArg(0);
793 Expr *Chain = BuiltinCall->getArg(1);
794
795 if (Call->getStmtClass() != Stmt::CallExprClass) {
796 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
797 << Call->getSourceRange();
798 return true;
799 }
800
801 auto CE = cast<CallExpr>(Call);
802 if (CE->getCallee()->getType()->isBlockPointerType()) {
803 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
804 << Call->getSourceRange();
805 return true;
806 }
807
808 const Decl *TargetDecl = CE->getCalleeDecl();
809 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
810 if (FD->getBuiltinID()) {
811 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
812 << Call->getSourceRange();
813 return true;
814 }
815
816 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
817 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
818 << Call->getSourceRange();
819 return true;
820 }
821
822 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
823 if (ChainResult.isInvalid())
824 return true;
825 if (!ChainResult.get()->getType()->isPointerType()) {
826 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
827 << Chain->getSourceRange();
828 return true;
829 }
830
831 QualType ReturnTy = CE->getCallReturnType(S.Context);
832 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
833 QualType BuiltinTy = S.Context.getFunctionType(
834 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
835 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
836
837 Builtin =
838 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
839
840 BuiltinCall->setType(CE->getType());
841 BuiltinCall->setValueKind(CE->getValueKind());
842 BuiltinCall->setObjectKind(CE->getObjectKind());
843 BuiltinCall->setCallee(Builtin);
844 BuiltinCall->setArg(1, ChainResult.get());
845
846 return false;
847}
848
849namespace {
850
851class ScanfDiagnosticFormatHandler
853 // Accepts the argument index (relative to the first destination index) of the
854 // argument whose size we want.
855 using ComputeSizeFunction =
856 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
857
858 // Accepts the argument index (relative to the first destination index), the
859 // destination size, and the source size).
860 using DiagnoseFunction =
861 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
862
863 ComputeSizeFunction ComputeSizeArgument;
864 DiagnoseFunction Diagnose;
865
866public:
867 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
868 DiagnoseFunction Diagnose)
869 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
870
871 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
872 const char *StartSpecifier,
873 unsigned specifierLen) override {
874 if (!FS.consumesDataArgument())
875 return true;
876
877 unsigned NulByte = 0;
878 switch ((FS.getConversionSpecifier().getKind())) {
879 default:
880 return true;
883 NulByte = 1;
884 break;
886 break;
887 }
888
889 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
890 if (FW.getHowSpecified() !=
891 analyze_format_string::OptionalAmount::HowSpecified::Constant)
892 return true;
893
894 unsigned SourceSize = FW.getConstantAmount() + NulByte;
895
896 std::optional<llvm::APSInt> DestSizeAPS =
897 ComputeSizeArgument(FS.getArgIndex());
898 if (!DestSizeAPS)
899 return true;
900
901 unsigned DestSize = DestSizeAPS->getZExtValue();
902
903 if (DestSize < SourceSize)
904 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
905
906 return true;
907 }
908};
909
910class EstimateSizeFormatHandler
912 size_t Size;
913 /// Whether the format string contains Linux kernel's format specifier
914 /// extension.
915 bool IsKernelCompatible = true;
916
917public:
918 EstimateSizeFormatHandler(StringRef Format)
919 : Size(std::min(Format.find(0), Format.size()) +
920 1 /* null byte always written by sprintf */) {}
921
922 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
923 const char *, unsigned SpecifierLen,
924 const TargetInfo &) override {
925
926 const size_t FieldWidth = computeFieldWidth(FS);
927 const size_t Precision = computePrecision(FS);
928
929 // The actual format.
930 switch (FS.getConversionSpecifier().getKind()) {
931 // Just a char.
934 Size += std::max(FieldWidth, (size_t)1);
935 break;
936 // Just an integer.
946 Size += std::max(FieldWidth, Precision);
947 break;
948
949 // %g style conversion switches between %f or %e style dynamically.
950 // %g removes trailing zeros, and does not print decimal point if there are
951 // no digits that follow it. Thus %g can print a single digit.
952 // FIXME: If it is alternative form:
953 // For g and G conversions, trailing zeros are not removed from the result.
956 Size += 1;
957 break;
958
959 // Floating point number in the form '[+]ddd.ddd'.
962 Size += std::max(FieldWidth, 1 /* integer part */ +
963 (Precision ? 1 + Precision
964 : 0) /* period + decimal */);
965 break;
966
967 // Floating point number in the form '[-]d.ddde[+-]dd'.
970 Size +=
971 std::max(FieldWidth,
972 1 /* integer part */ +
973 (Precision ? 1 + Precision : 0) /* period + decimal */ +
974 1 /* e or E letter */ + 2 /* exponent */);
975 break;
976
977 // Floating point number in the form '[-]0xh.hhhhp±dd'.
980 Size +=
981 std::max(FieldWidth,
982 2 /* 0x */ + 1 /* integer part */ +
983 (Precision ? 1 + Precision : 0) /* period + decimal */ +
984 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
985 break;
986
987 // Just a string.
990 Size += FieldWidth;
991 break;
992
993 // Just a pointer in the form '0xddd'.
995 // Linux kernel has its own extesion for `%p` specifier.
996 // Kernel Document:
997 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
998 IsKernelCompatible = false;
999 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
1000 break;
1001
1002 // A plain percent.
1004 Size += 1;
1005 break;
1006
1007 default:
1008 break;
1009 }
1010
1011 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
1012
1013 if (FS.hasAlternativeForm()) {
1014 switch (FS.getConversionSpecifier().getKind()) {
1015 // For o conversion, it increases the precision, if and only if necessary,
1016 // to force the first digit of the result to be a zero
1017 // (if the value and precision are both 0, a single 0 is printed)
1019 // For b conversion, a nonzero result has 0b prefixed to it.
1021 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1022 // it.
1025 // Note: even when the prefix is added, if
1026 // (prefix_width <= FieldWidth - formatted_length) holds,
1027 // the prefix does not increase the format
1028 // size. e.g.(("%#3x", 0xf) is "0xf")
1029
1030 // If the result is zero, o, b, x, X adds nothing.
1031 break;
1032 // For a, A, e, E, f, F, g, and G conversions,
1033 // the result of converting a floating-point number always contains a
1034 // decimal-point
1043 Size += (Precision ? 0 : 1);
1044 break;
1045 // For other conversions, the behavior is undefined.
1046 default:
1047 break;
1048 }
1049 }
1050 assert(SpecifierLen <= Size && "no underflow");
1051 Size -= SpecifierLen;
1052 return true;
1053 }
1054
1055 size_t getSizeLowerBound() const { return Size; }
1056 bool isKernelCompatible() const { return IsKernelCompatible; }
1057
1058private:
1059 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1060 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1061 size_t FieldWidth = 0;
1063 FieldWidth = FW.getConstantAmount();
1064 return FieldWidth;
1065 }
1066
1067 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1068 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1069 size_t Precision = 0;
1070
1071 // See man 3 printf for default precision value based on the specifier.
1072 switch (FW.getHowSpecified()) {
1074 switch (FS.getConversionSpecifier().getKind()) {
1075 default:
1076 break;
1080 Precision = 1;
1081 break;
1088 Precision = 1;
1089 break;
1096 Precision = 6;
1097 break;
1099 Precision = 1;
1100 break;
1101 }
1102 break;
1104 Precision = FW.getConstantAmount();
1105 break;
1106 default:
1107 break;
1108 }
1109 return Precision;
1110 }
1111};
1112
1113} // namespace
1114
1115static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1116 StringRef &FormatStrRef, size_t &StrLen,
1117 ASTContext &Context) {
1118 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1119 Format && (Format->isOrdinary() || Format->isUTF8())) {
1120 FormatStrRef = Format->getString();
1121 const ConstantArrayType *T =
1122 Context.getAsConstantArrayType(Format->getType());
1123 assert(T && "String literal not of constant array type!");
1124 size_t TypeSize = T->getZExtSize();
1125 // In case there's a null byte somewhere.
1126 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1127 return true;
1128 }
1129 return false;
1130}
1131
1132void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1133 CallExpr *TheCall) {
1134 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1136 return;
1137
1138 bool UseDABAttr = false;
1139 const FunctionDecl *UseDecl = FD;
1140
1141 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1142 if (DABAttr) {
1143 UseDecl = DABAttr->getFunction();
1144 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1145 UseDABAttr = true;
1146 }
1147
1148 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1149
1150 if (!BuiltinID)
1151 return;
1152
1153 const TargetInfo &TI = getASTContext().getTargetInfo();
1154 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1155
1156 auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1157 // If we refer to a diagnose_as_builtin attribute, we need to change the
1158 // argument index to refer to the arguments of the called function. Unless
1159 // the index is out of bounds, which presumably means it's a variadic
1160 // function.
1161 if (!UseDABAttr)
1162 return Index;
1163 unsigned DABIndices = DABAttr->argIndices_size();
1164 unsigned NewIndex = Index < DABIndices
1165 ? DABAttr->argIndices_begin()[Index]
1166 : Index - DABIndices + FD->getNumParams();
1167 if (NewIndex >= TheCall->getNumArgs())
1168 return std::nullopt;
1169 return NewIndex;
1170 };
1171
1172 auto ComputeExplicitObjectSizeArgument =
1173 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1174 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1175 if (!IndexOptional)
1176 return std::nullopt;
1177 unsigned NewIndex = *IndexOptional;
1179 Expr *SizeArg = TheCall->getArg(NewIndex);
1180 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
1181 return std::nullopt;
1182 llvm::APSInt Integer = Result.Val.getInt();
1183 Integer.setIsUnsigned(true);
1184 return Integer;
1185 };
1186
1187 auto ComputeSizeArgument =
1188 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1189 // If the parameter has a pass_object_size attribute, then we should use its
1190 // (potentially) more strict checking mode. Otherwise, conservatively assume
1191 // type 0.
1192 int BOSType = 0;
1193 // This check can fail for variadic functions.
1194 if (Index < FD->getNumParams()) {
1195 if (const auto *POS =
1196 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1197 BOSType = POS->getType();
1198 }
1199
1200 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1201 if (!IndexOptional)
1202 return std::nullopt;
1203 unsigned NewIndex = *IndexOptional;
1204
1205 if (NewIndex >= TheCall->getNumArgs())
1206 return std::nullopt;
1207
1208 const Expr *ObjArg = TheCall->getArg(NewIndex);
1210 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
1211 return std::nullopt;
1212
1213 // Get the object size in the target's size_t width.
1214 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
1215 };
1216
1217 auto ComputeStrLenArgument =
1218 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1219 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1220 if (!IndexOptional)
1221 return std::nullopt;
1222 unsigned NewIndex = *IndexOptional;
1223
1224 const Expr *ObjArg = TheCall->getArg(NewIndex);
1226 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
1227 return std::nullopt;
1228 // Add 1 for null byte.
1229 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
1230 };
1231
1232 std::optional<llvm::APSInt> SourceSize;
1233 std::optional<llvm::APSInt> DestinationSize;
1234 unsigned DiagID = 0;
1235 bool IsChkVariant = false;
1236
1237 auto GetFunctionName = [&]() {
1238 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
1239 // Skim off the details of whichever builtin was called to produce a better
1240 // diagnostic, as it's unlikely that the user wrote the __builtin
1241 // explicitly.
1242 if (IsChkVariant) {
1243 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
1244 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
1245 } else {
1246 FunctionName.consume_front("__builtin_");
1247 }
1248 return FunctionName;
1249 };
1250
1251 switch (BuiltinID) {
1252 default:
1253 return;
1254 case Builtin::BI__builtin_strcpy:
1255 case Builtin::BIstrcpy: {
1256 DiagID = diag::warn_fortify_strlen_overflow;
1257 SourceSize = ComputeStrLenArgument(1);
1258 DestinationSize = ComputeSizeArgument(0);
1259 break;
1260 }
1261
1262 case Builtin::BI__builtin___strcpy_chk: {
1263 DiagID = diag::warn_fortify_strlen_overflow;
1264 SourceSize = ComputeStrLenArgument(1);
1265 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1266 IsChkVariant = true;
1267 break;
1268 }
1269
1270 case Builtin::BIscanf:
1271 case Builtin::BIfscanf:
1272 case Builtin::BIsscanf: {
1273 unsigned FormatIndex = 1;
1274 unsigned DataIndex = 2;
1275 if (BuiltinID == Builtin::BIscanf) {
1276 FormatIndex = 0;
1277 DataIndex = 1;
1278 }
1279
1280 const auto *FormatExpr =
1281 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1282
1283 StringRef FormatStrRef;
1284 size_t StrLen;
1285 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1286 return;
1287
1288 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1289 unsigned SourceSize) {
1290 DiagID = diag::warn_fortify_scanf_overflow;
1291 unsigned Index = ArgIndex + DataIndex;
1292 StringRef FunctionName = GetFunctionName();
1293 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1294 PDiag(DiagID) << FunctionName << (Index + 1)
1295 << DestSize << SourceSize);
1296 };
1297
1298 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1299 return ComputeSizeArgument(Index + DataIndex);
1300 };
1301 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1302 const char *FormatBytes = FormatStrRef.data();
1304 FormatBytes + StrLen, getLangOpts(),
1306
1307 // Unlike the other cases, in this one we have already issued the diagnostic
1308 // here, so no need to continue (because unlike the other cases, here the
1309 // diagnostic refers to the argument number).
1310 return;
1311 }
1312
1313 case Builtin::BIsprintf:
1314 case Builtin::BI__builtin___sprintf_chk: {
1315 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1316 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1317
1318 StringRef FormatStrRef;
1319 size_t StrLen;
1320 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1321 EstimateSizeFormatHandler H(FormatStrRef);
1322 const char *FormatBytes = FormatStrRef.data();
1324 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1325 Context.getTargetInfo(), false)) {
1326 DiagID = H.isKernelCompatible()
1327 ? diag::warn_format_overflow
1328 : diag::warn_format_overflow_non_kprintf;
1329 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1330 .extOrTrunc(SizeTypeWidth);
1331 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1332 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1333 IsChkVariant = true;
1334 } else {
1335 DestinationSize = ComputeSizeArgument(0);
1336 }
1337 break;
1338 }
1339 }
1340 return;
1341 }
1342 case Builtin::BI__builtin___memcpy_chk:
1343 case Builtin::BI__builtin___memmove_chk:
1344 case Builtin::BI__builtin___memset_chk:
1345 case Builtin::BI__builtin___strlcat_chk:
1346 case Builtin::BI__builtin___strlcpy_chk:
1347 case Builtin::BI__builtin___strncat_chk:
1348 case Builtin::BI__builtin___strncpy_chk:
1349 case Builtin::BI__builtin___stpncpy_chk:
1350 case Builtin::BI__builtin___memccpy_chk:
1351 case Builtin::BI__builtin___mempcpy_chk: {
1352 DiagID = diag::warn_builtin_chk_overflow;
1353 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1354 DestinationSize =
1355 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1356 IsChkVariant = true;
1357 break;
1358 }
1359
1360 case Builtin::BI__builtin___snprintf_chk:
1361 case Builtin::BI__builtin___vsnprintf_chk: {
1362 DiagID = diag::warn_builtin_chk_overflow;
1363 SourceSize = ComputeExplicitObjectSizeArgument(1);
1364 DestinationSize = ComputeExplicitObjectSizeArgument(3);
1365 IsChkVariant = true;
1366 break;
1367 }
1368
1369 case Builtin::BIstrncat:
1370 case Builtin::BI__builtin_strncat:
1371 case Builtin::BIstrncpy:
1372 case Builtin::BI__builtin_strncpy:
1373 case Builtin::BIstpncpy:
1374 case Builtin::BI__builtin_stpncpy: {
1375 // Whether these functions overflow depends on the runtime strlen of the
1376 // string, not just the buffer size, so emitting the "always overflow"
1377 // diagnostic isn't quite right. We should still diagnose passing a buffer
1378 // size larger than the destination buffer though; this is a runtime abort
1379 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1380 DiagID = diag::warn_fortify_source_size_mismatch;
1381 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1382 DestinationSize = ComputeSizeArgument(0);
1383 break;
1384 }
1385
1386 case Builtin::BImemcpy:
1387 case Builtin::BI__builtin_memcpy:
1388 case Builtin::BImemmove:
1389 case Builtin::BI__builtin_memmove:
1390 case Builtin::BImemset:
1391 case Builtin::BI__builtin_memset:
1392 case Builtin::BImempcpy:
1393 case Builtin::BI__builtin_mempcpy: {
1394 DiagID = diag::warn_fortify_source_overflow;
1395 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1396 DestinationSize = ComputeSizeArgument(0);
1397 break;
1398 }
1399 case Builtin::BIsnprintf:
1400 case Builtin::BI__builtin_snprintf:
1401 case Builtin::BIvsnprintf:
1402 case Builtin::BI__builtin_vsnprintf: {
1403 DiagID = diag::warn_fortify_source_size_mismatch;
1404 SourceSize = ComputeExplicitObjectSizeArgument(1);
1405 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1406 StringRef FormatStrRef;
1407 size_t StrLen;
1408 if (SourceSize &&
1409 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1410 EstimateSizeFormatHandler H(FormatStrRef);
1411 const char *FormatBytes = FormatStrRef.data();
1413 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1414 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1415 llvm::APSInt FormatSize =
1416 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1417 .extOrTrunc(SizeTypeWidth);
1418 if (FormatSize > *SourceSize && *SourceSize != 0) {
1419 unsigned TruncationDiagID =
1420 H.isKernelCompatible() ? diag::warn_format_truncation
1421 : diag::warn_format_truncation_non_kprintf;
1422 SmallString<16> SpecifiedSizeStr;
1423 SmallString<16> FormatSizeStr;
1424 SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1425 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1426 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1427 PDiag(TruncationDiagID)
1428 << GetFunctionName() << SpecifiedSizeStr
1429 << FormatSizeStr);
1430 }
1431 }
1432 }
1433 DestinationSize = ComputeSizeArgument(0);
1434 }
1435 }
1436
1437 if (!SourceSize || !DestinationSize ||
1438 llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1439 return;
1440
1441 StringRef FunctionName = GetFunctionName();
1442
1443 SmallString<16> DestinationStr;
1444 SmallString<16> SourceStr;
1445 DestinationSize->toString(DestinationStr, /*Radix=*/10);
1446 SourceSize->toString(SourceStr, /*Radix=*/10);
1447 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1448 PDiag(DiagID)
1449 << FunctionName << DestinationStr << SourceStr);
1450}
1451
1452static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1453 Scope::ScopeFlags NeededScopeFlags,
1454 unsigned DiagID) {
1455 // Scopes aren't available during instantiation. Fortunately, builtin
1456 // functions cannot be template args so they cannot be formed through template
1457 // instantiation. Therefore checking once during the parse is sufficient.
1458 if (SemaRef.inTemplateInstantiation())
1459 return false;
1460
1461 Scope *S = SemaRef.getCurScope();
1462 while (S && !S->isSEHExceptScope())
1463 S = S->getParent();
1464 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1465 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1466 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1467 << DRE->getDecl()->getIdentifier();
1468 return true;
1469 }
1470
1471 return false;
1472}
1473
1474// In OpenCL, __builtin_alloca_* should return a pointer to address space
1475// that corresponds to the stack address space i.e private address space.
1476static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1477 QualType RT = TheCall->getType();
1478 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1479 "__builtin_alloca has invalid address space");
1480
1481 RT = RT->getPointeeType();
1483 TheCall->setType(S.Context.getPointerType(RT));
1484}
1485
1486namespace {
1487enum PointerAuthOpKind {
1488 PAO_Strip,
1489 PAO_Sign,
1490 PAO_Auth,
1491 PAO_SignGeneric,
1492 PAO_Discriminator,
1493 PAO_BlendPointer,
1494 PAO_BlendInteger
1495};
1496}
1497
1499 if (getLangOpts().PointerAuthIntrinsics)
1500 return false;
1501
1502 Diag(Loc, diag::err_ptrauth_disabled) << Range;
1503 return true;
1504}
1505
1508}
1509
1510static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1511 // Convert it to type 'int'.
1512 if (convertArgumentToType(S, Arg, S.Context.IntTy))
1513 return true;
1514
1515 // Value-dependent expressions are okay; wait for template instantiation.
1516 if (Arg->isValueDependent())
1517 return false;
1518
1519 unsigned KeyValue;
1520 return S.checkConstantPointerAuthKey(Arg, KeyValue);
1521}
1522
1524 // Attempt to constant-evaluate the expression.
1525 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
1526 if (!KeyValue) {
1527 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
1528 << 0 << Arg->getSourceRange();
1529 return true;
1530 }
1531
1532 // Ask the target to validate the key parameter.
1533 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
1535 {
1536 llvm::raw_svector_ostream Str(Value);
1537 Str << *KeyValue;
1538 }
1539
1540 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
1541 << Value << Arg->getSourceRange();
1542 return true;
1543 }
1544
1545 Result = KeyValue->getZExtValue();
1546 return false;
1547}
1548
1549static std::pair<const ValueDecl *, CharUnits>
1551 // Must evaluate as a pointer.
1553 if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())
1554 return {nullptr, CharUnits()};
1555
1556 const auto *BaseDecl =
1557 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1558 if (!BaseDecl)
1559 return {nullptr, CharUnits()};
1560
1561 return {BaseDecl, Result.Val.getLValueOffset()};
1562}
1563
1564static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1565 bool RequireConstant = false) {
1566 if (Arg->hasPlaceholderType()) {
1568 if (R.isInvalid())
1569 return true;
1570 Arg = R.get();
1571 }
1572
1573 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1574 return OpKind != PAO_BlendInteger;
1575 };
1576 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1577 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1578 OpKind == PAO_SignGeneric;
1579 };
1580
1581 // Require the value to have the right range of type.
1582 QualType ExpectedTy;
1583 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1584 ExpectedTy = Arg->getType().getUnqualifiedType();
1585 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1586 ExpectedTy = S.Context.VoidPtrTy;
1587 } else if (AllowsInteger(OpKind) &&
1589 ExpectedTy = S.Context.getUIntPtrType();
1590
1591 } else {
1592 // Diagnose the failures.
1593 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
1594 << unsigned(OpKind == PAO_Discriminator ? 1
1595 : OpKind == PAO_BlendPointer ? 2
1596 : OpKind == PAO_BlendInteger ? 3
1597 : 0)
1598 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1599 << Arg->getType() << Arg->getSourceRange();
1600 return true;
1601 }
1602
1603 // Convert to that type. This should just be an lvalue-to-rvalue
1604 // conversion.
1605 if (convertArgumentToType(S, Arg, ExpectedTy))
1606 return true;
1607
1608 if (!RequireConstant) {
1609 // Warn about null pointers for non-generic sign and auth operations.
1610 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1612 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
1613 ? diag::warn_ptrauth_sign_null_pointer
1614 : diag::warn_ptrauth_auth_null_pointer)
1615 << Arg->getSourceRange();
1616 }
1617
1618 return false;
1619 }
1620
1621 // Perform special checking on the arguments to ptrauth_sign_constant.
1622
1623 // The main argument.
1624 if (OpKind == PAO_Sign) {
1625 // Require the value we're signing to have a special form.
1626 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg);
1627 bool Invalid;
1628
1629 // Must be rooted in a declaration reference.
1630 if (!BaseDecl)
1631 Invalid = true;
1632
1633 // If it's a function declaration, we can't have an offset.
1634 else if (isa<FunctionDecl>(BaseDecl))
1635 Invalid = !Offset.isZero();
1636
1637 // Otherwise we're fine.
1638 else
1639 Invalid = false;
1640
1641 if (Invalid)
1642 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
1643 return Invalid;
1644 }
1645
1646 // The discriminator argument.
1647 assert(OpKind == PAO_Discriminator);
1648
1649 // Must be a pointer or integer or blend thereof.
1650 Expr *Pointer = nullptr;
1651 Expr *Integer = nullptr;
1652 if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {
1653 if (Call->getBuiltinCallee() ==
1654 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1655 Pointer = Call->getArg(0);
1656 Integer = Call->getArg(1);
1657 }
1658 }
1659 if (!Pointer && !Integer) {
1660 if (Arg->getType()->isPointerType())
1661 Pointer = Arg;
1662 else
1663 Integer = Arg;
1664 }
1665
1666 // Check the pointer.
1667 bool Invalid = false;
1668 if (Pointer) {
1669 assert(Pointer->getType()->isPointerType());
1670
1671 // TODO: if we're initializing a global, check that the address is
1672 // somehow related to what we're initializing. This probably will
1673 // never really be feasible and we'll have to catch it at link-time.
1674 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer);
1675 if (!BaseDecl || !isa<VarDecl>(BaseDecl))
1676 Invalid = true;
1677 }
1678
1679 // Check the integer.
1680 if (Integer) {
1681 assert(Integer->getType()->isIntegerType());
1682 if (!Integer->isEvaluatable(S.Context))
1683 Invalid = true;
1684 }
1685
1686 if (Invalid)
1687 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
1688 return Invalid;
1689}
1690
1692 if (S.checkArgCount(Call, 2))
1693 return ExprError();
1695 return ExprError();
1696 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
1697 checkPointerAuthKey(S, Call->getArgs()[1]))
1698 return ExprError();
1699
1700 Call->setType(Call->getArgs()[0]->getType());
1701 return Call;
1702}
1703
1705 if (S.checkArgCount(Call, 2))
1706 return ExprError();
1708 return ExprError();
1709 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
1710 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
1711 return ExprError();
1712
1713 Call->setType(S.Context.getUIntPtrType());
1714 return Call;
1715}
1716
1718 if (S.checkArgCount(Call, 2))
1719 return ExprError();
1721 return ExprError();
1722 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
1723 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
1724 return ExprError();
1725
1726 Call->setType(S.Context.getUIntPtrType());
1727 return Call;
1728}
1729
1731 PointerAuthOpKind OpKind,
1732 bool RequireConstant) {
1733 if (S.checkArgCount(Call, 3))
1734 return ExprError();
1736 return ExprError();
1737 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||
1738 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1739 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,
1740 RequireConstant))
1741 return ExprError();
1742
1743 Call->setType(Call->getArgs()[0]->getType());
1744 return Call;
1745}
1746
1748 if (S.checkArgCount(Call, 5))
1749 return ExprError();
1751 return ExprError();
1752 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1753 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1754 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1755 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1756 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
1757 return ExprError();
1758
1759 Call->setType(Call->getArgs()[0]->getType());
1760 return Call;
1761}
1762
1765 return ExprError();
1766
1767 // We've already performed normal call type-checking.
1768 const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();
1769
1770 // Operand must be an ordinary or UTF-8 string literal.
1771 const auto *Literal = dyn_cast<StringLiteral>(Arg);
1772 if (!Literal || Literal->getCharByteWidth() != 1) {
1773 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)
1774 << (Literal ? 1 : 0) << Arg->getSourceRange();
1775 return ExprError();
1776 }
1777
1778 return Call;
1779}
1780
1782 if (S.checkArgCount(TheCall, 1))
1783 return ExprError();
1784
1785 // Compute __builtin_launder's parameter type from the argument.
1786 // The parameter type is:
1787 // * The type of the argument if it's not an array or function type,
1788 // Otherwise,
1789 // * The decayed argument type.
1790 QualType ParamTy = [&]() {
1791 QualType ArgTy = TheCall->getArg(0)->getType();
1792 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1793 return S.Context.getPointerType(Ty->getElementType());
1794 if (ArgTy->isFunctionType()) {
1795 return S.Context.getPointerType(ArgTy);
1796 }
1797 return ArgTy;
1798 }();
1799
1800 TheCall->setType(ParamTy);
1801
1802 auto DiagSelect = [&]() -> std::optional<unsigned> {
1803 if (!ParamTy->isPointerType())
1804 return 0;
1805 if (ParamTy->isFunctionPointerType())
1806 return 1;
1807 if (ParamTy->isVoidPointerType())
1808 return 2;
1809 return std::optional<unsigned>{};
1810 }();
1811 if (DiagSelect) {
1812 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1813 << *DiagSelect << TheCall->getSourceRange();
1814 return ExprError();
1815 }
1816
1817 // We either have an incomplete class type, or we have a class template
1818 // whose instantiation has not been forced. Example:
1819 //
1820 // template <class T> struct Foo { T value; };
1821 // Foo<int> *p = nullptr;
1822 // auto *d = __builtin_launder(p);
1823 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1824 diag::err_incomplete_type))
1825 return ExprError();
1826
1827 assert(ParamTy->getPointeeType()->isObjectType() &&
1828 "Unhandled non-object pointer case");
1829
1830 InitializedEntity Entity =
1832 ExprResult Arg =
1833 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1834 if (Arg.isInvalid())
1835 return ExprError();
1836 TheCall->setArg(0, Arg.get());
1837
1838 return TheCall;
1839}
1840
1842 if (S.checkArgCount(TheCall, 1))
1843 return ExprError();
1844
1846 if (Arg.isInvalid())
1847 return ExprError();
1848 QualType ParamTy = Arg.get()->getType();
1849 TheCall->setArg(0, Arg.get());
1850 TheCall->setType(S.Context.BoolTy);
1851
1852 // Only accept pointers to objects as arguments, which should have object
1853 // pointer or void pointer types.
1854 if (const auto *PT = ParamTy->getAs<PointerType>()) {
1855 // LWG4138: Function pointer types not allowed
1856 if (PT->getPointeeType()->isFunctionType()) {
1857 S.Diag(TheCall->getArg(0)->getExprLoc(),
1858 diag::err_builtin_is_within_lifetime_invalid_arg)
1859 << 1;
1860 return ExprError();
1861 }
1862 // Disallow VLAs too since those shouldn't be able to
1863 // be a template parameter for `std::is_within_lifetime`
1864 if (PT->getPointeeType()->isVariableArrayType()) {
1865 S.Diag(TheCall->getArg(0)->getExprLoc(), diag::err_vla_unsupported)
1866 << 1 << "__builtin_is_within_lifetime";
1867 return ExprError();
1868 }
1869 } else {
1870 S.Diag(TheCall->getArg(0)->getExprLoc(),
1871 diag::err_builtin_is_within_lifetime_invalid_arg)
1872 << 0;
1873 return ExprError();
1874 }
1875
1876 return TheCall;
1877}
1878
1879// Emit an error and return true if the current object format type is in the
1880// list of unsupported types.
1882 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1883 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
1884 llvm::Triple::ObjectFormatType CurObjFormat =
1885 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
1886 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
1887 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1888 << TheCall->getSourceRange();
1889 return true;
1890 }
1891 return false;
1892}
1893
1894// Emit an error and return true if the current architecture is not in the list
1895// of supported architectures.
1896static bool
1898 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1899 llvm::Triple::ArchType CurArch =
1900 S.getASTContext().getTargetInfo().getTriple().getArch();
1901 if (llvm::is_contained(SupportedArchs, CurArch))
1902 return false;
1903 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1904 << TheCall->getSourceRange();
1905 return true;
1906}
1907
1908static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1909 SourceLocation CallSiteLoc);
1910
1911bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1912 CallExpr *TheCall) {
1913 switch (TI.getTriple().getArch()) {
1914 default:
1915 // Some builtins don't require additional checking, so just consider these
1916 // acceptable.
1917 return false;
1918 case llvm::Triple::arm:
1919 case llvm::Triple::armeb:
1920 case llvm::Triple::thumb:
1921 case llvm::Triple::thumbeb:
1922 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1923 case llvm::Triple::aarch64:
1924 case llvm::Triple::aarch64_32:
1925 case llvm::Triple::aarch64_be:
1926 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1927 case llvm::Triple::bpfeb:
1928 case llvm::Triple::bpfel:
1929 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1930 case llvm::Triple::hexagon:
1931 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1932 case llvm::Triple::mips:
1933 case llvm::Triple::mipsel:
1934 case llvm::Triple::mips64:
1935 case llvm::Triple::mips64el:
1936 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1937 case llvm::Triple::systemz:
1938 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1939 case llvm::Triple::x86:
1940 case llvm::Triple::x86_64:
1941 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
1942 case llvm::Triple::ppc:
1943 case llvm::Triple::ppcle:
1944 case llvm::Triple::ppc64:
1945 case llvm::Triple::ppc64le:
1946 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1947 case llvm::Triple::amdgcn:
1948 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1949 case llvm::Triple::riscv32:
1950 case llvm::Triple::riscv64:
1951 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
1952 case llvm::Triple::loongarch32:
1953 case llvm::Triple::loongarch64:
1954 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
1955 TheCall);
1956 case llvm::Triple::wasm32:
1957 case llvm::Triple::wasm64:
1958 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
1959 case llvm::Triple::nvptx:
1960 case llvm::Triple::nvptx64:
1961 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
1962 }
1963}
1964
1965// Check if \p Ty is a valid type for the elementwise math builtins. If it is
1966// not a valid type, emit an error message and return true. Otherwise return
1967// false.
1969 QualType ArgTy, int ArgIndex) {
1970 if (!ArgTy->getAs<VectorType>() &&
1972 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
1973 << ArgIndex << /* vector, integer or float ty*/ 0 << ArgTy;
1974 }
1975
1976 return false;
1977}
1978
1980 QualType ArgTy, int ArgIndex) {
1981 QualType EltTy = ArgTy;
1982 if (auto *VecTy = EltTy->getAs<VectorType>())
1983 EltTy = VecTy->getElementType();
1984
1985 if (!EltTy->isRealFloatingType()) {
1986 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
1987 << ArgIndex << /* vector or float ty*/ 5 << ArgTy;
1988 }
1989
1990 return false;
1991}
1992
1993/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
1994/// This checks that the target supports the builtin and that the string
1995/// argument is constant and valid.
1996static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
1997 const TargetInfo *AuxTI, unsigned BuiltinID) {
1998 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
1999 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2000 "Expecting __builtin_cpu_...");
2001
2002 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2003 const TargetInfo *TheTI = &TI;
2004 auto SupportsBI = [=](const TargetInfo *TInfo) {
2005 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2006 (!IsCPUSupports && TInfo->supportsCpuIs()));
2007 };
2008 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2009 TheTI = AuxTI;
2010
2011 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2012 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2013 return S.Diag(TheCall->getBeginLoc(),
2014 TI.getTriple().isOSAIX()
2015 ? diag::err_builtin_aix_os_unsupported
2016 : diag::err_builtin_target_unsupported)
2017 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2018
2019 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2020 // Check if the argument is a string literal.
2021 if (!isa<StringLiteral>(Arg))
2022 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2023 << Arg->getSourceRange();
2024
2025 // Check the contents of the string.
2026 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2027 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2028 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2029 << Arg->getSourceRange();
2030 return false;
2031 }
2032 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2033 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2034 << Arg->getSourceRange();
2035 return false;
2036}
2037
2038/// Checks that __builtin_popcountg was called with a single argument, which is
2039/// an unsigned integer.
2040static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2041 if (S.checkArgCount(TheCall, 1))
2042 return true;
2043
2044 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2045 if (ArgRes.isInvalid())
2046 return true;
2047
2048 Expr *Arg = ArgRes.get();
2049 TheCall->setArg(0, Arg);
2050
2051 QualType ArgTy = Arg->getType();
2052
2053 if (!ArgTy->isUnsignedIntegerType()) {
2054 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2055 << 1 << /*unsigned integer ty*/ 7 << ArgTy;
2056 return true;
2057 }
2058 return false;
2059}
2060
2061/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2062/// an unsigned integer, and an optional second argument, which is promoted to
2063/// an 'int'.
2064static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2065 if (S.checkArgCountRange(TheCall, 1, 2))
2066 return true;
2067
2068 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2069 if (Arg0Res.isInvalid())
2070 return true;
2071
2072 Expr *Arg0 = Arg0Res.get();
2073 TheCall->setArg(0, Arg0);
2074
2075 QualType Arg0Ty = Arg0->getType();
2076
2077 if (!Arg0Ty->isUnsignedIntegerType()) {
2078 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2079 << 1 << /*unsigned integer ty*/ 7 << Arg0Ty;
2080 return true;
2081 }
2082
2083 if (TheCall->getNumArgs() > 1) {
2084 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2085 if (Arg1Res.isInvalid())
2086 return true;
2087
2088 Expr *Arg1 = Arg1Res.get();
2089 TheCall->setArg(1, Arg1);
2090
2091 QualType Arg1Ty = Arg1->getType();
2092
2093 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2094 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2095 << 2 << /*'int' ty*/ 8 << Arg1Ty;
2096 return true;
2097 }
2098 }
2099
2100 return false;
2101}
2102
2104Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2105 CallExpr *TheCall) {
2106 ExprResult TheCallResult(TheCall);
2107
2108 // Find out if any arguments are required to be integer constant expressions.
2109 unsigned ICEArguments = 0;
2111 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
2112 if (Error != ASTContext::GE_None)
2113 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2114
2115 // If any arguments are required to be ICE's, check and diagnose.
2116 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2117 // Skip arguments not required to be ICE's.
2118 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2119
2120 llvm::APSInt Result;
2121 // If we don't have enough arguments, continue so we can issue better
2122 // diagnostic in checkArgCount(...)
2123 if (ArgNo < TheCall->getNumArgs() &&
2124 BuiltinConstantArg(TheCall, ArgNo, Result))
2125 return true;
2126 ICEArguments &= ~(1 << ArgNo);
2127 }
2128
2129 FPOptions FPO;
2130 switch (BuiltinID) {
2131 case Builtin::BI__builtin_cpu_supports:
2132 case Builtin::BI__builtin_cpu_is:
2133 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
2134 Context.getAuxTargetInfo(), BuiltinID))
2135 return ExprError();
2136 break;
2137 case Builtin::BI__builtin_cpu_init:
2139 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2140 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2141 return ExprError();
2142 }
2143 break;
2144 case Builtin::BI__builtin___CFStringMakeConstantString:
2145 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2146 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2148 *this, BuiltinID, TheCall,
2149 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2150 return ExprError();
2151 assert(TheCall->getNumArgs() == 1 &&
2152 "Wrong # arguments to builtin CFStringMakeConstantString");
2153 if (ObjC().CheckObjCString(TheCall->getArg(0)))
2154 return ExprError();
2155 break;
2156 case Builtin::BI__builtin_ms_va_start:
2157 case Builtin::BI__builtin_stdarg_start:
2158 case Builtin::BI__builtin_va_start:
2159 if (BuiltinVAStart(BuiltinID, TheCall))
2160 return ExprError();
2161 break;
2162 case Builtin::BI__va_start: {
2163 switch (Context.getTargetInfo().getTriple().getArch()) {
2164 case llvm::Triple::aarch64:
2165 case llvm::Triple::arm:
2166 case llvm::Triple::thumb:
2167 if (BuiltinVAStartARMMicrosoft(TheCall))
2168 return ExprError();
2169 break;
2170 default:
2171 if (BuiltinVAStart(BuiltinID, TheCall))
2172 return ExprError();
2173 break;
2174 }
2175 break;
2176 }
2177
2178 // The acquire, release, and no fence variants are ARM and AArch64 only.
2179 case Builtin::BI_interlockedbittestandset_acq:
2180 case Builtin::BI_interlockedbittestandset_rel:
2181 case Builtin::BI_interlockedbittestandset_nf:
2182 case Builtin::BI_interlockedbittestandreset_acq:
2183 case Builtin::BI_interlockedbittestandreset_rel:
2184 case Builtin::BI_interlockedbittestandreset_nf:
2186 *this, TheCall,
2187 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2188 return ExprError();
2189 break;
2190
2191 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2192 case Builtin::BI_bittest64:
2193 case Builtin::BI_bittestandcomplement64:
2194 case Builtin::BI_bittestandreset64:
2195 case Builtin::BI_bittestandset64:
2196 case Builtin::BI_interlockedbittestandreset64:
2197 case Builtin::BI_interlockedbittestandset64:
2199 *this, TheCall,
2200 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
2201 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2202 return ExprError();
2203 break;
2204
2205 case Builtin::BI__builtin_set_flt_rounds:
2207 *this, TheCall,
2208 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
2209 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn,
2210 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
2211 llvm::Triple::ppc64le}))
2212 return ExprError();
2213 break;
2214
2215 case Builtin::BI__builtin_isgreater:
2216 case Builtin::BI__builtin_isgreaterequal:
2217 case Builtin::BI__builtin_isless:
2218 case Builtin::BI__builtin_islessequal:
2219 case Builtin::BI__builtin_islessgreater:
2220 case Builtin::BI__builtin_isunordered:
2221 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
2222 return ExprError();
2223 break;
2224 case Builtin::BI__builtin_fpclassify:
2225 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
2226 return ExprError();
2227 break;
2228 case Builtin::BI__builtin_isfpclass:
2229 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
2230 return ExprError();
2231 break;
2232 case Builtin::BI__builtin_isfinite:
2233 case Builtin::BI__builtin_isinf:
2234 case Builtin::BI__builtin_isinf_sign:
2235 case Builtin::BI__builtin_isnan:
2236 case Builtin::BI__builtin_issignaling:
2237 case Builtin::BI__builtin_isnormal:
2238 case Builtin::BI__builtin_issubnormal:
2239 case Builtin::BI__builtin_iszero:
2240 case Builtin::BI__builtin_signbit:
2241 case Builtin::BI__builtin_signbitf:
2242 case Builtin::BI__builtin_signbitl:
2243 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
2244 return ExprError();
2245 break;
2246 case Builtin::BI__builtin_shufflevector:
2247 return BuiltinShuffleVector(TheCall);
2248 // TheCall will be freed by the smart pointer here, but that's fine, since
2249 // BuiltinShuffleVector guts it, but then doesn't release it.
2250 case Builtin::BI__builtin_prefetch:
2251 if (BuiltinPrefetch(TheCall))
2252 return ExprError();
2253 break;
2254 case Builtin::BI__builtin_alloca_with_align:
2255 case Builtin::BI__builtin_alloca_with_align_uninitialized:
2256 if (BuiltinAllocaWithAlign(TheCall))
2257 return ExprError();
2258 [[fallthrough]];
2259 case Builtin::BI__builtin_alloca:
2260 case Builtin::BI__builtin_alloca_uninitialized:
2261 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
2262 << TheCall->getDirectCallee();
2263 if (getLangOpts().OpenCL) {
2264 builtinAllocaAddrSpace(*this, TheCall);
2265 }
2266 break;
2267 case Builtin::BI__arithmetic_fence:
2268 if (BuiltinArithmeticFence(TheCall))
2269 return ExprError();
2270 break;
2271 case Builtin::BI__assume:
2272 case Builtin::BI__builtin_assume:
2273 if (BuiltinAssume(TheCall))
2274 return ExprError();
2275 break;
2276 case Builtin::BI__builtin_assume_aligned:
2277 if (BuiltinAssumeAligned(TheCall))
2278 return ExprError();
2279 break;
2280 case Builtin::BI__builtin_dynamic_object_size:
2281 case Builtin::BI__builtin_object_size:
2282 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
2283 return ExprError();
2284 break;
2285 case Builtin::BI__builtin_longjmp:
2286 if (BuiltinLongjmp(TheCall))
2287 return ExprError();
2288 break;
2289 case Builtin::BI__builtin_setjmp:
2290 if (BuiltinSetjmp(TheCall))
2291 return ExprError();
2292 break;
2293 case Builtin::BI__builtin_classify_type:
2294 if (checkArgCount(TheCall, 1))
2295 return true;
2296 TheCall->setType(Context.IntTy);
2297 break;
2298 case Builtin::BI__builtin_complex:
2299 if (BuiltinComplex(TheCall))
2300 return ExprError();
2301 break;
2302 case Builtin::BI__builtin_constant_p: {
2303 if (checkArgCount(TheCall, 1))
2304 return true;
2306 if (Arg.isInvalid()) return true;
2307 TheCall->setArg(0, Arg.get());
2308 TheCall->setType(Context.IntTy);
2309 break;
2310 }
2311 case Builtin::BI__builtin_launder:
2312 return BuiltinLaunder(*this, TheCall);
2313 case Builtin::BI__builtin_is_within_lifetime:
2314 return BuiltinIsWithinLifetime(*this, TheCall);
2315 case Builtin::BI__sync_fetch_and_add:
2316 case Builtin::BI__sync_fetch_and_add_1:
2317 case Builtin::BI__sync_fetch_and_add_2:
2318 case Builtin::BI__sync_fetch_and_add_4:
2319 case Builtin::BI__sync_fetch_and_add_8:
2320 case Builtin::BI__sync_fetch_and_add_16:
2321 case Builtin::BI__sync_fetch_and_sub:
2322 case Builtin::BI__sync_fetch_and_sub_1:
2323 case Builtin::BI__sync_fetch_and_sub_2:
2324 case Builtin::BI__sync_fetch_and_sub_4:
2325 case Builtin::BI__sync_fetch_and_sub_8:
2326 case Builtin::BI__sync_fetch_and_sub_16:
2327 case Builtin::BI__sync_fetch_and_or:
2328 case Builtin::BI__sync_fetch_and_or_1:
2329 case Builtin::BI__sync_fetch_and_or_2:
2330 case Builtin::BI__sync_fetch_and_or_4:
2331 case Builtin::BI__sync_fetch_and_or_8:
2332 case Builtin::BI__sync_fetch_and_or_16:
2333 case Builtin::BI__sync_fetch_and_and:
2334 case Builtin::BI__sync_fetch_and_and_1:
2335 case Builtin::BI__sync_fetch_and_and_2:
2336 case Builtin::BI__sync_fetch_and_and_4:
2337 case Builtin::BI__sync_fetch_and_and_8:
2338 case Builtin::BI__sync_fetch_and_and_16:
2339 case Builtin::BI__sync_fetch_and_xor:
2340 case Builtin::BI__sync_fetch_and_xor_1:
2341 case Builtin::BI__sync_fetch_and_xor_2:
2342 case Builtin::BI__sync_fetch_and_xor_4:
2343 case Builtin::BI__sync_fetch_and_xor_8:
2344 case Builtin::BI__sync_fetch_and_xor_16:
2345 case Builtin::BI__sync_fetch_and_nand:
2346 case Builtin::BI__sync_fetch_and_nand_1:
2347 case Builtin::BI__sync_fetch_and_nand_2:
2348 case Builtin::BI__sync_fetch_and_nand_4:
2349 case Builtin::BI__sync_fetch_and_nand_8:
2350 case Builtin::BI__sync_fetch_and_nand_16:
2351 case Builtin::BI__sync_add_and_fetch:
2352 case Builtin::BI__sync_add_and_fetch_1:
2353 case Builtin::BI__sync_add_and_fetch_2:
2354 case Builtin::BI__sync_add_and_fetch_4:
2355 case Builtin::BI__sync_add_and_fetch_8:
2356 case Builtin::BI__sync_add_and_fetch_16:
2357 case Builtin::BI__sync_sub_and_fetch:
2358 case Builtin::BI__sync_sub_and_fetch_1:
2359 case Builtin::BI__sync_sub_and_fetch_2:
2360 case Builtin::BI__sync_sub_and_fetch_4:
2361 case Builtin::BI__sync_sub_and_fetch_8:
2362 case Builtin::BI__sync_sub_and_fetch_16:
2363 case Builtin::BI__sync_and_and_fetch:
2364 case Builtin::BI__sync_and_and_fetch_1:
2365 case Builtin::BI__sync_and_and_fetch_2:
2366 case Builtin::BI__sync_and_and_fetch_4:
2367 case Builtin::BI__sync_and_and_fetch_8:
2368 case Builtin::BI__sync_and_and_fetch_16:
2369 case Builtin::BI__sync_or_and_fetch:
2370 case Builtin::BI__sync_or_and_fetch_1:
2371 case Builtin::BI__sync_or_and_fetch_2:
2372 case Builtin::BI__sync_or_and_fetch_4:
2373 case Builtin::BI__sync_or_and_fetch_8:
2374 case Builtin::BI__sync_or_and_fetch_16:
2375 case Builtin::BI__sync_xor_and_fetch:
2376 case Builtin::BI__sync_xor_and_fetch_1:
2377 case Builtin::BI__sync_xor_and_fetch_2:
2378 case Builtin::BI__sync_xor_and_fetch_4:
2379 case Builtin::BI__sync_xor_and_fetch_8:
2380 case Builtin::BI__sync_xor_and_fetch_16:
2381 case Builtin::BI__sync_nand_and_fetch:
2382 case Builtin::BI__sync_nand_and_fetch_1:
2383 case Builtin::BI__sync_nand_and_fetch_2:
2384 case Builtin::BI__sync_nand_and_fetch_4:
2385 case Builtin::BI__sync_nand_and_fetch_8:
2386 case Builtin::BI__sync_nand_and_fetch_16:
2387 case Builtin::BI__sync_val_compare_and_swap:
2388 case Builtin::BI__sync_val_compare_and_swap_1:
2389 case Builtin::BI__sync_val_compare_and_swap_2:
2390 case Builtin::BI__sync_val_compare_and_swap_4:
2391 case Builtin::BI__sync_val_compare_and_swap_8:
2392 case Builtin::BI__sync_val_compare_and_swap_16:
2393 case Builtin::BI__sync_bool_compare_and_swap:
2394 case Builtin::BI__sync_bool_compare_and_swap_1:
2395 case Builtin::BI__sync_bool_compare_and_swap_2:
2396 case Builtin::BI__sync_bool_compare_and_swap_4:
2397 case Builtin::BI__sync_bool_compare_and_swap_8:
2398 case Builtin::BI__sync_bool_compare_and_swap_16:
2399 case Builtin::BI__sync_lock_test_and_set:
2400 case Builtin::BI__sync_lock_test_and_set_1:
2401 case Builtin::BI__sync_lock_test_and_set_2:
2402 case Builtin::BI__sync_lock_test_and_set_4:
2403 case Builtin::BI__sync_lock_test_and_set_8:
2404 case Builtin::BI__sync_lock_test_and_set_16:
2405 case Builtin::BI__sync_lock_release:
2406 case Builtin::BI__sync_lock_release_1:
2407 case Builtin::BI__sync_lock_release_2:
2408 case Builtin::BI__sync_lock_release_4:
2409 case Builtin::BI__sync_lock_release_8:
2410 case Builtin::BI__sync_lock_release_16:
2411 case Builtin::BI__sync_swap:
2412 case Builtin::BI__sync_swap_1:
2413 case Builtin::BI__sync_swap_2:
2414 case Builtin::BI__sync_swap_4:
2415 case Builtin::BI__sync_swap_8:
2416 case Builtin::BI__sync_swap_16:
2417 return BuiltinAtomicOverloaded(TheCallResult);
2418 case Builtin::BI__sync_synchronize:
2419 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
2420 << TheCall->getCallee()->getSourceRange();
2421 break;
2422 case Builtin::BI__builtin_nontemporal_load:
2423 case Builtin::BI__builtin_nontemporal_store:
2424 return BuiltinNontemporalOverloaded(TheCallResult);
2425 case Builtin::BI__builtin_memcpy_inline: {
2426 clang::Expr *SizeOp = TheCall->getArg(2);
2427 // We warn about copying to or from `nullptr` pointers when `size` is
2428 // greater than 0. When `size` is value dependent we cannot evaluate its
2429 // value so we bail out.
2430 if (SizeOp->isValueDependent())
2431 break;
2432 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
2433 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2434 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
2435 }
2436 break;
2437 }
2438 case Builtin::BI__builtin_memset_inline: {
2439 clang::Expr *SizeOp = TheCall->getArg(2);
2440 // We warn about filling to `nullptr` pointers when `size` is greater than
2441 // 0. When `size` is value dependent we cannot evaluate its value so we bail
2442 // out.
2443 if (SizeOp->isValueDependent())
2444 break;
2445 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
2446 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2447 break;
2448 }
2449#define BUILTIN(ID, TYPE, ATTRS)
2450#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
2451 case Builtin::BI##ID: \
2452 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
2453#include "clang/Basic/Builtins.inc"
2454 case Builtin::BI__annotation:
2455 if (BuiltinMSVCAnnotation(*this, TheCall))
2456 return ExprError();
2457 break;
2458 case Builtin::BI__builtin_annotation:
2459 if (BuiltinAnnotation(*this, TheCall))
2460 return ExprError();
2461 break;
2462 case Builtin::BI__builtin_addressof:
2463 if (BuiltinAddressof(*this, TheCall))
2464 return ExprError();
2465 break;
2466 case Builtin::BI__builtin_function_start:
2467 if (BuiltinFunctionStart(*this, TheCall))
2468 return ExprError();
2469 break;
2470 case Builtin::BI__builtin_is_aligned:
2471 case Builtin::BI__builtin_align_up:
2472 case Builtin::BI__builtin_align_down:
2473 if (BuiltinAlignment(*this, TheCall, BuiltinID))
2474 return ExprError();
2475 break;
2476 case Builtin::BI__builtin_add_overflow:
2477 case Builtin::BI__builtin_sub_overflow:
2478 case Builtin::BI__builtin_mul_overflow:
2479 if (BuiltinOverflow(*this, TheCall, BuiltinID))
2480 return ExprError();
2481 break;
2482 case Builtin::BI__builtin_operator_new:
2483 case Builtin::BI__builtin_operator_delete: {
2484 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
2485 ExprResult Res =
2486 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
2487 if (Res.isInvalid())
2488 CorrectDelayedTyposInExpr(TheCallResult.get());
2489 return Res;
2490 }
2491 case Builtin::BI__builtin_dump_struct:
2492 return BuiltinDumpStruct(*this, TheCall);
2493 case Builtin::BI__builtin_expect_with_probability: {
2494 // We first want to ensure we are called with 3 arguments
2495 if (checkArgCount(TheCall, 3))
2496 return ExprError();
2497 // then check probability is constant float in range [0.0, 1.0]
2498 const Expr *ProbArg = TheCall->getArg(2);
2500 Expr::EvalResult Eval;
2501 Eval.Diag = &Notes;
2502 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2503 !Eval.Val.isFloat()) {
2504 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2505 << ProbArg->getSourceRange();
2506 for (const PartialDiagnosticAt &PDiag : Notes)
2507 Diag(PDiag.first, PDiag.second);
2508 return ExprError();
2509 }
2510 llvm::APFloat Probability = Eval.Val.getFloat();
2511 bool LoseInfo = false;
2512 Probability.convert(llvm::APFloat::IEEEdouble(),
2513 llvm::RoundingMode::Dynamic, &LoseInfo);
2514 if (!(Probability >= llvm::APFloat(0.0) &&
2515 Probability <= llvm::APFloat(1.0))) {
2516 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2517 << ProbArg->getSourceRange();
2518 return ExprError();
2519 }
2520 break;
2521 }
2522 case Builtin::BI__builtin_preserve_access_index:
2523 if (BuiltinPreserveAI(*this, TheCall))
2524 return ExprError();
2525 break;
2526 case Builtin::BI__builtin_call_with_static_chain:
2527 if (BuiltinCallWithStaticChain(*this, TheCall))
2528 return ExprError();
2529 break;
2530 case Builtin::BI__exception_code:
2531 case Builtin::BI_exception_code:
2532 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
2533 diag::err_seh___except_block))
2534 return ExprError();
2535 break;
2536 case Builtin::BI__exception_info:
2537 case Builtin::BI_exception_info:
2538 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2539 diag::err_seh___except_filter))
2540 return ExprError();
2541 break;
2542 case Builtin::BI__GetExceptionInfo:
2543 if (checkArgCount(TheCall, 1))
2544 return ExprError();
2545
2547 TheCall->getBeginLoc(),
2549 TheCall))
2550 return ExprError();
2551
2552 TheCall->setType(Context.VoidPtrTy);
2553 break;
2554 case Builtin::BIaddressof:
2555 case Builtin::BI__addressof:
2556 case Builtin::BIforward:
2557 case Builtin::BIforward_like:
2558 case Builtin::BImove:
2559 case Builtin::BImove_if_noexcept:
2560 case Builtin::BIas_const: {
2561 // These are all expected to be of the form
2562 // T &/&&/* f(U &/&&)
2563 // where T and U only differ in qualification.
2564 if (checkArgCount(TheCall, 1))
2565 return ExprError();
2566 QualType Param = FDecl->getParamDecl(0)->getType();
2567 QualType Result = FDecl->getReturnType();
2568 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
2569 BuiltinID == Builtin::BI__addressof;
2570 if (!(Param->isReferenceType() &&
2571 (ReturnsPointer ? Result->isAnyPointerType()
2572 : Result->isReferenceType()) &&
2574 Result->getPointeeType()))) {
2575 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
2576 << FDecl;
2577 return ExprError();
2578 }
2579 break;
2580 }
2581 case Builtin::BI__builtin_ptrauth_strip:
2582 return PointerAuthStrip(*this, TheCall);
2583 case Builtin::BI__builtin_ptrauth_blend_discriminator:
2584 return PointerAuthBlendDiscriminator(*this, TheCall);
2585 case Builtin::BI__builtin_ptrauth_sign_constant:
2586 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
2587 /*RequireConstant=*/true);
2588 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
2589 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
2590 /*RequireConstant=*/false);
2591 case Builtin::BI__builtin_ptrauth_auth:
2592 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
2593 /*RequireConstant=*/false);
2594 case Builtin::BI__builtin_ptrauth_sign_generic_data:
2595 return PointerAuthSignGenericData(*this, TheCall);
2596 case Builtin::BI__builtin_ptrauth_auth_and_resign:
2597 return PointerAuthAuthAndResign(*this, TheCall);
2598 case Builtin::BI__builtin_ptrauth_string_discriminator:
2599 return PointerAuthStringDiscriminator(*this, TheCall);
2600 // OpenCL v2.0, s6.13.16 - Pipe functions
2601 case Builtin::BIread_pipe:
2602 case Builtin::BIwrite_pipe:
2603 // Since those two functions are declared with var args, we need a semantic
2604 // check for the argument.
2605 if (OpenCL().checkBuiltinRWPipe(TheCall))
2606 return ExprError();
2607 break;
2608 case Builtin::BIreserve_read_pipe:
2609 case Builtin::BIreserve_write_pipe:
2610 case Builtin::BIwork_group_reserve_read_pipe:
2611 case Builtin::BIwork_group_reserve_write_pipe:
2612 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
2613 return ExprError();
2614 break;
2615 case Builtin::BIsub_group_reserve_read_pipe:
2616 case Builtin::BIsub_group_reserve_write_pipe:
2617 if (OpenCL().checkSubgroupExt(TheCall) ||
2618 OpenCL().checkBuiltinReserveRWPipe(TheCall))
2619 return ExprError();
2620 break;
2621 case Builtin::BIcommit_read_pipe:
2622 case Builtin::BIcommit_write_pipe:
2623 case Builtin::BIwork_group_commit_read_pipe:
2624 case Builtin::BIwork_group_commit_write_pipe:
2625 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
2626 return ExprError();
2627 break;
2628 case Builtin::BIsub_group_commit_read_pipe:
2629 case Builtin::BIsub_group_commit_write_pipe:
2630 if (OpenCL().checkSubgroupExt(TheCall) ||
2631 OpenCL().checkBuiltinCommitRWPipe(TheCall))
2632 return ExprError();
2633 break;
2634 case Builtin::BIget_pipe_num_packets:
2635 case Builtin::BIget_pipe_max_packets:
2636 if (OpenCL().checkBuiltinPipePackets(TheCall))
2637 return ExprError();
2638 break;
2639 case Builtin::BIto_global:
2640 case Builtin::BIto_local:
2641 case Builtin::BIto_private:
2642 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
2643 return ExprError();
2644 break;
2645 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2646 case Builtin::BIenqueue_kernel:
2647 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
2648 return ExprError();
2649 break;
2650 case Builtin::BIget_kernel_work_group_size:
2651 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2652 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
2653 return ExprError();
2654 break;
2655 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2656 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2657 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
2658 return ExprError();
2659 break;
2660 case Builtin::BI__builtin_os_log_format:
2662 [[fallthrough]];
2663 case Builtin::BI__builtin_os_log_format_buffer_size:
2664 if (BuiltinOSLogFormat(TheCall))
2665 return ExprError();
2666 break;
2667 case Builtin::BI__builtin_frame_address:
2668 case Builtin::BI__builtin_return_address: {
2669 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
2670 return ExprError();
2671
2672 // -Wframe-address warning if non-zero passed to builtin
2673 // return/frame address.
2675 if (!TheCall->getArg(0)->isValueDependent() &&
2676 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
2677 Result.Val.getInt() != 0)
2678 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
2679 << ((BuiltinID == Builtin::BI__builtin_return_address)
2680 ? "__builtin_return_address"
2681 : "__builtin_frame_address")
2682 << TheCall->getSourceRange();
2683 break;
2684 }
2685
2686 case Builtin::BI__builtin_nondeterministic_value: {
2687 if (BuiltinNonDeterministicValue(TheCall))
2688 return ExprError();
2689 break;
2690 }
2691
2692 // __builtin_elementwise_abs restricts the element type to signed integers or
2693 // floating point types only.
2694 case Builtin::BI__builtin_elementwise_abs: {
2696 return ExprError();
2697
2698 QualType ArgTy = TheCall->getArg(0)->getType();
2699 QualType EltTy = ArgTy;
2700
2701 if (auto *VecTy = EltTy->getAs<VectorType>())
2702 EltTy = VecTy->getElementType();
2703 if (EltTy->isUnsignedIntegerType()) {
2704 Diag(TheCall->getArg(0)->getBeginLoc(),
2705 diag::err_builtin_invalid_arg_type)
2706 << 1 << /* signed integer or float ty*/ 3 << ArgTy;
2707 return ExprError();
2708 }
2709 break;
2710 }
2711
2712 // These builtins restrict the element type to floating point
2713 // types only.
2714 case Builtin::BI__builtin_elementwise_acos:
2715 case Builtin::BI__builtin_elementwise_asin:
2716 case Builtin::BI__builtin_elementwise_atan:
2717 case Builtin::BI__builtin_elementwise_ceil:
2718 case Builtin::BI__builtin_elementwise_cos:
2719 case Builtin::BI__builtin_elementwise_cosh:
2720 case Builtin::BI__builtin_elementwise_exp:
2721 case Builtin::BI__builtin_elementwise_exp2:
2722 case Builtin::BI__builtin_elementwise_floor:
2723 case Builtin::BI__builtin_elementwise_log:
2724 case Builtin::BI__builtin_elementwise_log2:
2725 case Builtin::BI__builtin_elementwise_log10:
2726 case Builtin::BI__builtin_elementwise_roundeven:
2727 case Builtin::BI__builtin_elementwise_round:
2728 case Builtin::BI__builtin_elementwise_rint:
2729 case Builtin::BI__builtin_elementwise_nearbyint:
2730 case Builtin::BI__builtin_elementwise_sin:
2731 case Builtin::BI__builtin_elementwise_sinh:
2732 case Builtin::BI__builtin_elementwise_sqrt:
2733 case Builtin::BI__builtin_elementwise_tan:
2734 case Builtin::BI__builtin_elementwise_tanh:
2735 case Builtin::BI__builtin_elementwise_trunc:
2736 case Builtin::BI__builtin_elementwise_canonicalize: {
2738 return ExprError();
2739
2740 QualType ArgTy = TheCall->getArg(0)->getType();
2741 if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
2742 ArgTy, 1))
2743 return ExprError();
2744 break;
2745 }
2746 case Builtin::BI__builtin_elementwise_fma: {
2747 if (BuiltinElementwiseTernaryMath(TheCall))
2748 return ExprError();
2749 break;
2750 }
2751
2752 // These builtins restrict the element type to floating point
2753 // types only, and take in two arguments.
2754 case Builtin::BI__builtin_elementwise_minimum:
2755 case Builtin::BI__builtin_elementwise_maximum:
2756 case Builtin::BI__builtin_elementwise_atan2:
2757 case Builtin::BI__builtin_elementwise_fmod:
2758 case Builtin::BI__builtin_elementwise_pow: {
2759 if (BuiltinElementwiseMath(TheCall, /*FPOnly=*/true))
2760 return ExprError();
2761 break;
2762 }
2763
2764 // These builtins restrict the element type to integer
2765 // types only.
2766 case Builtin::BI__builtin_elementwise_add_sat:
2767 case Builtin::BI__builtin_elementwise_sub_sat: {
2768 if (BuiltinElementwiseMath(TheCall))
2769 return ExprError();
2770
2771 const Expr *Arg = TheCall->getArg(0);
2772 QualType ArgTy = Arg->getType();
2773 QualType EltTy = ArgTy;
2774
2775 if (auto *VecTy = EltTy->getAs<VectorType>())
2776 EltTy = VecTy->getElementType();
2777
2778 if (!EltTy->isIntegerType()) {
2779 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2780 << 1 << /* integer ty */ 6 << ArgTy;
2781 return ExprError();
2782 }
2783 break;
2784 }
2785
2786 case Builtin::BI__builtin_elementwise_min:
2787 case Builtin::BI__builtin_elementwise_max:
2788 if (BuiltinElementwiseMath(TheCall))
2789 return ExprError();
2790 break;
2791 case Builtin::BI__builtin_elementwise_popcount:
2792 case Builtin::BI__builtin_elementwise_bitreverse: {
2794 return ExprError();
2795
2796 const Expr *Arg = TheCall->getArg(0);
2797 QualType ArgTy = Arg->getType();
2798 QualType EltTy = ArgTy;
2799
2800 if (auto *VecTy = EltTy->getAs<VectorType>())
2801 EltTy = VecTy->getElementType();
2802
2803 if (!EltTy->isIntegerType()) {
2804 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2805 << 1 << /* integer ty */ 6 << ArgTy;
2806 return ExprError();
2807 }
2808 break;
2809 }
2810
2811 case Builtin::BI__builtin_elementwise_copysign: {
2812 if (checkArgCount(TheCall, 2))
2813 return ExprError();
2814
2815 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
2816 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
2817 if (Magnitude.isInvalid() || Sign.isInvalid())
2818 return ExprError();
2819
2820 QualType MagnitudeTy = Magnitude.get()->getType();
2821 QualType SignTy = Sign.get()->getType();
2822 if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
2823 MagnitudeTy, 1) ||
2824 checkFPMathBuiltinElementType(*this, TheCall->getArg(1)->getBeginLoc(),
2825 SignTy, 2)) {
2826 return ExprError();
2827 }
2828
2829 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
2830 return Diag(Sign.get()->getBeginLoc(),
2831 diag::err_typecheck_call_different_arg_types)
2832 << MagnitudeTy << SignTy;
2833 }
2834
2835 TheCall->setArg(0, Magnitude.get());
2836 TheCall->setArg(1, Sign.get());
2837 TheCall->setType(Magnitude.get()->getType());
2838 break;
2839 }
2840 case Builtin::BI__builtin_reduce_max:
2841 case Builtin::BI__builtin_reduce_min: {
2842 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2843 return ExprError();
2844
2845 const Expr *Arg = TheCall->getArg(0);
2846 const auto *TyA = Arg->getType()->getAs<VectorType>();
2847
2848 QualType ElTy;
2849 if (TyA)
2850 ElTy = TyA->getElementType();
2851 else if (Arg->getType()->isSizelessVectorType())
2853
2854 if (ElTy.isNull()) {
2855 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2856 << 1 << /* vector ty*/ 4 << Arg->getType();
2857 return ExprError();
2858 }
2859
2860 TheCall->setType(ElTy);
2861 break;
2862 }
2863 case Builtin::BI__builtin_reduce_maximum:
2864 case Builtin::BI__builtin_reduce_minimum: {
2865 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2866 return ExprError();
2867
2868 const Expr *Arg = TheCall->getArg(0);
2869 const auto *TyA = Arg->getType()->getAs<VectorType>();
2870
2871 QualType ElTy;
2872 if (TyA)
2873 ElTy = TyA->getElementType();
2874 else if (Arg->getType()->isSizelessVectorType())
2876
2877 if (ElTy.isNull() || !ElTy->isFloatingType()) {
2878 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2879 << 1 << /* vector of floating points */ 9 << Arg->getType();
2880 return ExprError();
2881 }
2882
2883 TheCall->setType(ElTy);
2884 break;
2885 }
2886
2887 // These builtins support vectors of integers only.
2888 // TODO: ADD/MUL should support floating-point types.
2889 case Builtin::BI__builtin_reduce_add:
2890 case Builtin::BI__builtin_reduce_mul:
2891 case Builtin::BI__builtin_reduce_xor:
2892 case Builtin::BI__builtin_reduce_or:
2893 case Builtin::BI__builtin_reduce_and: {
2894 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2895 return ExprError();
2896
2897 const Expr *Arg = TheCall->getArg(0);
2898 const auto *TyA = Arg->getType()->getAs<VectorType>();
2899
2900 QualType ElTy;
2901 if (TyA)
2902 ElTy = TyA->getElementType();
2903 else if (Arg->getType()->isSizelessVectorType())
2905
2906 if (ElTy.isNull() || !ElTy->isIntegerType()) {
2907 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2908 << 1 << /* vector of integers */ 6 << Arg->getType();
2909 return ExprError();
2910 }
2911
2912 TheCall->setType(ElTy);
2913 break;
2914 }
2915
2916 case Builtin::BI__builtin_matrix_transpose:
2917 return BuiltinMatrixTranspose(TheCall, TheCallResult);
2918
2919 case Builtin::BI__builtin_matrix_column_major_load:
2920 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
2921
2922 case Builtin::BI__builtin_matrix_column_major_store:
2923 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
2924
2925 case Builtin::BI__builtin_verbose_trap:
2926 if (!checkBuiltinVerboseTrap(TheCall, *this))
2927 return ExprError();
2928 break;
2929
2930 case Builtin::BI__builtin_get_device_side_mangled_name: {
2931 auto Check = [](CallExpr *TheCall) {
2932 if (TheCall->getNumArgs() != 1)
2933 return false;
2934 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2935 if (!DRE)
2936 return false;
2937 auto *D = DRE->getDecl();
2938 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2939 return false;
2940 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2941 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2942 };
2943 if (!Check(TheCall)) {
2944 Diag(TheCall->getBeginLoc(),
2945 diag::err_hip_invalid_args_builtin_mangled_name);
2946 return ExprError();
2947 }
2948 break;
2949 }
2950 case Builtin::BI__builtin_popcountg:
2951 if (BuiltinPopcountg(*this, TheCall))
2952 return ExprError();
2953 break;
2954 case Builtin::BI__builtin_clzg:
2955 case Builtin::BI__builtin_ctzg:
2956 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
2957 return ExprError();
2958 break;
2959
2960 case Builtin::BI__builtin_allow_runtime_check: {
2961 Expr *Arg = TheCall->getArg(0);
2962 // Check if the argument is a string literal.
2963 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) {
2964 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2965 << Arg->getSourceRange();
2966 return ExprError();
2967 }
2968 break;
2969 }
2970 case Builtin::BI__builtin_counted_by_ref:
2971 if (BuiltinCountedByRef(TheCall))
2972 return ExprError();
2973 break;
2974 }
2975
2976 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
2977 return ExprError();
2978
2979 // Since the target specific builtins for each arch overlap, only check those
2980 // of the arch we are compiling for.
2981 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2982 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2983 assert(Context.getAuxTargetInfo() &&
2984 "Aux Target Builtin, but not an aux target?");
2985
2986 if (CheckTSBuiltinFunctionCall(
2988 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2989 return ExprError();
2990 } else {
2991 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2992 TheCall))
2993 return ExprError();
2994 }
2995 }
2996
2997 return TheCallResult;
2998}
2999
3000bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3001 llvm::APSInt Result;
3002 // We can't check the value of a dependent argument.
3003 Expr *Arg = TheCall->getArg(ArgNum);
3004 if (Arg->isTypeDependent() || Arg->isValueDependent())
3005 return false;
3006
3007 // Check constant-ness first.
3008 if (BuiltinConstantArg(TheCall, ArgNum, Result))
3009 return true;
3010
3011 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3012 if (Result.isShiftedMask() || (~Result).isShiftedMask())
3013 return false;
3014
3015 return Diag(TheCall->getBeginLoc(),
3016 diag::err_argument_not_contiguous_bit_field)
3017 << ArgNum << Arg->getSourceRange();
3018}
3019
3020bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3021 bool IsVariadic, FormatStringInfo *FSI) {
3022 if (Format->getFirstArg() == 0)
3024 else if (IsVariadic)
3026 else
3028 FSI->FormatIdx = Format->getFormatIdx() - 1;
3029 FSI->FirstDataArg =
3030 FSI->ArgPassingKind == FAPK_VAList ? 0 : Format->getFirstArg() - 1;
3031
3032 // The way the format attribute works in GCC, the implicit this argument
3033 // of member functions is counted. However, it doesn't appear in our own
3034 // lists, so decrement format_idx in that case.
3035 if (IsCXXMember) {
3036 if(FSI->FormatIdx == 0)
3037 return false;
3038 --FSI->FormatIdx;
3039 if (FSI->FirstDataArg != 0)
3040 --FSI->FirstDataArg;
3041 }
3042 return true;
3043}
3044
3045/// Checks if a the given expression evaluates to null.
3046///
3047/// Returns true if the value evaluates to null.
3048static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3049 // Treat (smart) pointers constructed from nullptr as null, whether we can
3050 // const-evaluate them or not.
3051 // This must happen first: the smart pointer expr might have _Nonnull type!
3052 if (isa<CXXNullPtrLiteralExpr>(
3055 return true;
3056
3057 // If the expression has non-null type, it doesn't evaluate to null.
3058 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
3059 if (*nullability == NullabilityKind::NonNull)
3060 return false;
3061 }
3062
3063 // As a special case, transparent unions initialized with zero are
3064 // considered null for the purposes of the nonnull attribute.
3065 if (const RecordType *UT = Expr->getType()->getAsUnionType();
3066 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
3067 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
3068 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
3069 Expr = ILE->getInit(0);
3070 }
3071
3072 bool Result;
3073 return (!Expr->isValueDependent() &&
3075 !Result);
3076}
3077
3079 const Expr *ArgExpr,
3080 SourceLocation CallSiteLoc) {
3081 if (CheckNonNullExpr(S, ArgExpr))
3082 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3083 S.PDiag(diag::warn_null_arg)
3084 << ArgExpr->getSourceRange());
3085}
3086
3087/// Determine whether the given type has a non-null nullability annotation.
3089 if (auto nullability = type->getNullability())
3090 return *nullability == NullabilityKind::NonNull;
3091
3092 return false;
3093}
3094
3096 const NamedDecl *FDecl,
3097 const FunctionProtoType *Proto,
3099 SourceLocation CallSiteLoc) {
3100 assert((FDecl || Proto) && "Need a function declaration or prototype");
3101
3102 // Already checked by constant evaluator.
3104 return;
3105 // Check the attributes attached to the method/function itself.
3106 llvm::SmallBitVector NonNullArgs;
3107 if (FDecl) {
3108 // Handle the nonnull attribute on the function/method declaration itself.
3109 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3110 if (!NonNull->args_size()) {
3111 // Easy case: all pointer arguments are nonnull.
3112 for (const auto *Arg : Args)
3113 if (S.isValidPointerAttrType(Arg->getType()))
3114 CheckNonNullArgument(S, Arg, CallSiteLoc);
3115 return;
3116 }
3117
3118 for (const ParamIdx &Idx : NonNull->args()) {
3119 unsigned IdxAST = Idx.getASTIndex();
3120 if (IdxAST >= Args.size())
3121 continue;
3122 if (NonNullArgs.empty())
3123 NonNullArgs.resize(Args.size());
3124 NonNullArgs.set(IdxAST);
3125 }
3126 }
3127 }
3128
3129 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3130 // Handle the nonnull attribute on the parameters of the
3131 // function/method.
3133 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3134 parms = FD->parameters();
3135 else
3136 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3137
3138 unsigned ParamIndex = 0;
3139 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3140 I != E; ++I, ++ParamIndex) {
3141 const ParmVarDecl *PVD = *I;
3142 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
3143 if (NonNullArgs.empty())
3144 NonNullArgs.resize(Args.size());
3145
3146 NonNullArgs.set(ParamIndex);
3147 }
3148 }
3149 } else {
3150 // If we have a non-function, non-method declaration but no
3151 // function prototype, try to dig out the function prototype.
3152 if (!Proto) {
3153 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3154 QualType type = VD->getType().getNonReferenceType();
3155 if (auto pointerType = type->getAs<PointerType>())
3156 type = pointerType->getPointeeType();
3157 else if (auto blockType = type->getAs<BlockPointerType>())
3158 type = blockType->getPointeeType();
3159 // FIXME: data member pointers?
3160
3161 // Dig out the function prototype, if there is one.
3162 Proto = type->getAs<FunctionProtoType>();
3163 }
3164 }
3165
3166 // Fill in non-null argument information from the nullability
3167 // information on the parameter types (if we have them).
3168 if (Proto) {
3169 unsigned Index = 0;
3170 for (auto paramType : Proto->getParamTypes()) {
3171 if (isNonNullType(paramType)) {
3172 if (NonNullArgs.empty())
3173 NonNullArgs.resize(Args.size());
3174
3175 NonNullArgs.set(Index);
3176 }
3177
3178 ++Index;
3179 }
3180 }
3181 }
3182
3183 // Check for non-null arguments.
3184 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3185 ArgIndex != ArgIndexEnd; ++ArgIndex) {
3186 if (NonNullArgs[ArgIndex])
3187 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
3188 }
3189}
3190
3191void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
3192 StringRef ParamName, QualType ArgTy,
3193 QualType ParamTy) {
3194
3195 // If a function accepts a pointer or reference type
3196 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
3197 return;
3198
3199 // If the parameter is a pointer type, get the pointee type for the
3200 // argument too. If the parameter is a reference type, don't try to get
3201 // the pointee type for the argument.
3202 if (ParamTy->isPointerType())
3203 ArgTy = ArgTy->getPointeeType();
3204
3205 // Remove reference or pointer
3206 ParamTy = ParamTy->getPointeeType();
3207
3208 // Find expected alignment, and the actual alignment of the passed object.
3209 // getTypeAlignInChars requires complete types
3210 if (ArgTy.isNull() || ParamTy->isDependentType() ||
3211 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
3212 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
3213 return;
3214
3215 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
3216 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
3217
3218 // If the argument is less aligned than the parameter, there is a
3219 // potential alignment issue.
3220 if (ArgAlign < ParamAlign)
3221 Diag(Loc, diag::warn_param_mismatched_alignment)
3222 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
3223 << ParamName << (FDecl != nullptr) << FDecl;
3224}
3225
3226void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
3227 const Expr *ThisArg,
3229 if (!FD || Args.empty())
3230 return;
3231 auto GetArgAt = [&](int Idx) -> const Expr * {
3232 if (Idx == LifetimeCaptureByAttr::GLOBAL ||
3233 Idx == LifetimeCaptureByAttr::UNKNOWN)
3234 return nullptr;
3235 if (IsMemberFunction && Idx == 0)
3236 return ThisArg;
3237 return Args[Idx - IsMemberFunction];
3238 };
3239 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
3240 unsigned ArgIdx) {
3241 if (!Attr)
3242 return;
3243
3244 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
3245 for (int CapturingParamIdx : Attr->params()) {
3246 // lifetime_capture_by(this) case is handled in the lifetimebound expr
3247 // initialization codepath.
3248 if (CapturingParamIdx == LifetimeCaptureByAttr::THIS &&
3249 isa<CXXConstructorDecl>(FD))
3250 continue;
3251 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
3252 CapturingEntity CE{Capturing};
3253 // Ensure that 'Captured' outlives the 'Capturing' entity.
3254 checkCaptureByLifetime(*this, CE, Captured);
3255 }
3256 };
3257 for (unsigned I = 0; I < FD->getNumParams(); ++I)
3258 HandleCaptureByAttr(FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>(),
3259 I + IsMemberFunction);
3260 // Check when the implicit object param is captured.
3261 if (IsMemberFunction) {
3262 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
3263 if (!TSI)
3264 return;
3266 for (TypeLoc TL = TSI->getTypeLoc();
3267 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
3268 TL = ATL.getModifiedLoc())
3269 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
3270 }
3271}
3272
3274 const Expr *ThisArg, ArrayRef<const Expr *> Args,
3275 bool IsMemberFunction, SourceLocation Loc,
3277 // FIXME: We should check as much as we can in the template definition.
3279 return;
3280
3281 // Printf and scanf checking.
3282 llvm::SmallBitVector CheckedVarArgs;
3283 if (FDecl) {
3284 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3285 // Only create vector if there are format attributes.
3286 CheckedVarArgs.resize(Args.size());
3287
3288 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
3289 CheckedVarArgs);
3290 }
3291 }
3292
3293 // Refuse POD arguments that weren't caught by the format string
3294 // checks above.
3295 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3296 if (CallType != VariadicDoesNotApply &&
3297 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
3298 unsigned NumParams = Proto ? Proto->getNumParams()
3299 : isa_and_nonnull<FunctionDecl>(FDecl)
3300 ? cast<FunctionDecl>(FDecl)->getNumParams()
3301 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
3302 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3303 : 0;
3304
3305 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
3306 // Args[ArgIdx] can be null in malformed code.
3307 if (const Expr *Arg = Args[ArgIdx]) {
3308 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3309 checkVariadicArgument(Arg, CallType);
3310 }
3311 }
3312 }
3313 if (FD)
3314 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
3315 if (FDecl || Proto) {
3316 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
3317
3318 // Type safety checking.
3319 if (FDecl) {
3320 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
3321 CheckArgumentWithTypeTag(I, Args, Loc);
3322 }
3323 }
3324
3325 // Check that passed arguments match the alignment of original arguments.
3326 // Try to get the missing prototype from the declaration.
3327 if (!Proto && FDecl) {
3328 const auto *FT = FDecl->getFunctionType();
3329 if (isa_and_nonnull<FunctionProtoType>(FT))
3330 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
3331 }
3332 if (Proto) {
3333 // For variadic functions, we may have more args than parameters.
3334 // For some K&R functions, we may have less args than parameters.
3335 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
3336 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
3337 bool IsScalableArg = false;
3338 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
3339 // Args[ArgIdx] can be null in malformed code.
3340 if (const Expr *Arg = Args[ArgIdx]) {
3341 if (Arg->containsErrors())
3342 continue;
3343
3344 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
3345 FDecl->hasLinkage() &&
3346 FDecl->getFormalLinkage() != Linkage::Internal &&
3347 CallType == VariadicDoesNotApply)
3348 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
3349
3350 QualType ParamTy = Proto->getParamType(ArgIdx);
3351 if (ParamTy->isSizelessVectorType())
3352 IsScalableArg = true;
3353 QualType ArgTy = Arg->getType();
3354 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
3355 ArgTy, ParamTy);
3356 }
3357 }
3358
3359 // If the callee has an AArch64 SME attribute to indicate that it is an
3360 // __arm_streaming function, then the caller requires SME to be available.
3363 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
3364 llvm::StringMap<bool> CallerFeatureMap;
3365 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
3366 if (!CallerFeatureMap.contains("sme"))
3367 Diag(Loc, diag::err_sme_call_in_non_sme_target);
3368 } else if (!Context.getTargetInfo().hasFeature("sme")) {
3369 Diag(Loc, diag::err_sme_call_in_non_sme_target);
3370 }
3371 }
3372
3373 // If the call requires a streaming-mode change and has scalable vector
3374 // arguments or return values, then warn the user that the streaming and
3375 // non-streaming vector lengths may be different.
3376 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
3377 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
3378 (IsScalableArg || IsScalableRet)) {
3379 bool IsCalleeStreaming =
3381 bool IsCalleeStreamingCompatible =
3382 ExtInfo.AArch64SMEAttributes &
3384 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
3385 if (!IsCalleeStreamingCompatible &&
3386 (CallerFnType == SemaARM::ArmStreamingCompatible ||
3387 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
3388 if (IsScalableArg)
3389 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
3390 << /*IsArg=*/true;
3391 if (IsScalableRet)
3392 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
3393 << /*IsArg=*/false;
3394 }
3395 }
3396
3397 FunctionType::ArmStateValue CalleeArmZAState =
3399 FunctionType::ArmStateValue CalleeArmZT0State =
3401 if (CalleeArmZAState != FunctionType::ARM_None ||
3402 CalleeArmZT0State != FunctionType::ARM_None) {
3403 bool CallerHasZAState = false;
3404 bool CallerHasZT0State = false;
3405 if (CallerFD) {
3406 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
3407 if (Attr && Attr->isNewZA())
3408 CallerHasZAState = true;
3409 if (Attr && Attr->isNewZT0())
3410 CallerHasZT0State = true;
3411 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
3412 CallerHasZAState |=
3414 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
3416 CallerHasZT0State |=
3418 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
3420 }
3421 }
3422
3423 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
3424 Diag(Loc, diag::err_sme_za_call_no_za_state);
3425
3426 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
3427 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
3428
3429 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
3430 CalleeArmZT0State != FunctionType::ARM_None) {
3431 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
3432 Diag(Loc, diag::note_sme_use_preserves_za);
3433 }
3434 }
3435 }
3436
3437 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
3438 auto *AA = FDecl->getAttr<AllocAlignAttr>();
3439 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
3440 if (!Arg->isValueDependent()) {
3441 Expr::EvalResult Align;
3442 if (Arg->EvaluateAsInt(Align, Context)) {
3443 const llvm::APSInt &I = Align.Val.getInt();
3444 if (!I.isPowerOf2())
3445 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
3446 << Arg->getSourceRange();
3447
3448 if (I > Sema::MaximumAlignment)
3449 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
3450 << Arg->getSourceRange() << Sema::MaximumAlignment;
3451 }
3452 }
3453 }
3454
3455 if (FD)
3456 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
3457}
3458
3460 if (ConceptDecl *Decl = AutoT->getTypeConstraintConcept()) {
3462 }
3463}
3464
3465void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
3467 const FunctionProtoType *Proto,
3469 VariadicCallType CallType =
3471
3472 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
3473 CheckArgAlignment(
3474 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
3475 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
3476
3477 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
3478 Loc, SourceRange(), CallType);
3479}
3480
3482 const FunctionProtoType *Proto) {
3483 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
3484 isa<CXXMethodDecl>(FDecl);
3485 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
3486 IsMemberOperatorCall;
3487 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
3488 TheCall->getCallee());
3489 Expr** Args = TheCall->getArgs();
3490 unsigned NumArgs = TheCall->getNumArgs();
3491
3492 Expr *ImplicitThis = nullptr;
3493 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
3494 // If this is a call to a member operator, hide the first
3495 // argument from checkCall.
3496 // FIXME: Our choice of AST representation here is less than ideal.
3497 ImplicitThis = Args[0];
3498 ++Args;
3499 --NumArgs;
3500 } else if (IsMemberFunction && !FDecl->isStatic() &&
3502 ImplicitThis =
3503 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3504
3505 if (ImplicitThis) {
3506 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
3507 // used.
3508 QualType ThisType = ImplicitThis->getType();
3509 if (!ThisType->isPointerType()) {
3510 assert(!ThisType->isReferenceType());
3511 ThisType = Context.getPointerType(ThisType);
3512 }
3513
3514 QualType ThisTypeFromDecl = Context.getPointerType(
3515 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
3516
3517 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
3518 ThisTypeFromDecl);
3519 }
3520
3521 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
3522 IsMemberFunction, TheCall->getRParenLoc(),
3523 TheCall->getCallee()->getSourceRange(), CallType);
3524
3525 IdentifierInfo *FnInfo = FDecl->getIdentifier();
3526 // None of the checks below are needed for functions that don't have
3527 // simple names (e.g., C++ conversion functions).
3528 if (!FnInfo)
3529 return false;
3530
3531 // Enforce TCB except for builtin calls, which are always allowed.
3532 if (FDecl->getBuiltinID() == 0)
3533 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
3534
3535 CheckAbsoluteValueFunction(TheCall, FDecl);
3536 CheckMaxUnsignedZero(TheCall, FDecl);
3537 CheckInfNaNFunction(TheCall, FDecl);
3538
3539 if (getLangOpts().ObjC)
3540 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
3541
3542 unsigned CMId = FDecl->getMemoryFunctionKind();
3543
3544 // Handle memory setting and copying functions.
3545 switch (CMId) {
3546 case 0:
3547 return false;
3548 case Builtin::BIstrlcpy: // fallthrough
3549 case Builtin::BIstrlcat:
3550 CheckStrlcpycatArguments(TheCall, FnInfo);
3551 break;
3552 case Builtin::BIstrncat:
3553 CheckStrncatArguments(TheCall, FnInfo);
3554 break;
3555 case Builtin::BIfree:
3556 CheckFreeArguments(TheCall);
3557 break;
3558 default:
3559 CheckMemaccessArguments(TheCall, CMId, FnInfo);
3560 }
3561
3562 return false;
3563}
3564
3565bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3566 const FunctionProtoType *Proto) {
3567 QualType Ty;
3568 if (const auto *V = dyn_cast<VarDecl>(NDecl))
3569 Ty = V->getType().getNonReferenceType();
3570 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
3571 Ty = F->getType().getNonReferenceType();
3572 else
3573 return false;
3574
3575 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
3576 !Ty->isFunctionProtoType())
3577 return false;
3578
3579 VariadicCallType CallType;
3580 if (!Proto || !Proto->isVariadic()) {
3581 CallType = VariadicDoesNotApply;
3582 } else if (Ty->isBlockPointerType()) {
3583 CallType = VariadicBlock;
3584 } else { // Ty->isFunctionPointerType()
3585 CallType = VariadicFunction;
3586 }
3587
3588 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
3589 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3590 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
3591 TheCall->getCallee()->getSourceRange(), CallType);
3592
3593 return false;
3594}
3595
3596bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
3597 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
3598 TheCall->getCallee());
3599 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
3600 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3601 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
3602 TheCall->getCallee()->getSourceRange(), CallType);
3603
3604 return false;
3605}
3606
3607static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
3608 if (!llvm::isValidAtomicOrderingCABI(Ordering))
3609 return false;
3610
3611 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
3612 switch (Op) {
3613 case AtomicExpr::AO__c11_atomic_init:
3614 case AtomicExpr::AO__opencl_atomic_init:
3615 llvm_unreachable("There is no ordering argument for an init");
3616
3617 case AtomicExpr::AO__c11_atomic_load:
3618 case AtomicExpr::AO__opencl_atomic_load:
3619 case AtomicExpr::AO__hip_atomic_load:
3620 case AtomicExpr::AO__atomic_load_n:
3621 case AtomicExpr::AO__atomic_load:
3622 case AtomicExpr::AO__scoped_atomic_load_n:
3623 case AtomicExpr::AO__scoped_atomic_load:
3624 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
3625 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
3626
3627 case AtomicExpr::AO__c11_atomic_store:
3628 case AtomicExpr::AO__opencl_atomic_store:
3629 case AtomicExpr::AO__hip_atomic_store:
3630 case AtomicExpr::AO__atomic_store:
3631 case AtomicExpr::AO__atomic_store_n:
3632 case AtomicExpr::AO__scoped_atomic_store:
3633 case AtomicExpr::AO__scoped_atomic_store_n:
3634 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
3635 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
3636 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
3637
3638 default:
3639 return true;
3640 }
3641}
3642
3643ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
3645 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3646 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3647 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
3648 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
3649 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
3650 Op);
3651}
3652
3654 SourceLocation RParenLoc, MultiExprArg Args,
3656 AtomicArgumentOrder ArgOrder) {
3657 // All the non-OpenCL operations take one of the following forms.
3658 // The OpenCL operations take the __c11 forms with one extra argument for
3659 // synchronization scope.
3660 enum {
3661 // C __c11_atomic_init(A *, C)
3662 Init,
3663
3664 // C __c11_atomic_load(A *, int)
3665 Load,
3666
3667 // void __atomic_load(A *, CP, int)
3668 LoadCopy,
3669
3670 // void __atomic_store(A *, CP, int)
3671 Copy,
3672
3673 // C __c11_atomic_add(A *, M, int)
3674 Arithmetic,
3675
3676 // C __atomic_exchange_n(A *, CP, int)
3677 Xchg,
3678
3679 // void __atomic_exchange(A *, C *, CP, int)
3680 GNUXchg,
3681
3682 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
3683 C11CmpXchg,
3684
3685 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
3686 GNUCmpXchg
3687 } Form = Init;
3688
3689 const unsigned NumForm = GNUCmpXchg + 1;
3690 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
3691 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
3692 // where:
3693 // C is an appropriate type,
3694 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3695 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3696 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3697 // the int parameters are for orderings.
3698
3699 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3700 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3701 "need to update code for modified forms");
3702 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
3703 AtomicExpr::AO__atomic_xor_fetch + 1 ==
3704 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
3705 "need to update code for modified C11 atomics");
3706 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
3707 Op <= AtomicExpr::AO__opencl_atomic_store;
3708 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
3709 Op <= AtomicExpr::AO__hip_atomic_store;
3710 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
3711 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
3712 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
3713 Op <= AtomicExpr::AO__c11_atomic_store) ||
3714 IsOpenCL;
3715 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3716 Op == AtomicExpr::AO__atomic_store_n ||
3717 Op == AtomicExpr::AO__atomic_exchange_n ||
3718 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
3719 Op == AtomicExpr::AO__scoped_atomic_load_n ||
3720 Op == AtomicExpr::AO__scoped_atomic_store_n ||
3721 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
3722 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
3723 // Bit mask for extra allowed value types other than integers for atomic
3724 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
3725 // allow floating point.
3726 enum ArithOpExtraValueType {
3727 AOEVT_None = 0,
3728 AOEVT_Pointer = 1,
3729 AOEVT_FP = 2,
3730 };
3731 unsigned ArithAllows = AOEVT_None;
3732
3733 switch (Op) {
3734 case AtomicExpr::AO__c11_atomic_init:
3735 case AtomicExpr::AO__opencl_atomic_init:
3736 Form = Init;
3737 break;
3738
3739 case AtomicExpr::AO__c11_atomic_load:
3740 case AtomicExpr::AO__opencl_atomic_load:
3741 case AtomicExpr::AO__hip_atomic_load:
3742 case AtomicExpr::AO__atomic_load_n:
3743 case AtomicExpr::AO__scoped_atomic_load_n:
3744 Form = Load;
3745 break;
3746
3747 case AtomicExpr::AO__atomic_load:
3748 case AtomicExpr::AO__scoped_atomic_load:
3749 Form = LoadCopy;
3750 break;
3751
3752 case AtomicExpr::AO__c11_atomic_store:
3753 case AtomicExpr::AO__opencl_atomic_store:
3754 case AtomicExpr::AO__hip_atomic_store:
3755 case AtomicExpr::AO__atomic_store:
3756 case AtomicExpr::AO__atomic_store_n:
3757 case AtomicExpr::AO__scoped_atomic_store:
3758 case AtomicExpr::AO__scoped_atomic_store_n:
3759 Form = Copy;
3760 break;
3761 case AtomicExpr::AO__atomic_fetch_add:
3762 case AtomicExpr::AO__atomic_fetch_sub:
3763 case AtomicExpr::AO__atomic_add_fetch:
3764 case AtomicExpr::AO__atomic_sub_fetch:
3765 case AtomicExpr::AO__scoped_atomic_fetch_add:
3766 case AtomicExpr::AO__scoped_atomic_fetch_sub:
3767 case AtomicExpr::AO__scoped_atomic_add_fetch:
3768 case AtomicExpr::AO__scoped_atomic_sub_fetch:
3769 case AtomicExpr::AO__c11_atomic_fetch_add:
3770 case AtomicExpr::AO__c11_atomic_fetch_sub:
3771 case AtomicExpr::AO__opencl_atomic_fetch_add:
3772 case AtomicExpr::AO__opencl_atomic_fetch_sub:
3773 case AtomicExpr::AO__hip_atomic_fetch_add:
3774 case AtomicExpr::AO__hip_atomic_fetch_sub:
3775 ArithAllows = AOEVT_Pointer | AOEVT_FP;
3776 Form = Arithmetic;
3777 break;
3778 case AtomicExpr::AO__atomic_fetch_max:
3779 case AtomicExpr::AO__atomic_fetch_min:
3780 case AtomicExpr::AO__atomic_max_fetch:
3781 case AtomicExpr::AO__atomic_min_fetch:
3782 case AtomicExpr::AO__scoped_atomic_fetch_max:
3783 case AtomicExpr::AO__scoped_atomic_fetch_min:
3784 case AtomicExpr::AO__scoped_atomic_max_fetch:
3785 case AtomicExpr::AO__scoped_atomic_min_fetch:
3786 case AtomicExpr::AO__c11_atomic_fetch_max:
3787 case AtomicExpr::AO__c11_atomic_fetch_min:
3788 case AtomicExpr::AO__opencl_atomic_fetch_max:
3789 case AtomicExpr::AO__opencl_atomic_fetch_min:
3790 case AtomicExpr::AO__hip_atomic_fetch_max:
3791 case AtomicExpr::AO__hip_atomic_fetch_min:
3792 ArithAllows = AOEVT_FP;
3793 Form = Arithmetic;
3794 break;
3795 case AtomicExpr::AO__c11_atomic_fetch_and:
3796 case AtomicExpr::AO__c11_atomic_fetch_or:
3797 case AtomicExpr::AO__c11_atomic_fetch_xor:
3798 case AtomicExpr::AO__hip_atomic_fetch_and:
3799 case AtomicExpr::AO__hip_atomic_fetch_or:
3800 case AtomicExpr::AO__hip_atomic_fetch_xor:
3801 case AtomicExpr::AO__c11_atomic_fetch_nand:
3802 case AtomicExpr::AO__opencl_atomic_fetch_and:
3803 case AtomicExpr::AO__opencl_atomic_fetch_or:
3804 case AtomicExpr::AO__opencl_atomic_fetch_xor:
3805 case AtomicExpr::AO__atomic_fetch_and:
3806 case AtomicExpr::AO__atomic_fetch_or:
3807 case AtomicExpr::AO__atomic_fetch_xor:
3808 case AtomicExpr::AO__atomic_fetch_nand:
3809 case AtomicExpr::AO__atomic_and_fetch:
3810 case AtomicExpr::AO__atomic_or_fetch:
3811 case AtomicExpr::AO__atomic_xor_fetch:
3812 case AtomicExpr::AO__atomic_nand_fetch:
3813 case AtomicExpr::AO__scoped_atomic_fetch_and:
3814 case AtomicExpr::AO__scoped_atomic_fetch_or:
3815 case AtomicExpr::AO__scoped_atomic_fetch_xor:
3816 case AtomicExpr::AO__scoped_atomic_fetch_nand:
3817 case AtomicExpr::AO__scoped_atomic_and_fetch:
3818 case AtomicExpr::AO__scoped_atomic_or_fetch:
3819 case AtomicExpr::AO__scoped_atomic_xor_fetch:
3820 case AtomicExpr::AO__scoped_atomic_nand_fetch:
3821 Form = Arithmetic;
3822 break;
3823
3824 case AtomicExpr::AO__c11_atomic_exchange:
3825 case AtomicExpr::AO__hip_atomic_exchange:
3826 case AtomicExpr::AO__opencl_atomic_exchange:
3827 case AtomicExpr::AO__atomic_exchange_n:
3828 case AtomicExpr::AO__scoped_atomic_exchange_n:
3829 Form = Xchg;
3830 break;
3831
3832 case AtomicExpr::AO__atomic_exchange:
3833 case AtomicExpr::AO__scoped_atomic_exchange:
3834 Form = GNUXchg;
3835 break;
3836
3837 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3838 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3839 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
3840 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3841 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
3842 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
3843 Form = C11CmpXchg;
3844 break;
3845
3846 case AtomicExpr::AO__atomic_compare_exchange:
3847 case AtomicExpr::AO__atomic_compare_exchange_n:
3848 case AtomicExpr::AO__scoped_atomic_compare_exchange:
3849 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
3850 Form = GNUCmpXchg;
3851 break;
3852 }
3853
3854 unsigned AdjustedNumArgs = NumArgs[Form];
3855 if ((IsOpenCL || IsHIP || IsScoped) &&
3856 Op != AtomicExpr::AO__opencl_atomic_init)
3857 ++AdjustedNumArgs;
3858 // Check we have the right number of arguments.
3859 if (Args.size() < AdjustedNumArgs) {
3860 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
3861 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
3862 << /*is non object*/ 0 << ExprRange;
3863 return ExprError();
3864 } else if (Args.size() > AdjustedNumArgs) {
3865 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
3866 diag::err_typecheck_call_too_many_args)
3867 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
3868 << /*is non object*/ 0 << ExprRange;
3869 return ExprError();
3870 }
3871
3872 // Inspect the first argument of the atomic operation.
3873 Expr *Ptr = Args[0];
3875 if (ConvertedPtr.isInvalid())
3876 return ExprError();
3877
3878 Ptr = ConvertedPtr.get();
3879 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3880 if (!pointerType) {
3881 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
3882 << Ptr->getType() << 0 << Ptr->getSourceRange();
3883 return ExprError();
3884 }
3885
3886 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3887 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3888 QualType ValType = AtomTy; // 'C'
3889 if (IsC11) {
3890 if (!AtomTy->isAtomicType()) {
3891 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
3892 << Ptr->getType() << Ptr->getSourceRange();
3893 return ExprError();
3894 }
3895 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
3897 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
3898 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3899 << Ptr->getSourceRange();
3900 return ExprError();
3901 }
3902 ValType = AtomTy->castAs<AtomicType>()->getValueType();
3903 } else if (Form != Load && Form != LoadCopy) {
3904 if (ValType.isConstQualified()) {
3905 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
3906 << Ptr->getType() << Ptr->getSourceRange();
3907 return ExprError();
3908 }
3909 }
3910
3911 // Pointer to object of size zero is not allowed.
3912 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
3913 diag::err_incomplete_type))
3914 return ExprError();
3915 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
3916 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
3917 << Ptr->getType() << 1 << Ptr->getSourceRange();
3918 return ExprError();
3919 }
3920
3921 // For an arithmetic operation, the implied arithmetic must be well-formed.
3922 if (Form == Arithmetic) {
3923 // GCC does not enforce these rules for GNU atomics, but we do to help catch
3924 // trivial type errors.
3925 auto IsAllowedValueType = [&](QualType ValType,
3926 unsigned AllowedType) -> bool {
3927 if (ValType->isIntegerType())
3928 return true;
3929 if (ValType->isPointerType())
3930 return AllowedType & AOEVT_Pointer;
3931 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
3932 return false;
3933 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
3934 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
3936 &llvm::APFloat::x87DoubleExtended())
3937 return false;
3938 return true;
3939 };
3940 if (!IsAllowedValueType(ValType, ArithAllows)) {
3941 auto DID = ArithAllows & AOEVT_FP
3942 ? (ArithAllows & AOEVT_Pointer
3943 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
3944 : diag::err_atomic_op_needs_atomic_int_or_fp)
3945 : diag::err_atomic_op_needs_atomic_int;
3946 Diag(ExprRange.getBegin(), DID)
3947 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3948 return ExprError();
3949 }
3950 if (IsC11 && ValType->isPointerType() &&
3952 diag::err_incomplete_type)) {
3953 return ExprError();
3954 }
3955 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3956 // For __atomic_*_n operations, the value type must be a scalar integral or
3957 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
3958 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3959 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3960 return ExprError();
3961 }
3962
3963 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3964 !AtomTy->isScalarType()) {
3965 // For GNU atomics, require a trivially-copyable type. This is not part of
3966 // the GNU atomics specification but we enforce it for consistency with
3967 // other atomics which generally all require a trivially-copyable type. This
3968 // is because atomics just copy bits.
3969 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
3970 << Ptr->getType() << Ptr->getSourceRange();
3971 return ExprError();
3972 }
3973
3974 switch (ValType.getObjCLifetime()) {
3977 // okay
3978 break;
3979
3983 // FIXME: Can this happen? By this point, ValType should be known
3984 // to be trivially copyable.
3985 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
3986 << ValType << Ptr->getSourceRange();
3987 return ExprError();
3988 }
3989
3990 // All atomic operations have an overload which takes a pointer to a volatile
3991 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
3992 // into the result or the other operands. Similarly atomic_load takes a
3993 // pointer to a const 'A'.
3994 ValType.removeLocalVolatile();
3995 ValType.removeLocalConst();
3996 QualType ResultType = ValType;
3997 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3998 Form == Init)
3999 ResultType = Context.VoidTy;
4000 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4001 ResultType = Context.BoolTy;
4002
4003 // The type of a parameter passed 'by value'. In the GNU atomics, such
4004 // arguments are actually passed as pointers.
4005 QualType ByValType = ValType; // 'CP'
4006 bool IsPassedByAddress = false;
4007 if (!IsC11 && !IsHIP && !IsN) {
4008 ByValType = Ptr->getType();
4009 IsPassedByAddress = true;
4010 }
4011
4012 SmallVector<Expr *, 5> APIOrderedArgs;
4013 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4014 APIOrderedArgs.push_back(Args[0]);
4015 switch (Form) {
4016 case Init:
4017 case Load:
4018 APIOrderedArgs.push_back(Args[1]); // Val1/Order
4019 break;
4020 case LoadCopy:
4021 case Copy:
4022 case Arithmetic:
4023 case Xchg:
4024 APIOrderedArgs.push_back(Args[2]); // Val1
4025 APIOrderedArgs.push_back(Args[1]); // Order
4026 break;
4027 case GNUXchg:
4028 APIOrderedArgs.push_back(Args[2]); // Val1
4029 APIOrderedArgs.push_back(Args[3]); // Val2
4030 APIOrderedArgs.push_back(Args[1]); // Order
4031 break;
4032 case C11CmpXchg:
4033 APIOrderedArgs.push_back(Args[2]); // Val1
4034 APIOrderedArgs.push_back(Args[4]); // Val2
4035 APIOrderedArgs.push_back(Args[1]); // Order
4036 APIOrderedArgs.push_back(Args[3]); // OrderFail
4037 break;
4038 case GNUCmpXchg:
4039 APIOrderedArgs.push_back(Args[2]); // Val1
4040 APIOrderedArgs.push_back(Args[4]); // Val2
4041 APIOrderedArgs.push_back(Args[5]); // Weak
4042 APIOrderedArgs.push_back(Args[1]); // Order
4043 APIOrderedArgs.push_back(Args[3]); // OrderFail
4044 break;
4045 }
4046 } else
4047 APIOrderedArgs.append(Args.begin(), Args.end());
4048
4049 // The first argument's non-CV pointer type is used to deduce the type of
4050 // subsequent arguments, except for:
4051 // - weak flag (always converted to bool)
4052 // - memory order (always converted to int)
4053 // - scope (always converted to int)
4054 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4055 QualType Ty;
4056 if (i < NumVals[Form] + 1) {
4057 switch (i) {
4058 case 0:
4059 // The first argument is always a pointer. It has a fixed type.
4060 // It is always dereferenced, a nullptr is undefined.
4061 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4062 // Nothing else to do: we already know all we want about this pointer.
4063 continue;
4064 case 1:
4065 // The second argument is the non-atomic operand. For arithmetic, this
4066 // is always passed by value, and for a compare_exchange it is always
4067 // passed by address. For the rest, GNU uses by-address and C11 uses
4068 // by-value.
4069 assert(Form != Load);
4070 if (Form == Arithmetic && ValType->isPointerType())
4072 else if (Form == Init || Form == Arithmetic)
4073 Ty = ValType;
4074 else if (Form == Copy || Form == Xchg) {
4075 if (IsPassedByAddress) {
4076 // The value pointer is always dereferenced, a nullptr is undefined.
4077 CheckNonNullArgument(*this, APIOrderedArgs[i],
4078 ExprRange.getBegin());
4079 }
4080 Ty = ByValType;
4081 } else {
4082 Expr *ValArg = APIOrderedArgs[i];
4083 // The value pointer is always dereferenced, a nullptr is undefined.
4084 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4086 // Keep address space of non-atomic pointer type.
4087 if (const PointerType *PtrTy =
4088 ValArg->getType()->getAs<PointerType>()) {
4089 AS = PtrTy->getPointeeType().getAddressSpace();
4090 }
4093 }
4094 break;
4095 case 2:
4096 // The third argument to compare_exchange / GNU exchange is the desired
4097 // value, either by-value (for the C11 and *_n variant) or as a pointer.
4098 if (IsPassedByAddress)
4099 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4100 Ty = ByValType;
4101 break;
4102 case 3:
4103 // The fourth argument to GNU compare_exchange is a 'weak' flag.
4104 Ty = Context.BoolTy;
4105 break;
4106 }
4107 } else {
4108 // The order(s) and scope are always converted to int.
4109 Ty = Context.IntTy;
4110 }
4111
4112 InitializedEntity Entity =
4114 ExprResult Arg = APIOrderedArgs[i];
4115 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4116 if (Arg.isInvalid())
4117 return true;
4118 APIOrderedArgs[i] = Arg.get();
4119 }
4120
4121 // Permute the arguments into a 'consistent' order.
4122 SmallVector<Expr*, 5> SubExprs;
4123 SubExprs.push_back(Ptr);
4124 switch (Form) {
4125 case Init:
4126 // Note, AtomicExpr::getVal1() has a special case for this atomic.
4127 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4128 break;
4129 case Load:
4130 SubExprs.push_back(APIOrderedArgs[1]); // Order
4131 break;
4132 case LoadCopy:
4133 case Copy:
4134 case Arithmetic:
4135 case Xchg:
4136 SubExprs.push_back(APIOrderedArgs[2]); // Order
4137 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4138 break;
4139 case GNUXchg:
4140 // Note, AtomicExpr::getVal2() has a special case for this atomic.
4141 SubExprs.push_back(APIOrderedArgs[3]); // Order
4142 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4143 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4144 break;
4145 case C11CmpXchg:
4146 SubExprs.push_back(APIOrderedArgs[3]); // Order
4147 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4148 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4149 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4150 break;
4151 case GNUCmpXchg:
4152 SubExprs.push_back(APIOrderedArgs[4]); // Order
4153 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4154 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4155 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4156 SubExprs.push_back(APIOrderedArgs[3]); // Weak
4157 break;
4158 }
4159
4160 // If the memory orders are constants, check they are valid.
4161 if (SubExprs.size() >= 2 && Form != Init) {
4162 std::optional<llvm::APSInt> Success =
4163 SubExprs[1]->getIntegerConstantExpr(Context);
4164 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
4165 Diag(SubExprs[1]->getBeginLoc(),
4166 diag::warn_atomic_op_has_invalid_memory_order)
4167 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
4168 << SubExprs[1]->getSourceRange();
4169 }
4170 if (SubExprs.size() >= 5) {
4171 if (std::optional<llvm::APSInt> Failure =
4172 SubExprs[3]->getIntegerConstantExpr(Context)) {
4173 if (!llvm::is_contained(
4174 {llvm::AtomicOrderingCABI::relaxed,
4175 llvm::AtomicOrderingCABI::consume,
4176 llvm::AtomicOrderingCABI::acquire,
4177 llvm::AtomicOrderingCABI::seq_cst},
4178 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
4179 Diag(SubExprs[3]->getBeginLoc(),
4180 diag::warn_atomic_op_has_invalid_memory_order)
4181 << /*failure=*/2 << SubExprs[3]->getSourceRange();
4182 }
4183 }
4184 }
4185 }
4186
4187 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4188 auto *Scope = Args[Args.size() - 1];
4189 if (std::optional<llvm::APSInt> Result =
4190 Scope->getIntegerConstantExpr(Context)) {
4191 if (!ScopeModel->isValid(Result->getZExtValue()))
4192 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4193 << Scope->getSourceRange();
4194 }
4195 SubExprs.push_back(Scope);
4196 }
4197
4198 AtomicExpr *AE = new (Context)
4199 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4200
4201 if ((Op == AtomicExpr::AO__c11_atomic_load ||
4202 Op == AtomicExpr::AO__c11_atomic_store ||
4203 Op == AtomicExpr::AO__opencl_atomic_load ||
4204 Op == AtomicExpr::AO__hip_atomic_load ||
4205 Op == AtomicExpr::AO__opencl_atomic_store ||
4206 Op == AtomicExpr::AO__hip_atomic_store) &&
4208 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4209 << ((Op == AtomicExpr::AO__c11_atomic_load ||
4210 Op == AtomicExpr::AO__opencl_atomic_load ||
4211 Op == AtomicExpr::AO__hip_atomic_load)
4212 ? 0
4213 : 1);
4214
4215 if (ValType->isBitIntType()) {
4216 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
4217 return ExprError();
4218 }
4219
4220 return AE;
4221}
4222
4223/// checkBuiltinArgument - Given a call to a builtin function, perform
4224/// normal type-checking on the given argument, updating the call in
4225/// place. This is useful when a builtin function requires custom
4226/// type-checking for some of its arguments but not necessarily all of
4227/// them.
4228///
4229/// Returns true on error.
4230static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4231 FunctionDecl *Fn = E->getDirectCallee();
4232 assert(Fn && "builtin call without direct callee!");
4233
4234 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4235 InitializedEntity Entity =
4237
4238 ExprResult Arg = E->getArg(ArgIndex);
4239 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4240 if (Arg.isInvalid())
4241 return true;
4242
4243 E->setArg(ArgIndex, Arg.get());
4244 return false;
4245}
4246
4247ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
4248 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4249 Expr *Callee = TheCall->getCallee();
4250 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4251 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4252
4253 // Ensure that we have at least one argument to do type inference from.
4254 if (TheCall->getNumArgs() < 1) {
4255 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4256 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
4257 << Callee->getSourceRange();
4258 return ExprError();
4259 }
4260
4261 // Inspect the first argument of the atomic builtin. This should always be
4262 // a pointer type, whose element is an integral scalar or pointer type.
4263 // Because it is a pointer type, we don't have to worry about any implicit
4264 // casts here.
4265 // FIXME: We don't allow floating point scalars as input.
4266 Expr *FirstArg = TheCall->getArg(0);
4267 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4268 if (FirstArgResult.isInvalid())
4269 return ExprError();
4270 FirstArg = FirstArgResult.get();
4271 TheCall->setArg(0, FirstArg);
4272
4273 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4274 if (!pointerType) {
4275 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4276 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4277 return ExprError();
4278 }
4279
4280 QualType ValType = pointerType->getPointeeType();
4281 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4282 !ValType->isBlockPointerType()) {
4283 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4284 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4285 return ExprError();
4286 }
4287
4288 if (ValType.isConstQualified()) {
4289 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4290 << FirstArg->getType() << FirstArg->getSourceRange();
4291 return ExprError();
4292 }
4293
4294 switch (ValType.getObjCLifetime()) {
4297 // okay
4298 break;
4299
4303 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4304 << ValType << FirstArg->getSourceRange();
4305 return ExprError();
4306 }
4307
4308 // Strip any qualifiers off ValType.
4309 ValType = ValType.getUnqualifiedType();
4310
4311 // The majority of builtins return a value, but a few have special return
4312 // types, so allow them to override appropriately below.
4313 QualType ResultType = ValType;
4314
4315 // We need to figure out which concrete builtin this maps onto. For example,
4316 // __sync_fetch_and_add with a 2 byte object turns into
4317 // __sync_fetch_and_add_2.
4318#define BUILTIN_ROW(x) \
4319 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4320 Builtin::BI##x##_8, Builtin::BI##x##_16 }
4321
4322 static const unsigned BuiltinIndices[][5] = {
4323 BUILTIN_ROW(__sync_fetch_and_add),
4324 BUILTIN_ROW(__sync_fetch_and_sub),
4325 BUILTIN_ROW(__sync_fetch_and_or),
4326 BUILTIN_ROW(__sync_fetch_and_and),
4327 BUILTIN_ROW(__sync_fetch_and_xor),
4328 BUILTIN_ROW(__sync_fetch_and_nand),
4329
4330 BUILTIN_ROW(__sync_add_and_fetch),
4331 BUILTIN_ROW(__sync_sub_and_fetch),
4332 BUILTIN_ROW(__sync_and_and_fetch),
4333 BUILTIN_ROW(__sync_or_and_fetch),
4334 BUILTIN_ROW(__sync_xor_and_fetch),
4335 BUILTIN_ROW(__sync_nand_and_fetch),
4336
4337 BUILTIN_ROW(__sync_val_compare_and_swap),
4338 BUILTIN_ROW(__sync_bool_compare_and_swap),
4339 BUILTIN_ROW(__sync_lock_test_and_set),
4340 BUILTIN_ROW(__sync_lock_release),
4341 BUILTIN_ROW(__sync_swap)
4342 };
4343#undef BUILTIN_ROW
4344
4345 // Determine the index of the size.
4346 unsigned SizeIndex;
4347 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4348 case 1: SizeIndex = 0; break;
4349 case 2: SizeIndex = 1; break;
4350 case 4: SizeIndex = 2; break;
4351 case 8: SizeIndex = 3; break;
4352 case 16: SizeIndex = 4; break;
4353 default:
4354 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4355 << FirstArg->getType() << FirstArg->getSourceRange();
4356 return ExprError();
4357 }
4358
4359 // Each of these builtins has one pointer argument, followed by some number of
4360 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4361 // that we ignore. Find out which row of BuiltinIndices to read from as well
4362 // as the number of fixed args.
4363 unsigned BuiltinID = FDecl->getBuiltinID();
4364 unsigned BuiltinIndex, NumFixed = 1;
4365 bool WarnAboutSemanticsChange = false;
4366 switch (BuiltinID) {
4367 default: llvm_unreachable("Unknown overloaded atomic builtin!");
4368 case Builtin::BI__sync_fetch_and_add:
4369 case Builtin::BI__sync_fetch_and_add_1:
4370 case Builtin::BI__sync_fetch_and_add_2:
4371 case Builtin::BI__sync_fetch_and_add_4:
4372 case Builtin::BI__sync_fetch_and_add_8:
4373 case Builtin::BI__sync_fetch_and_add_16:
4374 BuiltinIndex = 0;
4375 break;
4376
4377 case Builtin::BI__sync_fetch_and_sub:
4378 case Builtin::BI__sync_fetch_and_sub_1:
4379 case Builtin::BI__sync_fetch_and_sub_2:
4380 case Builtin::BI__sync_fetch_and_sub_4:
4381 case Builtin::BI__sync_fetch_and_sub_8:
4382 case Builtin::BI__sync_fetch_and_sub_16:
4383 BuiltinIndex = 1;
4384 break;
4385
4386 case Builtin::BI__sync_fetch_and_or:
4387 case Builtin::BI__sync_fetch_and_or_1:
4388 case Builtin::BI__sync_fetch_and_or_2:
4389 case Builtin::BI__sync_fetch_and_or_4:
4390 case Builtin::BI__sync_fetch_and_or_8:
4391 case Builtin::BI__sync_fetch_and_or_16:
4392 BuiltinIndex = 2;
4393 break;
4394
4395 case Builtin::BI__sync_fetch_and_and:
4396 case Builtin::BI__sync_fetch_and_and_1:
4397 case Builtin::BI__sync_fetch_and_and_2:
4398 case Builtin::BI__sync_fetch_and_and_4:
4399 case Builtin::BI__sync_fetch_and_and_8:
4400 case Builtin::BI__sync_fetch_and_and_16:
4401 BuiltinIndex = 3;
4402 break;
4403
4404 case Builtin::BI__sync_fetch_and_xor:
4405 case Builtin::BI__sync_fetch_and_xor_1:
4406 case Builtin::BI__sync_fetch_and_xor_2:
4407 case Builtin::BI__sync_fetch_and_xor_4:
4408 case Builtin::BI__sync_fetch_and_xor_8:
4409 case Builtin::BI__sync_fetch_and_xor_16:
4410 BuiltinIndex = 4;
4411 break;
4412
4413 case Builtin::BI__sync_fetch_and_nand:
4414 case Builtin::BI__sync_fetch_and_nand_1:
4415 case Builtin::BI__sync_fetch_and_nand_2:
4416 case Builtin::BI__sync_fetch_and_nand_4:
4417 case Builtin::BI__sync_fetch_and_nand_8:
4418 case Builtin::BI__sync_fetch_and_nand_16:
4419 BuiltinIndex = 5;
4420 WarnAboutSemanticsChange = true;
4421 break;
4422
4423 case Builtin::BI__sync_add_and_fetch:
4424 case Builtin::BI__sync_add_and_fetch_1:
4425 case Builtin::BI__sync_add_and_fetch_2:
4426 case Builtin::BI__sync_add_and_fetch_4:
4427 case Builtin::BI__sync_add_and_fetch_8:
4428 case Builtin::BI__sync_add_and_fetch_16:
4429 BuiltinIndex = 6;
4430 break;
4431
4432 case Builtin::BI__sync_sub_and_fetch:
4433 case Builtin::BI__sync_sub_and_fetch_1:
4434 case Builtin::BI__sync_sub_and_fetch_2:
4435 case Builtin::BI__sync_sub_and_fetch_4:
4436 case Builtin::BI__sync_sub_and_fetch_8:
4437 case Builtin::BI__sync_sub_and_fetch_16:
4438 BuiltinIndex = 7;
4439 break;
4440
4441 case Builtin::BI__sync_and_and_fetch:
4442 case Builtin::BI__sync_and_and_fetch_1:
4443 case Builtin::BI__sync_and_and_fetch_2:
4444 case Builtin::BI__sync_and_and_fetch_4:
4445 case Builtin::BI__sync_and_and_fetch_8:
4446 case Builtin::BI__sync_and_and_fetch_16:
4447 BuiltinIndex = 8;
4448 break;
4449
4450 case Builtin::BI__sync_or_and_fetch:
4451 case Builtin::BI__sync_or_and_fetch_1:
4452 case Builtin::BI__sync_or_and_fetch_2:
4453 case Builtin::BI__sync_or_and_fetch_4:
4454 case Builtin::BI__sync_or_and_fetch_8:
4455 case Builtin::BI__sync_or_and_fetch_16:
4456 BuiltinIndex = 9;
4457 break;
4458
4459 case Builtin::BI__sync_xor_and_fetch:
4460 case Builtin::BI__sync_xor_and_fetch_1:
4461 case Builtin::BI__sync_xor_and_fetch_2:
4462 case Builtin::BI__sync_xor_and_fetch_4:
4463 case Builtin::BI__sync_xor_and_fetch_8:
4464 case Builtin::BI__sync_xor_and_fetch_16:
4465 BuiltinIndex = 10;
4466 break;
4467
4468 case Builtin::BI__sync_nand_and_fetch:
4469 case Builtin::BI__sync_nand_and_fetch_1:
4470 case Builtin::BI__sync_nand_and_fetch_2:
4471 case Builtin::BI__sync_nand_and_fetch_4:
4472 case Builtin::BI__sync_nand_and_fetch_8:
4473 case Builtin::BI__sync_nand_and_fetch_16:
4474 BuiltinIndex = 11;
4475 WarnAboutSemanticsChange = true;
4476 break;
4477
4478 case Builtin::BI__sync_val_compare_and_swap:
4479 case Builtin::BI__sync_val_compare_and_swap_1:
4480 case Builtin::BI__sync_val_compare_and_swap_2:
4481 case Builtin::BI__sync_val_compare_and_swap_4:
4482 case Builtin::BI__sync_val_compare_and_swap_8:
4483 case Builtin::BI__sync_val_compare_and_swap_16:
4484 BuiltinIndex = 12;
4485 NumFixed = 2;
4486 break;
4487
4488 case Builtin::BI__sync_bool_compare_and_swap:
4489 case Builtin::BI__sync_bool_compare_and_swap_1:
4490 case Builtin::BI__sync_bool_compare_and_swap_2:
4491 case Builtin::BI__sync_bool_compare_and_swap_4:
4492 case Builtin::BI__sync_bool_compare_and_swap_8:
4493 case Builtin::BI__sync_bool_compare_and_swap_16:
4494 BuiltinIndex = 13;
4495 NumFixed = 2;
4496 ResultType = Context.BoolTy;
4497 break;
4498
4499 case Builtin::BI__sync_lock_test_and_set:
4500 case Builtin::BI__sync_lock_test_and_set_1:
4501 case Builtin::BI__sync_lock_test_and_set_2:
4502 case Builtin::BI__sync_lock_test_and_set_4:
4503 case Builtin::BI__sync_lock_test_and_set_8:
4504 case Builtin::BI__sync_lock_test_and_set_16:
4505 BuiltinIndex = 14;
4506 break;
4507
4508 case Builtin::BI__sync_lock_release:
4509 case Builtin::BI__sync_lock_release_1:
4510 case Builtin::BI__sync_lock_release_2:
4511 case Builtin::BI__sync_lock_release_4:
4512 case Builtin::BI__sync_lock_release_8:
4513 case Builtin::BI__sync_lock_release_16:
4514 BuiltinIndex = 15;
4515 NumFixed = 0;
4516 ResultType = Context.VoidTy;
4517 break;
4518
4519 case Builtin::BI__sync_swap:
4520 case Builtin::BI__sync_swap_1:
4521 case Builtin::BI__sync_swap_2:
4522 case Builtin::BI__sync_swap_4:
4523 case Builtin::BI__sync_swap_8:
4524 case Builtin::BI__sync_swap_16:
4525 BuiltinIndex = 16;
4526 break;
4527 }
4528
4529 // Now that we know how many fixed arguments we expect, first check that we
4530 // have at least that many.
4531 if (TheCall->getNumArgs() < 1+NumFixed) {
4532 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4533 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
4534 << Callee->getSourceRange();
4535 return ExprError();
4536 }
4537
4538 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
4539 << Callee->getSourceRange();
4540
4541 if (WarnAboutSemanticsChange) {
4542 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
4543 << Callee->getSourceRange();
4544 }
4545
4546 // Get the decl for the concrete builtin from this, we can tell what the
4547 // concrete integer type we should convert to is.
4548 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
4549 StringRef NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
4550 FunctionDecl *NewBuiltinDecl;
4551 if (NewBuiltinID == BuiltinID)
4552 NewBuiltinDecl = FDecl;
4553 else {
4554 // Perform builtin lookup to avoid redeclaring it.
4555 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
4556 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
4557 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
4558 assert(Res.getFoundDecl());
4559 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
4560 if (!NewBuiltinDecl)
4561 return ExprError();
4562 }
4563
4564 // The first argument --- the pointer --- has a fixed type; we
4565 // deduce the types of the rest of the arguments accordingly. Walk
4566 // the remaining arguments, converting them to the deduced value type.
4567 for (unsigned i = 0; i != NumFixed; ++i) {
4568 ExprResult Arg = TheCall->getArg(i+1);
4569
4570 // GCC does an implicit conversion to the pointer or integer ValType. This
4571 // can fail in some cases (1i -> int**), check for this error case now.
4572 // Initialize the argument.
4574 ValType, /*consume*/ false);
4575 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4576 if (Arg.isInvalid())
4577 return ExprError();
4578
4579 // Okay, we have something that *can* be converted to the right type. Check
4580 // to see if there is a potentially weird extension going on here. This can
4581 // happen when you do an atomic operation on something like an char* and
4582 // pass in 42. The 42 gets converted to char. This is even more strange
4583 // for things like 45.123 -> char, etc.
4584 // FIXME: Do this check.
4585 TheCall->setArg(i+1, Arg.get());
4586 }
4587
4588 // Create a new DeclRefExpr to refer to the new decl.
4590 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
4591 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
4592 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
4593
4594 // Set the callee in the CallExpr.
4595 // FIXME: This loses syntactic information.
4596 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
4597 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
4598 CK_BuiltinFnToFnPtr);
4599 TheCall->setCallee(PromotedCall.get());
4600
4601 // Change the result type of the call to match the original value type. This
4602 // is arbitrary, but the codegen for these builtins ins design to handle it
4603 // gracefully.
4604 TheCall->setType(ResultType);
4605
4606 // Prohibit problematic uses of bit-precise integer types with atomic
4607 // builtins. The arguments would have already been converted to the first
4608 // argument's type, so only need to check the first argument.
4609 const auto *BitIntValType = ValType->getAs<BitIntType>();
4610 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
4611 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
4612 return ExprError();
4613 }
4614
4615 return TheCallResult;
4616}
4617
4618ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
4619 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
4620 DeclRefExpr *DRE =
4621 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4622 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4623 unsigned BuiltinID = FDecl->getBuiltinID();
4624 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
4625 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
4626 "Unexpected nontemporal load/store builtin!");
4627 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
4628 unsigned numArgs = isStore ? 2 : 1;
4629
4630 // Ensure that we have the proper number of arguments.
4631 if (checkArgCount(TheCall, numArgs))
4632 return ExprError();
4633
4634 // Inspect the last argument of the nontemporal builtin. This should always
4635 // be a pointer type, from which we imply the type of the memory access.
4636 // Because it is a pointer type, we don't have to worry about any implicit
4637 // casts here.
4638 Expr *PointerArg = TheCall->getArg(numArgs - 1);
4639 ExprResult PointerArgResult =
4641
4642 if (PointerArgResult.isInvalid())
4643 return ExprError();
4644 PointerArg = PointerArgResult.get();
4645 TheCall->setArg(numArgs - 1, PointerArg);
4646
4647 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
4648 if (!pointerType) {
4649 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
4650 << PointerArg->getType() << PointerArg->getSourceRange();
4651 return ExprError();
4652 }
4653
4654 QualType ValType = pointerType->getPointeeType();
4655
4656 // Strip any qualifiers off ValType.
4657 ValType = ValType.getUnqualifiedType();
4658 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4659 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
4660 !ValType->isVectorType()) {
4661 Diag(DRE->getBeginLoc(),
4662 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
4663 << PointerArg->getType() << PointerArg->getSourceRange();
4664 return ExprError();
4665 }
4666
4667 if (!isStore) {
4668 TheCall->setType(ValType);
4669 return TheCallResult;
4670 }
4671
4672 ExprResult ValArg = TheCall->getArg(0);
4674 Context, ValType, /*consume*/ false);
4675 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
4676 if (ValArg.isInvalid())
4677 return ExprError();
4678
4679 TheCall->setArg(0, ValArg.get());
4680 TheCall->setType(Context.VoidTy);
4681 return TheCallResult;
4682}
4683
4684/// CheckObjCString - Checks that the format string argument to the os_log()
4685/// and os_trace() functions is correct, and converts it to const char *.
4686ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
4687 Arg = Arg->IgnoreParenCasts();
4688 auto *Literal = dyn_cast<StringLiteral>(Arg);
4689 if (!Literal) {
4690 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
4691 Literal = ObjcLiteral->getString();
4692 }
4693 }
4694
4695 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
4696 return ExprError(
4697 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
4698 << Arg->getSourceRange());
4699 }
4700
4701 ExprResult Result(Literal);
4703 InitializedEntity Entity =
4706 return Result;
4707}
4708
4709/// Check that the user is calling the appropriate va_start builtin for the
4710/// target and calling convention.
4711static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
4712 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
4713 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
4714 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
4715 TT.getArch() == llvm::Triple::aarch64_32);
4716 bool IsWindows = TT.isOSWindows();
4717 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
4718 if (IsX64 || IsAArch64) {
4719 CallingConv CC = CC_C;
4720 if (const FunctionDecl *FD = S.getCurFunctionDecl())
4721 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
4722 if (IsMSVAStart) {
4723 // Don't allow this in System V ABI functions.
4724 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
4725 return S.Diag(Fn->getBeginLoc(),
4726 diag::err_ms_va_start_used_in_sysv_function);
4727 } else {
4728 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
4729 // On x64 Windows, don't allow this in System V ABI functions.
4730 // (Yes, that means there's no corresponding way to support variadic
4731 // System V ABI functions on Windows.)
4732 if ((IsWindows && CC == CC_X86_64SysV) ||
4733 (!IsWindows && CC == CC_Win64))
4734 return S.Diag(Fn->getBeginLoc(),
4735 diag::err_va_start_used_in_wrong_abi_function)
4736 << !IsWindows;
4737 }
4738 return false;
4739 }
4740
4741 if (IsMSVAStart)
4742 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
4743 return false;
4744}
4745
4747 ParmVarDecl **LastParam = nullptr) {
4748 // Determine whether the current function, block, or obj-c method is variadic
4749 // and get its parameter list.
4750 bool IsVariadic = false;
4752 DeclContext *Caller = S.CurContext;
4753 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
4754 IsVariadic = Block->isVariadic();
4755 Params = Block->parameters();
4756 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
4757 IsVariadic = FD->isVariadic();
4758 Params = FD->parameters();
4759 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
4760 IsVariadic = MD->isVariadic();
4761 // FIXME: This isn't correct for methods (results in bogus warning).
4762 Params = MD->parameters();
4763 } else if (isa<CapturedDecl>(Caller)) {
4764 // We don't support va_start in a CapturedDecl.
4765 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
4766 return true;
4767 } else {
4768 // This must be some other declcontext that parses exprs.
4769 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
4770 return true;
4771 }
4772
4773 if (!IsVariadic) {
4774 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
4775 return true;
4776 }
4777
4778 if (LastParam)
4779 *LastParam = Params.empty() ? nullptr : Params.back();
4780
4781 return false;
4782}
4783
4784bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
4785 Expr *Fn = TheCall->getCallee();
4786
4787 if (checkVAStartABI(*this, BuiltinID, Fn))
4788 return true;
4789
4790 // In C23 mode, va_start only needs one argument. However, the builtin still
4791 // requires two arguments (which matches the behavior of the GCC builtin),
4792 // <stdarg.h> passes `0` as the second argument in C23 mode.
4793 if (checkArgCount(TheCall, 2))
4794 return true;
4795
4796 // Type-check the first argument normally.
4797 if (checkBuiltinArgument(*this, TheCall, 0))
4798 return true;
4799
4800 // Check that the current function is variadic, and get its last parameter.
4801 ParmVarDecl *LastParam;
4802 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
4803 return true;
4804
4805 // Verify that the second argument to the builtin is the last argument of the
4806 // current function or method. In C23 mode, if the second argument is an
4807 // integer constant expression with value 0, then we don't bother with this
4808 // check.
4809 bool SecondArgIsLastNamedArgument = false;
4810 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
4811 if (std::optional<llvm::APSInt> Val =
4813 Val && LangOpts.C23 && *Val == 0)
4814 return false;
4815
4816 // These are valid if SecondArgIsLastNamedArgument is false after the next
4817 // block.
4818 QualType Type;
4819 SourceLocation ParamLoc;
4820 bool IsCRegister = false;
4821
4822 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
4823 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
4824 SecondArgIsLastNamedArgument = PV == LastParam;
4825
4826 Type = PV->getType();
4827 ParamLoc = PV->getLocation();
4828 IsCRegister =
4829 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
4830 }
4831 }
4832
4833 if (!SecondArgIsLastNamedArgument)
4834 Diag(TheCall->getArg(1)->getBeginLoc(),
4835 diag::warn_second_arg_of_va_start_not_last_named_param);
4836 else if (IsCRegister || Type->isReferenceType() ||
4837 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4838 // Promotable integers are UB, but enumerations need a bit of
4839 // extra checking to see what their promotable type actually is.
4840 if (!Context.isPromotableIntegerType(Type))
4841 return false;
4842 if (!Type->isEnumeralType())
4843 return true;
4844 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
4845 return !(ED &&
4846 Context.typesAreCompatible(ED->getPromotionType(), Type));
4847 }()) {
4848 unsigned Reason = 0;
4849 if (Type->isReferenceType()) Reason = 1;
4850 else if (IsCRegister) Reason = 2;
4851 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
4852 Diag(ParamLoc, diag::note_parameter_type) << Type;
4853 }
4854
4855 return false;
4856}
4857
4858bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
4859 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
4860 const LangOptions &LO = getLangOpts();
4861
4862 if (LO.CPlusPlus)
4863 return Arg->getType()
4865 .getTypePtr()
4866 ->getPointeeType()
4868
4869 // In C, allow aliasing through `char *`, this is required for AArch64 at
4870 // least.
4871 return true;
4872 };
4873
4874 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4875 // const char *named_addr);
4876
4877 Expr *Func = Call->getCallee();
4878
4879 if (Call->getNumArgs() < 3)
4880 return Diag(Call->getEndLoc(),
4881 diag::err_typecheck_call_too_few_args_at_least)
4882 << 0 /*function call*/ << 3 << Call->getNumArgs()
4883 << /*is non object*/ 0;
4884
4885 // Type-check the first argument normally.
4886 if (checkBuiltinArgument(*this, Call, 0))
4887 return true;
4888
4889 // Check that the current function is variadic.
4891 return true;
4892
4893 // __va_start on Windows does not validate the parameter qualifiers
4894
4895 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4896 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4897
4898 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4899 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4900
4901 const QualType &ConstCharPtrTy =
4903 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
4904 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
4905 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
4906 << 0 /* qualifier difference */
4907 << 3 /* parameter mismatch */
4908 << 2 << Arg1->getType() << ConstCharPtrTy;
4909
4910 const QualType SizeTy = Context.getSizeType();
4911 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4912 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
4913 << Arg2->getType() << SizeTy << 1 /* different class */
4914 << 0 /* qualifier difference */
4915 << 3 /* parameter mismatch */
4916 << 3 << Arg2->getType() << SizeTy;
4917
4918 return false;
4919}
4920
4921bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
4922 if (checkArgCount(TheCall, 2))
4923 return true;
4924
4925 if (BuiltinID == Builtin::BI__builtin_isunordered &&
4926 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
4927 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
4928 << 1 << 0 << TheCall->getSourceRange();
4929
4930 ExprResult OrigArg0 = TheCall->getArg(0);
4931 ExprResult OrigArg1 = TheCall->getArg(1);
4932
4933 // Do standard promotions between the two arguments, returning their common
4934 // type.
4936 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
4937 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4938 return true;
4939
4940 // Make sure any conversions are pushed back into the call; this is
4941 // type safe since unordered compare builtins are declared as "_Bool
4942 // foo(...)".
4943 TheCall->setArg(0, OrigArg0.get());
4944 TheCall->setArg(1, OrigArg1.get());
4945
4946 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
4947 return false;
4948
4949 // If the common type isn't a real floating type, then the arguments were
4950 // invalid for this operation.
4951 if (Res.isNull() || !Res->isRealFloatingType())
4952 return Diag(OrigArg0.get()->getBeginLoc(),
4953 diag::err_typecheck_call_invalid_ordered_compare)
4954 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4955 << SourceRange(OrigArg0.get()->getBeginLoc(),
4956 OrigArg1.get()->getEndLoc());
4957
4958 return false;
4959}
4960
4961bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
4962 unsigned BuiltinID) {
4963 if (checkArgCount(TheCall, NumArgs))
4964 return true;
4965
4967 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
4968 BuiltinID == Builtin::BI__builtin_isinf ||
4969 BuiltinID == Builtin::BI__builtin_isinf_sign))
4970 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
4971 << 0 << 0 << TheCall->getSourceRange();
4972
4973 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
4974 BuiltinID == Builtin::BI__builtin_isunordered))
4975 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
4976 << 1 << 0 << TheCall->getSourceRange();
4977
4978 bool IsFPClass = NumArgs == 2;
4979
4980 // Find out position of floating-point argument.
4981 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
4982
4983 // We can count on all parameters preceding the floating-point just being int.
4984 // Try all of those.
4985 for (unsigned i = 0; i < FPArgNo; ++i) {
4986 Expr *Arg = TheCall->getArg(i);
4987
4988 if (Arg->isTypeDependent())
4989 return false;
4990
4993
4994 if (Res.isInvalid())
4995 return true;
4996 TheCall->setArg(i, Res.get());
4997 }
4998
4999 Expr *OrigArg = TheCall->getArg(FPArgNo);
5000
5001 if (OrigArg->isTypeDependent())
5002 return false;
5003
5004 // Usual Unary Conversions will convert half to float, which we want for
5005 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5006 // type how it is, but do normal L->Rvalue conversions.
5008 ExprResult Res = UsualUnaryConversions(OrigArg);
5009
5010 if (!Res.isUsable())
5011 return true;
5012 OrigArg = Res.get();
5013 } else {
5015
5016 if (!Res.isUsable())
5017 return true;
5018 OrigArg = Res.get();
5019 }
5020 TheCall->setArg(FPArgNo, OrigArg);
5021
5022 QualType VectorResultTy;
5023 QualType ElementTy = OrigArg->getType();
5024 // TODO: When all classification function are implemented with is_fpclass,
5025 // vector argument can be supported in all of them.
5026 if (ElementTy->isVectorType() && IsFPClass) {
5027 VectorResultTy = GetSignedVectorType(ElementTy);
5028 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
5029 }
5030
5031 // This operation requires a non-_Complex floating-point number.
5032 if (!ElementTy->isRealFloatingType())
5033 return Diag(OrigArg->getBeginLoc(),
5034 diag::err_typecheck_call_invalid_unary_fp)
5035 << OrigArg->getType() << OrigArg->getSourceRange();
5036
5037 // __builtin_isfpclass has integer parameter that specify test mask. It is
5038 // passed in (...), so it should be analyzed completely here.
5039 if (IsFPClass)
5040 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
5041 return true;
5042
5043 // TODO: enable this code to all classification functions.
5044 if (IsFPClass) {
5045 QualType ResultTy;
5046 if (!VectorResultTy.isNull())
5047 ResultTy = VectorResultTy;
5048 else
5049 ResultTy = Context.IntTy;
5050 TheCall->setType(ResultTy);
5051 }
5052
5053 return false;
5054}
5055
5056bool Sema::BuiltinComplex(CallExpr *TheCall) {
5057 if (checkArgCount(TheCall, 2))
5058 return true;
5059
5060 bool Dependent = false;
5061 for (unsigned I = 0; I != 2; ++I) {
5062 Expr *Arg = TheCall->getArg(I);
5063 QualType T = Arg->getType();
5064 if (T->isDependentType()) {
5065 Dependent = true;
5066 continue;
5067 }
5068
5069 // Despite supporting _Complex int, GCC requires a real floating point type
5070 // for the operands of __builtin_complex.
5071 if (!T->isRealFloatingType()) {
5072 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
5073 << Arg->getType() << Arg->getSourceRange();
5074 }
5075
5076 ExprResult Converted = DefaultLvalueConversion(Arg);
5077 if (Converted.isInvalid())
5078 return true;
5079 TheCall->setArg(I, Converted.get());
5080 }
5081
5082 if (Dependent) {
5083 TheCall->setType(Context.DependentTy);
5084 return false;
5085 }
5086
5087 Expr *Real = TheCall->getArg(0);
5088 Expr *Imag = TheCall->getArg(1);
5089 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
5090 return Diag(Real->getBeginLoc(),
5091 diag::err_typecheck_call_different_arg_types)
5092 << Real->getType() << Imag->getType()
5093 << Real->getSourceRange() << Imag->getSourceRange();
5094 }
5095
5096 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
5097 // don't allow this builtin to form those types either.
5098 // FIXME: Should we allow these types?
5099 if (Real->getType()->isFloat16Type())
5100 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
5101 << "_Float16";
5102 if (Real->getType()->isHalfType())
5103 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
5104 << "half";
5105
5106 TheCall->setType(Context.getComplexType(Real->getType()));
5107 return false;
5108}
5109
5110/// BuiltinShuffleVector - Handle __builtin_shufflevector.
5111// This is declared to take (...), so we have to check everything.
5113 if (TheCall->getNumArgs() < 2)
5114 return ExprError(Diag(TheCall->getEndLoc(),
5115 diag::err_typecheck_call_too_few_args_at_least)
5116 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5117 << /*is non object*/ 0 << TheCall->getSourceRange());
5118
5119 // Determine which of the following types of shufflevector we're checking:
5120 // 1) unary, vector mask: (lhs, mask)
5121 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5122 QualType resType = TheCall->getArg(0)->getType();
5123 unsigned numElements = 0;
5124
5125 if (!TheCall->getArg(0)->isTypeDependent() &&
5126 !TheCall->getArg(1)->isTypeDependent()) {
5127 QualType LHSType = TheCall->getArg(0)->getType();
5128 QualType RHSType = TheCall->getArg(1)->getType();
5129
5130 if (!LHSType->isVectorType() || !RHSType->isVectorType())
5131 return ExprError(
5132 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5133 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ false
5134 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5135 TheCall->getArg(1)->getEndLoc()));
5136
5137 numElements = LHSType->castAs<VectorType>()->getNumElements();
5138 unsigned numResElements = TheCall->getNumArgs() - 2;
5139
5140 // Check to see if we have a call with 2 vector arguments, the unary shuffle
5141 // with mask. If so, verify that RHS is an integer vector type with the
5142 // same number of elts as lhs.
5143 if (TheCall->getNumArgs() == 2) {
5144 if (!RHSType->hasIntegerRepresentation() ||
5145 RHSType->castAs<VectorType>()->getNumElements() != numElements)
5146 return ExprError(Diag(TheCall->getBeginLoc(),
5147 diag::err_vec_builtin_incompatible_vector)
5148 << TheCall->getDirectCallee()
5149 << /*isMorethantwoArgs*/ false
5150 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5151 TheCall->getArg(1)->getEndLoc()));
5152 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5153 return ExprError(Diag(TheCall->getBeginLoc(),
5154 diag::err_vec_builtin_incompatible_vector)
5155 << TheCall->getDirectCallee()
5156 << /*isMorethantwoArgs*/ false
5157 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5158 TheCall->getArg(1)->getEndLoc()));
5159 } else if (numElements != numResElements) {
5160 QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5161 resType =
5162 Context.getVectorType(eltType, numResElements, VectorKind::Generic);
5163 }
5164 }
5165
5166 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5167 if (TheCall->getArg(i)->isTypeDependent() ||
5168 TheCall->getArg(i)->isValueDependent())
5169 continue;
5170
5171 std::optional<llvm::APSInt> Result;
5172 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
5173 return ExprError(Diag(TheCall->getBeginLoc(),
5174 diag::err_shufflevector_nonconstant_argument)
5175 << TheCall->getArg(i)->getSourceRange());
5176
5177 // Allow -1 which will be translated to undef in the IR.
5178 if (Result->isSigned() && Result->isAllOnes())
5179 continue;
5180
5181 if (Result->getActiveBits() > 64 ||
5182 Result->getZExtValue() >= numElements * 2)
5183 return ExprError(Diag(TheCall->getBeginLoc(),
5184 diag::err_shufflevector_argument_too_large)
5185 << TheCall->getArg(i)->getSourceRange());
5186 }
5187
5189
5190 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5191 exprs.push_back(TheCall->getArg(i));
5192 TheCall->setArg(i, nullptr);
5193 }
5194
5195 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5196 TheCall->getCallee()->getBeginLoc(),
5197 TheCall->getRParenLoc());
5198}
5199
5201 SourceLocation BuiltinLoc,
5202 SourceLocation RParenLoc) {
5205 QualType DstTy = TInfo->getType();
5206 QualType SrcTy = E->getType();
5207
5208 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5209 return ExprError(Diag(BuiltinLoc,
5210 diag::err_convertvector_non_vector)
5211 << E->getSourceRange());
5212 if (!DstTy->isVectorType() && !DstTy->isDependentType())
5213 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
5214 << "second"
5215 << "__builtin_convertvector");
5216
5217 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5218 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5219 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5220 if (SrcElts != DstElts)
5221 return ExprError(Diag(BuiltinLoc,
5222 diag::err_convertvector_incompatible_vector)
5223 << E->getSourceRange());
5224 }
5225
5226 return new (Context) class ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
5227 BuiltinLoc, RParenLoc);
5228}
5229
5230bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
5231 unsigned NumArgs = TheCall->getNumArgs();
5232
5233 if (NumArgs > 3)
5234 return Diag(TheCall->getEndLoc(),
5235 diag::err_typecheck_call_too_many_args_at_most)
5236 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
5237 << TheCall->getSourceRange();
5238
5239 // Argument 0 is checked for us and the remaining arguments must be
5240 // constant integers.
5241 for (unsigned i = 1; i != NumArgs; ++i)
5242 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5243 return true;
5244
5245 return false;
5246}
5247
5248bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
5250 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
5251 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5252 if (checkArgCount(TheCall, 1))
5253 return true;
5254 Expr *Arg = TheCall->getArg(0);
5255 if (Arg->isInstantiationDependent())
5256 return false;
5257
5258 QualType ArgTy = Arg->getType();
5259 if (!ArgTy->hasFloatingRepresentation())
5260 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
5261 << ArgTy;
5262 if (Arg->isLValue()) {
5263 ExprResult FirstArg = DefaultLvalueConversion(Arg);
5264 TheCall->setArg(0, FirstArg.get());
5265 }
5266 TheCall->setType(TheCall->getArg(0)->getType());
5267 return false;
5268}
5269
5270bool Sema::BuiltinAssume(CallExpr *TheCall) {
5271 Expr *Arg = TheCall->getArg(0);
5272 if (Arg->isInstantiationDependent()) return false;
5273
5274 if (Arg->HasSideEffects(Context))
5275 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5276 << Arg->getSourceRange()
5277 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5278
5279 return false;
5280}
5281
5282bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
5283 // The alignment must be a constant integer.
5284 Expr *Arg = TheCall->getArg(1);
5285
5286 // We can't check the value of a dependent argument.
5287 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5288 if (const auto *UE =
5289 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5290 if (UE->getKind() == UETT_AlignOf ||
5291 UE->getKind() == UETT_PreferredAlignOf)
5292 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5293 << Arg->getSourceRange();
5294
5295 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5296
5297 if (!Result.isPowerOf2())
5298 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5299 << Arg->getSourceRange();
5300
5301 if (Result < Context.getCharWidth())
5302 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5304
5305 if (Result > std::numeric_limits<int32_t>::max())
5306 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5307 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5308 }
5309
5310 return false;
5311}
5312
5313bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
5314 if (checkArgCountRange(TheCall, 2, 3))
5315 return true;
5316
5317 unsigned NumArgs = TheCall->getNumArgs();
5318 Expr *FirstArg = TheCall->getArg(0);
5319
5320 {
5321 ExprResult FirstArgResult =
5323 if (!FirstArgResult.get()->getType()->isPointerType()) {
5324 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
5325 << TheCall->getSourceRange();
5326 return true;
5327 }
5328 TheCall->setArg(0, FirstArgResult.get());
5329 }
5330
5331 // The alignment must be a constant integer.
5332 Expr *SecondArg = TheCall->getArg(1);
5333
5334 // We can't check the value of a dependent argument.
5335 if (!SecondArg->isValueDependent()) {
5336 llvm::APSInt Result;
5337 if (BuiltinConstantArg(TheCall, 1, Result))
5338 return true;
5339
5340 if (!Result.isPowerOf2())
5341 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5342 << SecondArg->getSourceRange();
5343
5345 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
5346 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
5347 }
5348
5349 if (NumArgs > 2) {
5350 Expr *ThirdArg = TheCall->getArg(2);
5351 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
5352 return true;
5353 TheCall->setArg(2, ThirdArg);
5354 }
5355
5356 return false;
5357}
5358
5359bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
5360 unsigned BuiltinID =
5361 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5362 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5363
5364 unsigned NumArgs = TheCall->getNumArgs();
5365 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5366 if (NumArgs < NumRequiredArgs) {
5367 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5368 << 0 /* function call */ << NumRequiredArgs << NumArgs
5369 << /*is non object*/ 0 << TheCall->getSourceRange();
5370 }
5371 if (NumArgs >= NumRequiredArgs + 0x100) {
5372 return Diag(TheCall->getEndLoc(),
5373 diag::err_typecheck_call_too_many_args_at_most)
5374 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5375 << /*is non object*/ 0 << TheCall->getSourceRange();
5376 }
5377 unsigned i = 0;
5378
5379 // For formatting call, check buffer arg.
5380 if (!IsSizeCall) {
5381 ExprResult Arg(TheCall->getArg(i));
5383 Context, Context.VoidPtrTy, false);
5384 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5385 if (Arg.isInvalid())
5386 return true;
5387 TheCall->setArg(i, Arg.get());
5388 i++;
5389 }
5390
5391 // Check string literal arg.
5392 unsigned FormatIdx = i;
5393 {
5394 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5395 if (Arg.isInvalid())
5396 return true;
5397 TheCall->setArg(i, Arg.get());
5398 i++;
5399 }
5400
5401 // Make sure variadic args are scalar.
5402 unsigned FirstDataArg = i;
5403 while (i < NumArgs) {
5405 TheCall->getArg(i), VariadicFunction, nullptr);
5406 if (Arg.isInvalid())
5407 return true;
5408 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5409 if (ArgSize.getQuantity() >= 0x100) {
5410 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
5411 << i << (int)ArgSize.getQuantity() << 0xff
5412 << TheCall->getSourceRange();
5413 }
5414 TheCall->setArg(i, Arg.get());
5415 i++;
5416 }
5417
5418 // Check formatting specifiers. NOTE: We're only doing this for the non-size
5419 // call to avoid duplicate diagnostics.
5420 if (!IsSizeCall) {
5421 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5422 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5423 bool Success = CheckFormatArguments(
5424 Args, FAPK_Variadic, FormatIdx, FirstDataArg, FST_OSLog,
5426 CheckedVarArgs);
5427 if (!Success)
5428 return true;
5429 }
5430
5431 if (IsSizeCall) {
5432 TheCall->setType(Context.getSizeType());
5433 } else {
5434 TheCall->setType(Context.VoidPtrTy);
5435 }
5436 return false;
5437}
5438
5439bool Sema::BuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5440 llvm::APSInt &Result) {
5441 Expr *Arg = TheCall->getArg(ArgNum);
5442 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5443 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5444
5445 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
5446
5447 std::optional<llvm::APSInt> R;
5448 if (!(R = Arg->getIntegerConstantExpr(Context)))
5449 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
5450 << FDecl->getDeclName() << Arg->getSourceRange();
5451 Result = *R;
5452 return false;
5453}
5454
5455bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
5456 int High, bool RangeIsError) {
5458 return false;
5459 llvm::APSInt Result;
5460
5461 // We can't check the value of a dependent argument.
5462 Expr *Arg = TheCall->getArg(ArgNum);
5463 if (Arg->isTypeDependent() || Arg->isValueDependent())
5464 return false;
5465
5466 // Check constant-ness first.
5467 if (BuiltinConstantArg(TheCall, ArgNum, Result))
5468 return true;
5469
5470 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
5471 if (RangeIsError)
5472 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
5473 << toString(Result, 10) << Low << High << Arg->getSourceRange();
5474 else
5475 // Defer the warning until we know if the code will be emitted so that
5476 // dead code can ignore this.
5477 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
5478 PDiag(diag::warn_argument_invalid_range)
5479 << toString(Result, 10) << Low << High
5480 << Arg->getSourceRange());
5481 }
5482
5483 return false;
5484}
5485
5487 unsigned Num) {
5488 llvm::APSInt Result;
5489
5490 // We can't check the value of a dependent argument.
5491 Expr *Arg = TheCall->getArg(ArgNum);
5492 if (Arg->isTypeDependent() || Arg->isValueDependent())
5493 return false;
5494
5495 // Check constant-ness first.
5496 if (BuiltinConstantArg(TheCall, ArgNum, Result))
5497 return true;
5498
5499 if (Result.getSExtValue() % Num != 0)
5500 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
5501 << Num << Arg->getSourceRange();
5502
5503 return false;
5504}
5505
5506bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
5507 llvm::APSInt Result;
5508
5509 // We can't check the value of a dependent argument.
5510 Expr *Arg = TheCall->getArg(ArgNum);
5511 if (Arg->isTypeDependent() || Arg->isValueDependent())
5512 return false;
5513
5514 // Check constant-ness first.
5515 if (BuiltinConstantArg(TheCall, ArgNum, Result))
5516 return true;
5517
5518 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
5519 // and only if x is a power of 2.
5520 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
5521 return false;
5522
5523 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
5524 << Arg->getSourceRange();
5525}
5526
5527static bool IsShiftedByte(llvm::APSInt Value) {
5528 if (Value.isNegative())
5529 return false;
5530
5531 // Check if it's a shifted byte, by shifting it down
5532 while (true) {
5533 // If the value fits in the bottom byte, the check passes.
5534 if (Value < 0x100)
5535 return true;
5536
5537 // Otherwise, if the value has _any_ bits in the bottom byte, the check
5538 // fails.
5539 if ((Value & 0xFF) != 0)
5540 return false;
5541
5542 // If the bottom 8 bits are all 0, but something above that is nonzero,
5543 // then shifting the value right by 8 bits won't affect whether it's a
5544 // shifted byte or not. So do that, and go round again.
5545 Value >>= 8;
5546 }
5547}
5548
5550 unsigned ArgBits) {
5551 llvm::APSInt Result;
5552
5553 // We can't check the value of a dependent argument.
5554 Expr *Arg = TheCall->getArg(ArgNum);
5555 if (Arg->isTypeDependent() || Arg->isValueDependent())
5556 return false;
5557
5558 // Check constant-ness first.
5559 if (BuiltinConstantArg(TheCall, ArgNum, Result))
5560 return true;
5561
5562 // Truncate to the given size.
5563 Result = Result.getLoBits(ArgBits);
5564 Result.setIsUnsigned(true);
5565
5566 if (IsShiftedByte(Result))
5567 return false;
5568
5569 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
5570 << Arg->getSourceRange();
5571}
5572
5574 unsigned ArgBits) {
5575 llvm::APSInt Result;
5576
5577 // We can't check the value of a dependent argument.
5578 Expr *Arg = TheCall->getArg(ArgNum);
5579 if (Arg->isTypeDependent() || Arg->isValueDependent())
5580 return false;
5581
5582 // Check constant-ness first.
5583 if (BuiltinConstantArg(TheCall, ArgNum, Result))
5584 return true;
5585
5586 // Truncate to the given size.
5587 Result = Result.getLoBits(ArgBits);
5588 Result.setIsUnsigned(true);
5589
5590 // Check to see if it's in either of the required forms.
5591 if (IsShiftedByte(Result) ||
5592 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
5593 return false;
5594
5595 return Diag(TheCall->getBeginLoc(),
5596 diag::err_argument_not_shifted_byte_or_xxff)
5597 << Arg->getSourceRange();
5598}
5599
5600bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
5602 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
5603 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5604
5605 Expr *Arg = TheCall->getArg(1);
5606 llvm::APSInt Result;
5607
5608 // TODO: This is less than ideal. Overload this to take a value.
5609 if (BuiltinConstantArg(TheCall, 1, Result))
5610 return true;
5611
5612 if (Result != 1)
5613 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
5614 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
5615
5616 return false;
5617}
5618
5619bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
5621 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
5622 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5623 return false;
5624}
5625
5626bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
5627 if (checkArgCount(TheCall, 1))
5628 return true;
5629
5630 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
5631 if (ArgRes.isInvalid())
5632 return true;
5633
5634 // For simplicity, we support only limited expressions for the argument.
5635 // Specifically a pointer to a flexible array member:'ptr->array'. This
5636 // allows us to reject arguments with complex casting, which really shouldn't
5637 // be a huge problem.
5638 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
5639 if (!isa<PointerType>(Arg->getType()) && !Arg->getType()->isArrayType())
5640 return Diag(Arg->getBeginLoc(),
5641 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
5642 << Arg->getSourceRange();
5643
5644 if (Arg->HasSideEffects(Context))
5645 return Diag(Arg->getBeginLoc(),
5646 diag::err_builtin_counted_by_ref_has_side_effects)
5647 << Arg->getSourceRange();
5648
5649 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
5650 if (!ME->isFlexibleArrayMemberLike(
5651 Context, getLangOpts().getStrictFlexArraysLevel()))
5652 return Diag(Arg->getBeginLoc(),
5653 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
5654 << Arg->getSourceRange();
5655
5656 if (auto *CATy =
5657 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
5658 CATy && CATy->getKind() == CountAttributedType::CountedBy) {
5659 const auto *FAMDecl = cast<FieldDecl>(ME->getMemberDecl());
5660 if (const FieldDecl *CountFD = FAMDecl->findCountedByField()) {
5661 TheCall->setType(Context.getPointerType(CountFD->getType()));
5662 return false;
5663 }
5664 }
5665 } else {
5666 return Diag(Arg->getBeginLoc(),
5667 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
5668 << Arg->getSourceRange();
5669 }
5670
5672 return false;
5673}
5674
5675/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
5676/// It allows leaking and modification of bounds safety information.
5677bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
5678 BuiltinCountedByRefKind K) {
5679 const CallExpr *CE =
5680 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
5681 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
5682 return false;
5683
5684 switch (K) {
5685 case AssignmentKind:
5686 case InitializerKind:
5687 Diag(E->getExprLoc(),
5688 diag::err_builtin_counted_by_ref_cannot_leak_reference)
5689 << 0 << E->getSourceRange();
5690 break;
5691 case FunctionArgKind:
5692 Diag(E->getExprLoc(),
5693 diag::err_builtin_counted_by_ref_cannot_leak_reference)
5694 << 1 << E->getSourceRange();
5695 break;
5696 case ReturnArgKind:
5697 Diag(E->getExprLoc(),
5698 diag::err_builtin_counted_by_ref_cannot_leak_reference)
5699 << 2 << E->getSourceRange();
5700 break;
5701 case ArraySubscriptKind:
5702 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
5703 << 0 << E->getSourceRange();
5704 break;
5705 case BinaryExprKind:
5706 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
5707 << 1 << E->getSourceRange();
5708 break;
5709 }
5710
5711 return true;
5712}
5713
5714namespace {
5715
5716class UncoveredArgHandler {
5717 enum { Unknown = -1, AllCovered = -2 };
5718
5719 signed FirstUncoveredArg = Unknown;
5720 SmallVector<const Expr *, 4> DiagnosticExprs;
5721
5722public:
5723 UncoveredArgHandler() = default;
5724
5725 bool hasUncoveredArg() const {
5726 return (FirstUncoveredArg >= 0);
5727 }
5728
5729 unsigned getUncoveredArg() const {
5730 assert(hasUncoveredArg() && "no uncovered argument");
5731 return FirstUncoveredArg;
5732 }
5733
5734 void setAllCovered() {
5735 // A string has been found with all arguments covered, so clear out
5736 // the diagnostics.
5737 DiagnosticExprs.clear();
5738 FirstUncoveredArg = AllCovered;
5739 }
5740
5741 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
5742 assert(NewFirstUncoveredArg >= 0 && "Outside range");
5743
5744 // Don't update if a previous string covers all arguments.
5745 if (FirstUncoveredArg == AllCovered)
5746 return;
5747
5748 // UncoveredArgHandler tracks the highest uncovered argument index
5749 // and with it all the strings that match this index.
5750 if (NewFirstUncoveredArg == FirstUncoveredArg)
5751 DiagnosticExprs.push_back(StrExpr);
5752 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
5753 DiagnosticExprs.clear();
5754 DiagnosticExprs.push_back(StrExpr);
5755 FirstUncoveredArg = NewFirstUncoveredArg;
5756 }
5757 }
5758
5759 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
5760};
5761
5762enum StringLiteralCheckType {
5763 SLCT_NotALiteral,
5764 SLCT_UncheckedLiteral,
5765 SLCT_CheckedLiteral
5766};
5767
5768} // namespace
5769
5770static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
5771 BinaryOperatorKind BinOpKind,
5772 bool AddendIsRight) {
5773 unsigned BitWidth = Offset.getBitWidth();
5774 unsigned AddendBitWidth = Addend.getBitWidth();
5775 // There might be negative interim results.
5776 if (Addend.isUnsigned()) {
5777 Addend = Addend.zext(++AddendBitWidth);
5778 Addend.setIsSigned(true);
5779 }
5780 // Adjust the bit width of the APSInts.
5781 if (AddendBitWidth > BitWidth) {
5782 Offset = Offset.sext(AddendBitWidth);
5783 BitWidth = AddendBitWidth;
5784 } else if (BitWidth > AddendBitWidth) {
5785 Addend = Addend.sext(BitWidth);
5786 }
5787
5788 bool Ov = false;
5789 llvm::APSInt ResOffset = Offset;
5790 if (BinOpKind == BO_Add)
5791 ResOffset = Offset.sadd_ov(Addend, Ov);
5792 else {
5793 assert(AddendIsRight && BinOpKind == BO_Sub &&
5794 "operator must be add or sub with addend on the right");
5795 ResOffset = Offset.ssub_ov(Addend, Ov);
5796 }
5797
5798 // We add an offset to a pointer here so we should support an offset as big as
5799 // possible.
5800 if (Ov) {
5801 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
5802 "index (intermediate) result too big");
5803 Offset = Offset.sext(2 * BitWidth);
5804 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
5805 return;
5806 }
5807
5808 Offset = ResOffset;
5809}
5810
5811namespace {
5812
5813// This is a wrapper class around StringLiteral to support offsetted string
5814// literals as format strings. It takes the offset into account when returning
5815// the string and its length or the source locations to display notes correctly.
5816class FormatStringLiteral {
5817 const StringLiteral *FExpr;
5818 int64_t Offset;
5819
5820 public:
5821 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
5822 : FExpr(fexpr), Offset(Offset) {}
5823
5824 StringRef getString() const {
5825 return FExpr->getString().drop_front(Offset);
5826 }
5827
5828 unsigned getByteLength() const {
5829 return FExpr->getByteLength() - getCharByteWidth() * Offset;
5830 }
5831
5832 unsigned getLength() const { return FExpr->getLength() - Offset; }
5833 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
5834
5835 StringLiteralKind getKind() const { return FExpr->getKind(); }
5836
5837 QualType getType() const { return FExpr->getType(); }
5838
5839 bool isAscii() const { return FExpr->isOrdinary(); }
5840 bool isWide() const { return FExpr->isWide(); }
5841 bool isUTF8() const { return FExpr->isUTF8(); }
5842 bool isUTF16() const { return FExpr->isUTF16(); }
5843 bool isUTF32() const { return FExpr->isUTF32(); }
5844 bool isPascal() const { return FExpr->isPascal(); }
5845
5846 SourceLocation getLocationOfByte(
5847 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
5848 const TargetInfo &Target, unsigned *StartToken = nullptr,
5849 unsigned *StartTokenByteOffset = nullptr) const {
5850 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
5851 StartToken, StartTokenByteOffset);
5852 }
5853
5854 SourceLocation getBeginLoc() const LLVM_READONLY {
5855 return FExpr->getBeginLoc().getLocWithOffset(Offset);
5856 }
5857
5858 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
5859};
5860
5861} // namespace
5862
5863static void CheckFormatString(
5864 Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr,
5866 unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type,
5867 bool inFunctionCall, Sema::VariadicCallType CallType,
5868 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
5869 bool IgnoreStringsWithoutSpecifiers);
5870
5871static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
5872 const Expr *E);
5873
5874// Determine if an expression is a string literal or constant string.
5875// If this function returns false on the arguments to a function expecting a
5876// format string, we will usually need to emit a warning.
5877// True string literals are then checked by CheckFormatString.
5878static StringLiteralCheckType
5880 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
5881 unsigned firstDataArg, Sema::FormatStringType Type,
5882 Sema::VariadicCallType CallType, bool InFunctionCall,
5883 llvm::SmallBitVector &CheckedVarArgs,
5884 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
5885 bool IgnoreStringsWithoutSpecifiers = false) {
5887 return SLCT_NotALiteral;
5888tryAgain:
5889 assert(Offset.isSigned() && "invalid offset");
5890
5891 if (E->isTypeDependent() || E->isValueDependent())
5892 return SLCT_NotALiteral;
5893
5894 E = E->IgnoreParenCasts();
5895
5897 // Technically -Wformat-nonliteral does not warn about this case.
5898 // The behavior of printf and friends in this case is implementation
5899 // dependent. Ideally if the format string cannot be null then
5900 // it should have a 'nonnull' attribute in the function prototype.
5901 return SLCT_UncheckedLiteral;
5902
5903 switch (E->getStmtClass()) {
5904 case Stmt::InitListExprClass:
5905 // Handle expressions like {"foobar"}.
5906 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
5907 return checkFormatStringExpr(S, SLE, Args, APK, format_idx, firstDataArg,
5908 Type, CallType, /*InFunctionCall*/ false,
5909 CheckedVarArgs, UncoveredArg, Offset,
5910 IgnoreStringsWithoutSpecifiers);
5911 }
5912 return SLCT_NotALiteral;
5913 case Stmt::BinaryConditionalOperatorClass:
5914 case Stmt::ConditionalOperatorClass: {
5915 // The expression is a literal if both sub-expressions were, and it was
5916 // completely checked only if both sub-expressions were checked.
5918 cast<AbstractConditionalOperator>(E);
5919
5920 // Determine whether it is necessary to check both sub-expressions, for
5921 // example, because the condition expression is a constant that can be
5922 // evaluated at compile time.
5923 bool CheckLeft = true, CheckRight = true;
5924
5925 bool Cond;
5926 if (C->getCond()->EvaluateAsBooleanCondition(
5927 Cond, S.getASTContext(), S.isConstantEvaluatedContext())) {
5928 if (Cond)
5929 CheckRight = false;
5930 else
5931 CheckLeft = false;
5932 }
5933
5934 // We need to maintain the offsets for the right and the left hand side
5935 // separately to check if every possible indexed expression is a valid
5936 // string literal. They might have different offsets for different string
5937 // literals in the end.
5938 StringLiteralCheckType Left;
5939 if (!CheckLeft)
5940 Left = SLCT_UncheckedLiteral;
5941 else {
5942 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, APK, format_idx,
5943 firstDataArg, Type, CallType, InFunctionCall,
5944 CheckedVarArgs, UncoveredArg, Offset,
5945 IgnoreStringsWithoutSpecifiers);
5946 if (Left == SLCT_NotALiteral || !CheckRight) {
5947 return Left;
5948 }
5949 }
5950
5951 StringLiteralCheckType Right = checkFormatStringExpr(
5952 S, C->getFalseExpr(), Args, APK, format_idx, firstDataArg, Type,
5953 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
5954 IgnoreStringsWithoutSpecifiers);
5955
5956 return (CheckLeft && Left < Right) ? Left : Right;
5957 }
5958
5959 case Stmt::ImplicitCastExprClass:
5960 E = cast<ImplicitCastExpr>(E)->getSubExpr();
5961 goto tryAgain;
5962
5963 case Stmt::OpaqueValueExprClass:
5964 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
5965 E = src;
5966 goto tryAgain;
5967 }
5968 return SLCT_NotALiteral;
5969
5970 case Stmt::PredefinedExprClass:
5971 // While __func__, etc., are technically not string literals, they
5972 // cannot contain format specifiers and thus are not a security
5973 // liability.
5974 return SLCT_UncheckedLiteral;
5975
5976 case Stmt::DeclRefExprClass: {
5977 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
5978
5979 // As an exception, do not flag errors for variables binding to
5980 // const string literals.
5981 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
5982 bool isConstant = false;
5983 QualType T = DR->getType();
5984
5985 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
5986 isConstant = AT->getElementType().isConstant(S.Context);
5987 } else if (const PointerType *PT = T->getAs<PointerType>()) {
5988 isConstant = T.isConstant(S.Context) &&
5990 } else if (T->isObjCObjectPointerType()) {
5991 // In ObjC, there is usually no "const ObjectPointer" type,
5992 // so don't check if the pointee type is constant.
5993 isConstant = T.isConstant(S.Context);
5994 }
5995
5996 if (isConstant) {
5997 if (const Expr *Init = VD->getAnyInitializer()) {
5998 // Look through initializers like const char c[] = { "foo" }
5999 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6000 if (InitList->isStringLiteralInit())
6001 Init = InitList->getInit(0)->IgnoreParenImpCasts();
6002 }
6003 return checkFormatStringExpr(
6004 S, Init, Args, APK, format_idx, firstDataArg, Type, CallType,
6005 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg, Offset);
6006 }
6007 }
6008
6009 // When the format argument is an argument of this function, and this
6010 // function also has the format attribute, there are several interactions
6011 // for which there shouldn't be a warning. For instance, when calling
6012 // v*printf from a function that has the printf format attribute, we
6013 // should not emit a warning about using `fmt`, even though it's not
6014 // constant, because the arguments have already been checked for the
6015 // caller of `logmessage`:
6016 //
6017 // __attribute__((format(printf, 1, 2)))
6018 // void logmessage(char const *fmt, ...) {
6019 // va_list ap;
6020 // va_start(ap, fmt);
6021 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
6022 // ...
6023 // }
6024 //
6025 // Another interaction that we need to support is calling a variadic
6026 // format function from a format function that has fixed arguments. For
6027 // instance:
6028 //
6029 // __attribute__((format(printf, 1, 2)))
6030 // void logstring(char const *fmt, char const *str) {
6031 // printf(fmt, str); /* do not emit a warning about "fmt" */
6032 // }
6033 //
6034 // Same (and perhaps more relatably) for the variadic template case:
6035 //
6036 // template<typename... Args>
6037 // __attribute__((format(printf, 1, 2)))
6038 // void log(const char *fmt, Args&&... args) {
6039 // printf(fmt, forward<Args>(args)...);
6040 // /* do not emit a warning about "fmt" */
6041 // }
6042 //
6043 // Due to implementation difficulty, we only check the format, not the
6044 // format arguments, in all cases.
6045 //
6046 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
6047 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
6048 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
6049 bool IsCXXMember = false;
6050 if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
6051 IsCXXMember = MD->isInstance();
6052
6053 bool IsVariadic = false;
6054 if (const FunctionType *FnTy = D->getFunctionType())
6055 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
6056 else if (const auto *BD = dyn_cast<BlockDecl>(D))
6057 IsVariadic = BD->isVariadic();
6058 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
6059 IsVariadic = OMD->isVariadic();
6060
6061 Sema::FormatStringInfo CallerFSI;
6062 if (Sema::getFormatStringInfo(PVFormat, IsCXXMember, IsVariadic,
6063 &CallerFSI)) {
6064 // We also check if the formats are compatible.
6065 // We can't pass a 'scanf' string to a 'printf' function.
6066 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx &&
6067 Type == S.GetFormatStringType(PVFormat)) {
6068 // Lastly, check that argument passing kinds transition in a
6069 // way that makes sense:
6070 // from a caller with FAPK_VAList, allow FAPK_VAList
6071 // from a caller with FAPK_Fixed, allow FAPK_Fixed
6072 // from a caller with FAPK_Fixed, allow FAPK_Variadic
6073 // from a caller with FAPK_Variadic, allow FAPK_VAList
6074 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
6079 return SLCT_UncheckedLiteral;
6080 }
6081 }
6082 }
6083 }
6084 }
6085 }
6086 }
6087
6088 return SLCT_NotALiteral;
6089 }
6090
6091 case Stmt::CallExprClass:
6092 case Stmt::CXXMemberCallExprClass: {
6093 const CallExpr *CE = cast<CallExpr>(E);
6094 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6095 bool IsFirst = true;
6096 StringLiteralCheckType CommonResult;
6097 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6098 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6099 StringLiteralCheckType Result = checkFormatStringExpr(
6100 S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
6101 InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6102 IgnoreStringsWithoutSpecifiers);
6103 if (IsFirst) {
6104 CommonResult = Result;
6105 IsFirst = false;
6106 }
6107 }
6108 if (!IsFirst)
6109 return CommonResult;
6110
6111 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6112 unsigned BuiltinID = FD->getBuiltinID();
6113 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6114 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6115 const Expr *Arg = CE->getArg(0);
6116 return checkFormatStringExpr(
6117 S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
6118 InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6119 IgnoreStringsWithoutSpecifiers);
6120 }
6121 }
6122 }
6123 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
6124 return checkFormatStringExpr(S, SLE, Args, APK, format_idx, firstDataArg,
6125 Type, CallType, /*InFunctionCall*/ false,
6126 CheckedVarArgs, UncoveredArg, Offset,
6127 IgnoreStringsWithoutSpecifiers);
6128 return SLCT_NotALiteral;
6129 }
6130 case Stmt::ObjCMessageExprClass: {
6131 const auto *ME = cast<ObjCMessageExpr>(E);
6132 if (const auto *MD = ME->getMethodDecl()) {
6133 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6134 // As a special case heuristic, if we're using the method -[NSBundle
6135 // localizedStringForKey:value:table:], ignore any key strings that lack
6136 // format specifiers. The idea is that if the key doesn't have any
6137 // format specifiers then its probably just a key to map to the
6138 // localized strings. If it does have format specifiers though, then its
6139 // likely that the text of the key is the format string in the
6140 // programmer's language, and should be checked.
6141 const ObjCInterfaceDecl *IFace;
6142 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6143 IFace->getIdentifier()->isStr("NSBundle") &&
6144 MD->getSelector().isKeywordSelector(
6145 {"localizedStringForKey", "value", "table"})) {
6146 IgnoreStringsWithoutSpecifiers = true;
6147 }
6148
6149 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6150 return checkFormatStringExpr(
6151 S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
6152 InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6153 IgnoreStringsWithoutSpecifiers);
6154 }
6155 }
6156
6157 return SLCT_NotALiteral;
6158 }
6159 case Stmt::ObjCStringLiteralClass:
6160 case Stmt::StringLiteralClass: {
6161 const StringLiteral *StrE = nullptr;
6162
6163 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6164 StrE = ObjCFExpr->getString();
6165 else
6166 StrE = cast<StringLiteral>(E);
6167
6168 if (StrE) {
6169 if (Offset.isNegative() || Offset > StrE->getLength()) {
6170 // TODO: It would be better to have an explicit warning for out of
6171 // bounds literals.
6172 return SLCT_NotALiteral;
6173 }
6174 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6175 CheckFormatString(S, &FStr, E, Args, APK, format_idx, firstDataArg, Type,
6176 InFunctionCall, CallType, CheckedVarArgs, UncoveredArg,
6177 IgnoreStringsWithoutSpecifiers);
6178 return SLCT_CheckedLiteral;
6179 }
6180
6181 return SLCT_NotALiteral;
6182 }
6183 case Stmt::BinaryOperatorClass: {
6184 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6185
6186 // A string literal + an int offset is still a string literal.
6187 if (BinOp->isAdditiveOp()) {
6188 Expr::EvalResult LResult, RResult;
6189
6190 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6191 LResult, S.Context, Expr::SE_NoSideEffects,
6193 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6194 RResult, S.Context, Expr::SE_NoSideEffects,
6196
6197 if (LIsInt != RIsInt) {
6198 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6199
6200 if (LIsInt) {
6201 if (BinOpKind == BO_Add) {
6202 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6203 E = BinOp->getRHS();
6204 goto tryAgain;
6205 }
6206 } else {
6207 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6208 E = BinOp->getLHS();
6209 goto tryAgain;
6210 }
6211 }
6212 }
6213
6214 return SLCT_NotALiteral;
6215 }
6216 case Stmt::UnaryOperatorClass: {
6217 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6218 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6219 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6220 Expr::EvalResult IndexResult;
6221 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6224 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6225 /*RHS is int*/ true);
6226 E = ASE->getBase();
6227 goto tryAgain;
6228 }
6229 }
6230
6231 return SLCT_NotALiteral;
6232 }
6233
6234 default:
6235 return SLCT_NotALiteral;
6236 }
6237}
6238
6239// If this expression can be evaluated at compile-time,
6240// check if the result is a StringLiteral and return it
6241// otherwise return nullptr
6243 const Expr *E) {
6245 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
6246 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
6247 if (isa_and_nonnull<StringLiteral>(LVE))
6248 return LVE;
6249 }
6250 return nullptr;
6251}
6252
6254 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6255 .Case("scanf", FST_Scanf)
6256 .Cases("printf", "printf0", "syslog", FST_Printf)
6257 .Cases("NSString", "CFString", FST_NSString)
6258 .Case("strftime", FST_Strftime)
6259 .Case("strfmon", FST_Strfmon)
6260 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6261 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6262 .Case("os_trace", FST_OSLog)
6263 .Case("os_log", FST_OSLog)
6264 .Default(FST_Unknown);
6265}
6266
6267bool Sema::CheckFormatArguments(const FormatAttr *Format,
6268 ArrayRef<const Expr *> Args, bool IsCXXMember,
6269 VariadicCallType CallType, SourceLocation Loc,
6271 llvm::SmallBitVector &CheckedVarArgs) {
6272 FormatStringInfo FSI;
6273 if (getFormatStringInfo(Format, IsCXXMember, CallType != VariadicDoesNotApply,
6274 &FSI))
6275 return CheckFormatArguments(Args, FSI.ArgPassingKind, FSI.FormatIdx,
6276 FSI.FirstDataArg, GetFormatStringType(Format),
6277 CallType, Loc, Range, CheckedVarArgs);
6278 return false;
6279}
6280
6281bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6283 unsigned format_idx, unsigned firstDataArg,
6284 FormatStringType Type,
6285 VariadicCallType CallType, SourceLocation Loc,
6287 llvm::SmallBitVector &CheckedVarArgs) {
6288 // CHECK: printf/scanf-like function is called with no format string.
6289 if (format_idx >= Args.size()) {
6290 Diag(Loc, diag::warn_missing_format_string) << Range;
6291 return false;
6292 }
6293
6294 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6295
6296 // CHECK: format string is not a string literal.
6297 //
6298 // Dynamically generated format strings are difficult to
6299 // automatically vet at compile time. Requiring that format strings
6300 // are string literals: (1) permits the checking of format strings by
6301 // the compiler and thereby (2) can practically remove the source of
6302 // many format string exploits.
6303
6304 // Format string can be either ObjC string (e.g. @"%d") or
6305 // C string (e.g. "%d")
6306 // ObjC string uses the same format specifiers as C string, so we can use
6307 // the same format string checking logic for both ObjC and C strings.
6308 UncoveredArgHandler UncoveredArg;
6309 StringLiteralCheckType CT = checkFormatStringExpr(
6310 *this, OrigFormatExpr, Args, APK, format_idx, firstDataArg, Type,
6311 CallType,
6312 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
6313 /*no string offset*/ llvm::APSInt(64, false) = 0);
6314
6315 // Generate a diagnostic where an uncovered argument is detected.
6316 if (UncoveredArg.hasUncoveredArg()) {
6317 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6318 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6319 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6320 }
6321
6322 if (CT != SLCT_NotALiteral)
6323 // Literal format string found, check done!
6324 return CT == SLCT_CheckedLiteral;
6325
6326 // Strftime is particular as it always uses a single 'time' argument,
6327 // so it is safe to pass a non-literal string.
6328 if (Type == FST_Strftime)
6329 return false;
6330
6331 // Do not emit diag when the string param is a macro expansion and the
6332 // format is either NSString or CFString. This is a hack to prevent
6333 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6334 // which are usually used in place of NS and CF string literals.
6335 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
6336 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
6337 return false;
6338
6339 // If there are no arguments specified, warn with -Wformat-security, otherwise
6340 // warn only with -Wformat-nonliteral.
6341 if (Args.size() == firstDataArg) {
6342 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6343 << OrigFormatExpr->getSourceRange();
6344 switch (Type) {
6345 default:
6346 break;
6347 case FST_Kprintf:
6348 case FST_FreeBSDKPrintf:
6349 case FST_Printf:
6350 case FST_Syslog:
6351 Diag(FormatLoc, diag::note_format_security_fixit)
6352 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
6353 break;
6354 case FST_NSString:
6355 Diag(FormatLoc, diag::note_format_security_fixit)
6356 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
6357 break;
6358 }
6359 } else {
6360 Diag(FormatLoc, diag::warn_format_nonliteral)
6361 << OrigFormatExpr->getSourceRange();
6362 }
6363 return false;
6364}
6365
6366namespace {
6367
6368class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6369protected:
6370 Sema &S;
6371 const FormatStringLiteral *FExpr;
6372 const Expr *OrigFormatExpr;
6373 const Sema::FormatStringType FSType;
6374 const unsigned FirstDataArg;
6375 const unsigned NumDataArgs;
6376 const char *Beg; // Start of format string.
6377 const Sema::FormatArgumentPassingKind ArgPassingKind;
6379 unsigned FormatIdx;
6380 llvm::SmallBitVector CoveredArgs;
6381 bool usesPositionalArgs = false;
6382 bool atFirstArg = true;
6383 bool inFunctionCall;
6384 Sema::VariadicCallType CallType;
6385 llvm::SmallBitVector &CheckedVarArgs;
6386 UncoveredArgHandler &UncoveredArg;
6387
6388public:
6389 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
6390 const Expr *origFormatExpr,
6391 const Sema::FormatStringType type, unsigned firstDataArg,
6392 unsigned numDataArgs, const char *beg,
6394 ArrayRef<const Expr *> Args, unsigned formatIdx,
6395 bool inFunctionCall, Sema::VariadicCallType callType,
6396 llvm::SmallBitVector &CheckedVarArgs,
6397 UncoveredArgHandler &UncoveredArg)
6398 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
6399 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
6400 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
6401 inFunctionCall(inFunctionCall), CallType(callType),
6402 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
6403 CoveredArgs.resize(numDataArgs);
6404 CoveredArgs.reset();
6405 }
6406
6407 void DoneProcessing();
6408
6409 void HandleIncompleteSpecifier(const char *startSpecifier,
6410 unsigned specifierLen) override;
6411
6412 void HandleInvalidLengthModifier(
6415 const char *startSpecifier, unsigned specifierLen,
6416 unsigned DiagID);
6417
6418 void HandleNonStandardLengthModifier(
6420 const char *startSpecifier, unsigned specifierLen);
6421
6422 void HandleNonStandardConversionSpecifier(
6424 const char *startSpecifier, unsigned specifierLen);
6425
6426 void HandlePosition(const char *startPos, unsigned posLen) override;
6427
6428 void HandleInvalidPosition(const char *startSpecifier,
6429 unsigned specifierLen,
6431
6432 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
6433
6434 void HandleNullChar(const char *nullCharacter) override;
6435
6436 template <typename Range>
6437 static void
6438 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
6439 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
6440 bool IsStringLocation, Range StringRange,
6441 ArrayRef<FixItHint> Fixit = {});
6442
6443protected:
6444 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
6445 const char *startSpec,
6446 unsigned specifierLen,
6447 const char *csStart, unsigned csLen);
6448
6449 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
6450 const char *startSpec,
6451 unsigned specifierLen);
6452
6453 SourceRange getFormatStringRange();
6454 CharSourceRange getSpecifierRange(const char *startSpecifier,
6455 unsigned specifierLen);
6456 SourceLocation getLocationOfByte(const char *x);
6457
6458 const Expr *getDataArg(unsigned i) const;
6459
6460 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
6462 const char *startSpecifier, unsigned specifierLen,
6463 unsigned argIndex);
6464
6465 template <typename Range>
6466 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
6467 bool IsStringLocation, Range StringRange,
6468 ArrayRef<FixItHint> Fixit = {});
6469};
6470
6471} // namespace
6472
6473SourceRange CheckFormatHandler::getFormatStringRange() {
6474 return OrigFormatExpr->getSourceRange();
6475}
6476
6477CharSourceRange CheckFormatHandler::
6478getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
6479 SourceLocation Start = getLocationOfByte(startSpecifier);
6480 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
6481
6482 // Advance the end SourceLocation by one due to half-open ranges.
6483 End = End.getLocWithOffset(1);
6484
6485 return CharSourceRange::getCharRange(Start, End);
6486}
6487
6488SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
6489 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
6491}
6492
6493void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
6494 unsigned specifierLen){
6495 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
6496 getLocationOfByte(startSpecifier),
6497 /*IsStringLocation*/true,
6498 getSpecifierRange(startSpecifier, specifierLen));
6499}
6500
6501void CheckFormatHandler::HandleInvalidLengthModifier(
6504 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
6505 using namespace analyze_format_string;
6506
6507 const LengthModifier &LM = FS.getLengthModifier();
6508 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6509
6510 // See if we know how to fix this length modifier.
6511 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6512 if (FixedLM) {
6513 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6514 getLocationOfByte(LM.getStart()),
6515 /*IsStringLocation*/true,
6516 getSpecifierRange(startSpecifier, specifierLen));
6517
6518 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6519 << FixedLM->toString()
6520 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6521
6522 } else {
6523 FixItHint Hint;
6524 if (DiagID == diag::warn_format_nonsensical_length)
6525 Hint = FixItHint::CreateRemoval(LMRange);
6526
6527 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6528 getLocationOfByte(LM.getStart()),
6529 /*IsStringLocation*/true,
6530 getSpecifierRange(startSpecifier, specifierLen),
6531 Hint);
6532 }
6533}
6534
6535void CheckFormatHandler::HandleNonStandardLengthModifier(
6537 const char *startSpecifier, unsigned specifierLen) {
6538 using namespace analyze_format_string;
6539
6540 const LengthModifier &LM = FS.getLengthModifier();
6541 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6542
6543 // See if we know how to fix this length modifier.
6544 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6545 if (FixedLM) {
6546 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6547 << LM.toString() << 0,
6548 getLocationOfByte(LM.getStart()),
6549 /*IsStringLocation*/true,
6550 getSpecifierRange(startSpecifier, specifierLen));
6551
6552 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6553 << FixedLM->toString()
6554 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6555
6556 } else {
6557 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6558 << LM.toString() << 0,
6559 getLocationOfByte(LM.getStart()),
6560 /*IsStringLocation*/true,
6561 getSpecifierRange(startSpecifier, specifierLen));
6562 }
6563}
6564
6565void CheckFormatHandler::HandleNonStandardConversionSpecifier(
6567 const char *startSpecifier, unsigned specifierLen) {
6568 using namespace analyze_format_string;
6569
6570 // See if we know how to fix this conversion specifier.
6571 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
6572 if (FixedCS) {
6573 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6574 << CS.toString() << /*conversion specifier*/1,
6575 getLocationOfByte(CS.getStart()),
6576 /*IsStringLocation*/true,
6577 getSpecifierRange(startSpecifier, specifierLen));
6578
6579 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
6580 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
6581 << FixedCS->toString()
6582 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
6583 } else {
6584 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6585 << CS.toString() << /*conversion specifier*/1,
6586 getLocationOfByte(CS.getStart()),
6587 /*IsStringLocation*/true,
6588 getSpecifierRange(startSpecifier, specifierLen));
6589 }
6590}
6591
6592void CheckFormatHandler::HandlePosition(const char *startPos,
6593 unsigned posLen) {
6594 if (!S.getDiagnostics().isIgnored(
6595 diag::warn_format_non_standard_positional_arg, SourceLocation()))
6596 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
6597 getLocationOfByte(startPos),
6598 /*IsStringLocation*/ true,
6599 getSpecifierRange(startPos, posLen));
6600}
6601
6602void CheckFormatHandler::HandleInvalidPosition(
6603 const char *startSpecifier, unsigned specifierLen,
6605 if (!S.getDiagnostics().isIgnored(
6606 diag::warn_format_invalid_positional_specifier, SourceLocation()))
6607 EmitFormatDiagnostic(
6608 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
6609 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
6610 getSpecifierRange(startSpecifier, specifierLen));
6611}
6612
6613void CheckFormatHandler::HandleZeroPosition(const char *startPos,
6614 unsigned posLen) {
6615 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
6616 SourceLocation()))
6617 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
6618 getLocationOfByte(startPos),
6619 /*IsStringLocation*/ true,
6620 getSpecifierRange(startPos, posLen));
6621}
6622
6623void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
6624 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
6625 // The presence of a null character is likely an error.
6626 EmitFormatDiagnostic(
6627 S.PDiag(diag::warn_printf_format_string_contains_null_char),
6628 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
6629 getFormatStringRange());
6630 }
6631}
6632
6633// Note that this may return NULL if there was an error parsing or building
6634// one of the argument expressions.
6635const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
6636 return Args[FirstDataArg + i];
6637}
6638
6639void CheckFormatHandler::DoneProcessing() {
6640 // Does the number of data arguments exceed the number of
6641 // format conversions in the format string?
6642 if (ArgPassingKind != Sema::FAPK_VAList) {
6643 // Find any arguments that weren't covered.
6644 CoveredArgs.flip();
6645 signed notCoveredArg = CoveredArgs.find_first();
6646 if (notCoveredArg >= 0) {
6647 assert((unsigned)notCoveredArg < NumDataArgs);
6648 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
6649 } else {
6650 UncoveredArg.setAllCovered();
6651 }
6652 }
6653}
6654
6655void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
6656 const Expr *ArgExpr) {
6657 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
6658 "Invalid state");
6659
6660 if (!ArgExpr)
6661 return;
6662
6663 SourceLocation Loc = ArgExpr->getBeginLoc();
6664
6666 return;
6667
6668 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
6669 for (auto E : DiagnosticExprs)
6670 PDiag << E->getSourceRange();
6671
6672 CheckFormatHandler::EmitFormatDiagnostic(
6673 S, IsFunctionCall, DiagnosticExprs[0],
6674 PDiag, Loc, /*IsStringLocation*/false,
6675 DiagnosticExprs[0]->getSourceRange());
6676}
6677
6678bool
6679CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
6681 const char *startSpec,
6682 unsigned specifierLen,
6683 const char *csStart,
6684 unsigned csLen) {
6685 bool keepGoing = true;
6686 if (argIndex < NumDataArgs) {
6687 // Consider the argument coverered, even though the specifier doesn't
6688 // make sense.
6689 CoveredArgs.set(argIndex);
6690 }
6691 else {
6692 // If argIndex exceeds the number of data arguments we
6693 // don't issue a warning because that is just a cascade of warnings (and
6694 // they may have intended '%%' anyway). We don't want to continue processing
6695 // the format string after this point, however, as we will like just get
6696 // gibberish when trying to match arguments.
6697 keepGoing = false;
6698 }
6699
6700 StringRef Specifier(csStart, csLen);
6701
6702 // If the specifier in non-printable, it could be the first byte of a UTF-8
6703 // sequence. In that case, print the UTF-8 code point. If not, print the byte
6704 // hex value.
6705 std::string CodePointStr;
6706 if (!llvm::sys::locale::isPrint(*csStart)) {
6707 llvm::UTF32 CodePoint;
6708 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
6709 const llvm::UTF8 *E =
6710 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
6711 llvm::ConversionResult Result =
6712 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
6713
6714 if (Result != llvm::conversionOK) {
6715 unsigned char FirstChar = *csStart;
6716 CodePoint = (llvm::UTF32)FirstChar;
6717 }
6718
6719 llvm::raw_string_ostream OS(CodePointStr);
6720 if (CodePoint < 256)
6721 OS << "\\x" << llvm::format("%02x", CodePoint);
6722 else if (CodePoint <= 0xFFFF)
6723 OS << "\\u" << llvm::format("%04x", CodePoint);
6724 else
6725 OS << "\\U" << llvm::format("%08x", CodePoint);
6726 Specifier = CodePointStr;
6727 }
6728
6729 EmitFormatDiagnostic(
6730 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
6731 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
6732
6733 return keepGoing;
6734}
6735
6736void
6737CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
6738 const char *startSpec,
6739 unsigned specifierLen) {
6740 EmitFormatDiagnostic(
6741 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
6742 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
6743}
6744
6745bool
6746CheckFormatHandler::CheckNumArgs(
6749 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
6750
6751 if (argIndex >= NumDataArgs) {
6752 PartialDiagnostic PDiag = FS.usesPositionalArg()
6753 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
6754 << (argIndex+1) << NumDataArgs)
6755 : S.PDiag(diag::warn_printf_insufficient_data_args);
6756 EmitFormatDiagnostic(
6757 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
6758 getSpecifierRange(startSpecifier, specifierLen));
6759
6760 // Since more arguments than conversion tokens are given, by extension
6761 // all arguments are covered, so mark this as so.
6762 UncoveredArg.setAllCovered();
6763 return false;
6764 }
6765 return true;
6766}
6767
6768template<typename Range>
6769void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
6771 bool IsStringLocation,
6772 Range StringRange,
6773 ArrayRef<FixItHint> FixIt) {
6774 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
6775 Loc, IsStringLocation, StringRange, FixIt);
6776}
6777
6778/// If the format string is not within the function call, emit a note
6779/// so that the function call and string are in diagnostic messages.
6780///
6781/// \param InFunctionCall if true, the format string is within the function
6782/// call and only one diagnostic message will be produced. Otherwise, an
6783/// extra note will be emitted pointing to location of the format string.
6784///
6785/// \param ArgumentExpr the expression that is passed as the format string
6786/// argument in the function call. Used for getting locations when two
6787/// diagnostics are emitted.
6788///
6789/// \param PDiag the callee should already have provided any strings for the
6790/// diagnostic message. This function only adds locations and fixits
6791/// to diagnostics.
6792///
6793/// \param Loc primary location for diagnostic. If two diagnostics are
6794/// required, one will be at Loc and a new SourceLocation will be created for
6795/// the other one.
6796///
6797/// \param IsStringLocation if true, Loc points to the format string should be
6798/// used for the note. Otherwise, Loc points to the argument list and will
6799/// be used with PDiag.
6800///
6801/// \param StringRange some or all of the string to highlight. This is
6802/// templated so it can accept either a CharSourceRange or a SourceRange.
6803///
6804/// \param FixIt optional fix it hint for the format string.
6805template <typename Range>
6806void CheckFormatHandler::EmitFormatDiagnostic(
6807 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
6808 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
6809 Range StringRange, ArrayRef<FixItHint> FixIt) {
6810 if (InFunctionCall) {
6811 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
6812 D << StringRange;
6813 D << FixIt;
6814 } else {
6815 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
6816 << ArgumentExpr->getSourceRange();
6817
6819 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
6820 diag::note_format_string_defined);
6821
6822 Note << StringRange;
6823 Note << FixIt;
6824 }
6825}
6826
6827//===--- CHECK: Printf format string checking -----------------------------===//
6828
6829namespace {
6830
6831class CheckPrintfHandler : public CheckFormatHandler {
6832public:
6833 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
6834 const Expr *origFormatExpr,
6835 const Sema::FormatStringType type, unsigned firstDataArg,
6836 unsigned numDataArgs, bool isObjC, const char *beg,
6838 ArrayRef<const Expr *> Args, unsigned formatIdx,
6839 bool inFunctionCall, Sema::VariadicCallType CallType,
6840 llvm::SmallBitVector &CheckedVarArgs,
6841 UncoveredArgHandler &UncoveredArg)
6842 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6843 numDataArgs, beg, APK, Args, formatIdx,
6844 inFunctionCall, CallType, CheckedVarArgs,
6845 UncoveredArg) {}
6846
6847 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
6848
6849 /// Returns true if '%@' specifiers are allowed in the format string.
6850 bool allowsObjCArg() const {
6851 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
6852 FSType == Sema::FST_OSTrace;
6853 }
6854
6855 bool HandleInvalidPrintfConversionSpecifier(
6857 const char *startSpecifier,
6858 unsigned specifierLen) override;
6859
6860 void handleInvalidMaskType(StringRef MaskType) override;
6861
6862 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
6863 const char *startSpecifier, unsigned specifierLen,
6864 const TargetInfo &Target) override;
6865 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6866 const char *StartSpecifier,
6867 unsigned SpecifierLen,
6868 const Expr *E);
6869
6870 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
6871 const char *startSpecifier, unsigned specifierLen);
6872 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
6874 unsigned type,
6875 const char *startSpecifier, unsigned specifierLen);
6876 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
6877 const analyze_printf::OptionalFlag &flag,
6878 const char *startSpecifier, unsigned specifierLen);
6879 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
6880 const analyze_printf::OptionalFlag &ignoredFlag,
6881 const analyze_printf::OptionalFlag &flag,
6882 const char *startSpecifier, unsigned specifierLen);
6883 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
6884 const Expr *E);
6885
6886 void HandleEmptyObjCModifierFlag(const char *startFlag,
6887 unsigned flagLen) override;
6888
6889 void HandleInvalidObjCModifierFlag(const char *startFlag,
6890 unsigned flagLen) override;
6891
6892 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
6893 const char *flagsEnd,
6894 const char *conversionPosition)
6895 override;
6896};
6897
6898} // namespace
6899
6900bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
6902 const char *startSpecifier,
6903 unsigned specifierLen) {
6905 FS.getConversionSpecifier();
6906
6907 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6908 getLocationOfByte(CS.getStart()),
6909 startSpecifier, specifierLen,
6910 CS.getStart(), CS.getLength());
6911}
6912
6913void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
6914 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
6915}
6916
6917bool CheckPrintfHandler::HandleAmount(
6918 const analyze_format_string::OptionalAmount &Amt, unsigned k,
6919 const char *startSpecifier, unsigned specifierLen) {
6920 if (Amt.hasDataArgument()) {
6921 if (ArgPassingKind != Sema::FAPK_VAList) {
6922 unsigned argIndex = Amt.getArgIndex();
6923 if (argIndex >= NumDataArgs) {
6924 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
6925 << k,
6926 getLocationOfByte(Amt.getStart()),
6927 /*IsStringLocation*/ true,
6928 getSpecifierRange(startSpecifier, specifierLen));
6929 // Don't do any more checking. We will just emit
6930 // spurious errors.
6931 return false;
6932 }
6933
6934 // Type check the data argument. It should be an 'int'.
6935 // Although not in conformance with C99, we also allow the argument to be
6936 // an 'unsigned int' as that is a reasonably safe case. GCC also
6937 // doesn't emit a warning for that case.
6938 CoveredArgs.set(argIndex);
6939 const Expr *Arg = getDataArg(argIndex);
6940 if (!Arg)
6941 return false;
6942
6943 QualType T = Arg->getType();
6944
6945 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
6946 assert(AT.isValid());
6947
6948 if (!AT.matchesType(S.Context, T)) {
6949 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
6951 << T << Arg->getSourceRange(),
6952 getLocationOfByte(Amt.getStart()),
6953 /*IsStringLocation*/true,
6954 getSpecifierRange(startSpecifier, specifierLen));
6955 // Don't do any more checking. We will just emit
6956 // spurious errors.
6957 return false;
6958 }
6959 }
6960 }
6961 return true;
6962}
6963
6964void CheckPrintfHandler::HandleInvalidAmount(
6967 unsigned type,
6968 const char *startSpecifier,
6969 unsigned specifierLen) {
6971 FS.getConversionSpecifier();
6972
6973 FixItHint fixit =
6975 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
6976 Amt.getConstantLength()))
6977 : FixItHint();
6978
6979 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
6980 << type << CS.toString(),
6981 getLocationOfByte(Amt.getStart()),
6982 /*IsStringLocation*/true,
6983 getSpecifierRange(startSpecifier, specifierLen),
6984 fixit);
6985}
6986
6987void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
6988 const analyze_printf::OptionalFlag &flag,
6989 const char *startSpecifier,
6990 unsigned specifierLen) {
6991 // Warn about pointless flag with a fixit removal.
6993 FS.getConversionSpecifier();
6994 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
6995 << flag.toString() << CS.toString(),
6996 getLocationOfByte(flag.getPosition()),
6997 /*IsStringLocation*/true,
6998 getSpecifierRange(startSpecifier, specifierLen),
7000 getSpecifierRange(flag.getPosition(), 1)));
7001}
7002
7003void CheckPrintfHandler::HandleIgnoredFlag(
7005 const analyze_printf::OptionalFlag &ignoredFlag,
7006 const analyze_printf::OptionalFlag &flag,
7007 const char *startSpecifier,
7008 unsigned specifierLen) {
7009 // Warn about ignored flag with a fixit removal.
7010 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7011 << ignoredFlag.toString() << flag.toString(),
7012 getLocationOfByte(ignoredFlag.getPosition()),
7013 /*IsStringLocation*/true,
7014 getSpecifierRange(startSpecifier, specifierLen),
7016 getSpecifierRange(ignoredFlag.getPosition(), 1)));
7017}
7018
7019void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7020 unsigned flagLen) {
7021 // Warn about an empty flag.
7022 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7023 getLocationOfByte(startFlag),
7024 /*IsStringLocation*/true,
7025 getSpecifierRange(startFlag, flagLen));
7026}
7027
7028void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7029 unsigned flagLen) {
7030 // Warn about an invalid flag.
7031 auto Range = getSpecifierRange(startFlag, flagLen);
7032 StringRef flag(startFlag, flagLen);
7033 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7034 getLocationOfByte(startFlag),
7035 /*IsStringLocation*/true,
7037}
7038
7039void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7040 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7041 // Warn about using '[...]' without a '@' conversion.
7042 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7043 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7044 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7045 getLocationOfByte(conversionPosition),
7046 /*IsStringLocation*/true,
7048}
7049
7050// Determines if the specified is a C++ class or struct containing
7051// a member with the specified name and kind (e.g. a CXXMethodDecl named
7052// "c_str()").
7053template<typename MemberKind>
7055CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7056 const RecordType *RT = Ty->getAs<RecordType>();
7058
7059 if (!RT)
7060 return Results;
7061 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7062 if (!RD || !RD->getDefinition())
7063 return Results;
7064
7065 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7068
7069 // We just need to include all members of the right kind turned up by the
7070 // filter, at this point.
7071 if (S.LookupQualifiedName(R, RT->getDecl()))
7072 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7073 NamedDecl *decl = (*I)->getUnderlyingDecl();
7074 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7075 Results.insert(FK);
7076 }
7077 return Results;
7078}
7079
7080/// Check if we could call '.c_str()' on an object.
7081///
7082/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7083/// allow the call, or if it would be ambiguous).
7085 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7086
7087 MethodSet Results =
7088 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7089 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7090 MI != ME; ++MI)
7091 if ((*MI)->getMinRequiredArguments() == 0)
7092 return true;
7093 return false;
7094}
7095
7096// Check if a (w)string was passed when a (w)char* was needed, and offer a
7097// better diagnostic if so. AT is assumed to be valid.
7098// Returns true when a c_str() conversion method is found.
7099bool CheckPrintfHandler::checkForCStrMembers(
7100 const analyze_printf::ArgType &AT, const Expr *E) {
7101 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7102
7103 MethodSet Results =
7104 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7105
7106 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7107 MI != ME; ++MI) {
7108 const CXXMethodDecl *Method = *MI;
7109 if (Method->getMinRequiredArguments() == 0 &&
7110 AT.matchesType(S.Context, Method->getReturnType())) {
7111 // FIXME: Suggest parens if the expression needs them.
7113 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7114 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7115 return true;
7116 }
7117 }
7118
7119 return false;
7120}
7121
7122bool CheckPrintfHandler::HandlePrintfSpecifier(
7123 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
7124 unsigned specifierLen, const TargetInfo &Target) {
7125 using namespace analyze_format_string;
7126 using namespace analyze_printf;
7127
7128 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7129
7130 if (FS.consumesDataArgument()) {
7131 if (atFirstArg) {
7132 atFirstArg = false;
7133 usesPositionalArgs = FS.usesPositionalArg();
7134 }
7135 else if (usesPositionalArgs != FS.usesPositionalArg()) {
7136 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7137 startSpecifier, specifierLen);
7138 return false;
7139 }
7140 }
7141
7142 // First check if the field width, precision, and conversion specifier
7143 // have matching data arguments.
7144 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7145 startSpecifier, specifierLen)) {
7146 return false;
7147 }
7148
7149 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7150 startSpecifier, specifierLen)) {
7151 return false;
7152 }
7153
7154 if (!CS.consumesDataArgument()) {
7155 // FIXME: Technically specifying a precision or field width here
7156 // makes no sense. Worth issuing a warning at some point.
7157 return true;
7158 }
7159
7160 // Consume the argument.
7161 unsigned argIndex = FS.getArgIndex();
7162 if (argIndex < NumDataArgs) {
7163 // The check to see if the argIndex is valid will come later.
7164 // We set the bit here because we may exit early from this
7165 // function if we encounter some other error.
7166 CoveredArgs.set(argIndex);
7167 }
7168
7169 // FreeBSD kernel extensions.
7170 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7171 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7172 // We need at least two arguments.
7173 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7174 return false;
7175
7176 // Claim the second argument.
7177 CoveredArgs.set(argIndex + 1);
7178
7179 // Type check the first argument (int for %b, pointer for %D)
7180 const Expr *Ex = getDataArg(argIndex);
7181 const analyze_printf::ArgType &AT =
7182 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7183 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7184 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7185 EmitFormatDiagnostic(
7186 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7187 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7188 << false << Ex->getSourceRange(),
7189 Ex->getBeginLoc(), /*IsStringLocation*/ false,
7190 getSpecifierRange(startSpecifier, specifierLen));
7191
7192 // Type check the second argument (char * for both %b and %D)
7193 Ex = getDataArg(argIndex + 1);
7194 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7195 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7196 EmitFormatDiagnostic(
7197 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7198 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7199 << false << Ex->getSourceRange(),
7200 Ex->getBeginLoc(), /*IsStringLocation*/ false,
7201 getSpecifierRange(startSpecifier, specifierLen));
7202
7203 return true;
7204 }
7205
7206 // Check for using an Objective-C specific conversion specifier
7207 // in a non-ObjC literal.
7208 if (!allowsObjCArg() && CS.isObjCArg()) {
7209 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7210 specifierLen);
7211 }
7212
7213 // %P can only be used with os_log.
7214 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7215 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7216 specifierLen);
7217 }
7218
7219 // %n is not allowed with os_log.
7220 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7221 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7222 getLocationOfByte(CS.getStart()),
7223 /*IsStringLocation*/ false,
7224 getSpecifierRange(startSpecifier, specifierLen));
7225
7226 return true;
7227 }
7228
7229 // Only scalars are allowed for os_trace.
7230 if (FSType == Sema::FST_OSTrace &&
7231 (CS.getKind() == ConversionSpecifier::PArg ||
7232 CS.getKind() == ConversionSpecifier::sArg ||
7233 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7234 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7235 specifierLen);
7236 }
7237
7238 // Check for use of public/private annotation outside of os_log().
7239 if (FSType != Sema::FST_OSLog) {
7240 if (FS.isPublic().isSet()) {
7241 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7242 << "public",
7243 getLocationOfByte(FS.isPublic().getPosition()),
7244 /*IsStringLocation*/ false,
7245 getSpecifierRange(startSpecifier, specifierLen));
7246 }
7247 if (FS.isPrivate().isSet()) {
7248 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7249 << "private",
7250 getLocationOfByte(FS.isPrivate().getPosition()),
7251 /*IsStringLocation*/ false,
7252 getSpecifierRange(startSpecifier, specifierLen));
7253 }
7254 }
7255
7256 const llvm::Triple &Triple = Target.getTriple();
7257 if (CS.getKind() == ConversionSpecifier::nArg &&
7258 (Triple.isAndroid() || Triple.isOSFuchsia())) {
7259 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
7260 getLocationOfByte(CS.getStart()),
7261 /*IsStringLocation*/ false,
7262 getSpecifierRange(startSpecifier, specifierLen));
7263 }
7264
7265 // Check for invalid use of field width
7266 if (!FS.hasValidFieldWidth()) {
7267 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7268 startSpecifier, specifierLen);
7269 }
7270
7271 // Check for invalid use of precision
7272 if (!FS.hasValidPrecision()) {
7273 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7274 startSpecifier, specifierLen);
7275 }
7276
7277 // Precision is mandatory for %P specifier.
7278 if (CS.getKind() == ConversionSpecifier::PArg &&
7279 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7280 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7281 getLocationOfByte(startSpecifier),
7282 /*IsStringLocation*/ false,
7283 getSpecifierRange(startSpecifier, specifierLen));
7284 }
7285
7286 // Check each flag does not conflict with any other component.
7287 if (!FS.hasValidThousandsGroupingPrefix())
7288 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7289 if (!FS.hasValidLeadingZeros())
7290 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7291 if (!FS.hasValidPlusPrefix())
7292 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7293 if (!FS.hasValidSpacePrefix())
7294 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7295 if (!FS.hasValidAlternativeForm())
7296 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7297 if (!FS.hasValidLeftJustified())
7298 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7299
7300 // Check that flags are not ignored by another flag
7301 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7302 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7303 startSpecifier, specifierLen);
7304 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7305 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7306 startSpecifier, specifierLen);
7307
7308 // Check the length modifier is valid with the given conversion specifier.
7309 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7310 S.getLangOpts()))
7311 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7312 diag::warn_format_nonsensical_length);
7313 else if (!FS.hasStandardLengthModifier())
7314 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7315 else if (!FS.hasStandardLengthConversionCombination())
7316 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7317 diag::warn_format_non_standard_conversion_spec);
7318
7319 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7320 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7321
7322 // The remaining checks depend on the data arguments.
7323 if (ArgPassingKind == Sema::FAPK_VAList)
7324 return true;
7325
7326 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7327 return false;
7328
7329 const Expr *Arg = getDataArg(argIndex);
7330 if (!Arg)
7331 return true;
7332
7333 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
7334}
7335
7336static bool requiresParensToAddCast(const Expr *E) {
7337 // FIXME: We should have a general way to reason about operator
7338 // precedence and whether parens are actually needed here.
7339 // Take care of a few common cases where they aren't.
7340 const Expr *Inside = E->IgnoreImpCasts();
7341 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7342 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7343
7344 switch (Inside->getStmtClass()) {
7345 case Stmt::ArraySubscriptExprClass:
7346 case Stmt::CallExprClass:
7347 case Stmt::CharacterLiteralClass:
7348 case Stmt::CXXBoolLiteralExprClass:
7349 case Stmt::DeclRefExprClass:
7350 case Stmt::FloatingLiteralClass:
7351 case Stmt::IntegerLiteralClass:
7352 case Stmt::MemberExprClass:
7353 case Stmt::ObjCArrayLiteralClass:
7354 case Stmt::ObjCBoolLiteralExprClass:
7355 case Stmt::ObjCBoxedExprClass:
7356 case Stmt::ObjCDictionaryLiteralClass:
7357 case Stmt::ObjCEncodeExprClass:
7358 case Stmt::ObjCIvarRefExprClass:
7359 case Stmt::ObjCMessageExprClass:
7360 case Stmt::ObjCPropertyRefExprClass:
7361 case Stmt::ObjCStringLiteralClass:
7362 case Stmt::ObjCSubscriptRefExprClass:
7363 case Stmt::ParenExprClass:
7364 case Stmt::StringLiteralClass:
7365 case Stmt::UnaryOperatorClass:
7366 return false;
7367 default:
7368 return true;
7369 }
7370}
7371
7372static std::pair<QualType, StringRef>
7374 QualType IntendedTy,
7375 const Expr *E) {
7376 // Use a 'while' to peel off layers of typedefs.
7377 QualType TyTy = IntendedTy;
7378 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
7379 StringRef Name = UserTy->getDecl()->getName();
7380 QualType CastTy = llvm::StringSwitch<QualType>(Name)
7381 .Case("CFIndex", Context.getNSIntegerType())
7382 .Case("NSInteger", Context.getNSIntegerType())
7383 .Case("NSUInteger", Context.getNSUIntegerType())
7384 .Case("SInt32", Context.IntTy)
7385 .Case("UInt32", Context.UnsignedIntTy)
7386 .Default(QualType());
7387
7388 if (!CastTy.isNull())
7389 return std::make_pair(CastTy, Name);
7390
7391 TyTy = UserTy->desugar();
7392 }
7393
7394 // Strip parens if necessary.
7395 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
7396 return shouldNotPrintDirectly(Context,
7397 PE->getSubExpr()->getType(),
7398 PE->getSubExpr());
7399
7400 // If this is a conditional expression, then its result type is constructed
7401 // via usual arithmetic conversions and thus there might be no necessary
7402 // typedef sugar there. Recurse to operands to check for NSInteger &
7403 // Co. usage condition.
7404 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7405 QualType TrueTy, FalseTy;
7406 StringRef TrueName, FalseName;
7407
7408 std::tie(TrueTy, TrueName) =
7409 shouldNotPrintDirectly(Context,
7410 CO->getTrueExpr()->getType(),
7411 CO->getTrueExpr());
7412 std::tie(FalseTy, FalseName) =
7413 shouldNotPrintDirectly(Context,
7414 CO->getFalseExpr()->getType(),
7415 CO->getFalseExpr());
7416
7417 if (TrueTy == FalseTy)
7418 return std::make_pair(TrueTy, TrueName);
7419 else if (TrueTy.isNull())
7420 return std::make_pair(FalseTy, FalseName);
7421 else if (FalseTy.isNull())
7422 return std::make_pair(TrueTy, TrueName);
7423 }
7424
7425 return std::make_pair(QualType(), StringRef());
7426}
7427
7428/// Return true if \p ICE is an implicit argument promotion of an arithmetic
7429/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
7430/// type do not count.
7431static bool
7433 QualType From = ICE->getSubExpr()->getType();
7434 QualType To = ICE->getType();
7435 // It's an integer promotion if the destination type is the promoted
7436 // source type.
7437 if (ICE->getCastKind() == CK_IntegralCast &&
7439 S.Context.getPromotedIntegerType(From) == To)
7440 return true;
7441 // Look through vector types, since we do default argument promotion for
7442 // those in OpenCL.
7443 if (const auto *VecTy = From->getAs<ExtVectorType>())
7444 From = VecTy->getElementType();
7445 if (const auto *VecTy = To->getAs<ExtVectorType>())
7446 To = VecTy->getElementType();
7447 // It's a floating promotion if the source type is a lower rank.
7448 return ICE->getCastKind() == CK_FloatingCast &&
7449 S.Context.getFloatingTypeOrder(From, To) < 0;
7450}
7451
7456 Match =
7457 Diags.isIgnored(
7458 diag::warn_format_conversion_argument_type_mismatch_signedness, Loc)
7461 }
7462 return Match;
7463}
7464
7465bool
7466CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7467 const char *StartSpecifier,
7468 unsigned SpecifierLen,
7469 const Expr *E) {
7470 using namespace analyze_format_string;
7471 using namespace analyze_printf;
7472
7473 // Now type check the data expression that matches the
7474 // format specifier.
7475 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
7476 if (!AT.isValid())
7477 return true;
7478
7479 QualType ExprTy = E->getType();
7480 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
7481 ExprTy = TET->getUnderlyingExpr()->getType();
7482 }
7483
7484 // When using the format attribute in C++, you can receive a function or an
7485 // array that will necessarily decay to a pointer when passed to the final
7486 // format consumer. Apply decay before type comparison.
7487 if (ExprTy->canDecayToPointerType())
7488 ExprTy = S.Context.getDecayedType(ExprTy);
7489
7490 // Diagnose attempts to print a boolean value as a character. Unlike other
7491 // -Wformat diagnostics, this is fine from a type perspective, but it still
7492 // doesn't make sense.
7493 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
7495 const CharSourceRange &CSR =
7496 getSpecifierRange(StartSpecifier, SpecifierLen);
7497 SmallString<4> FSString;
7498 llvm::raw_svector_ostream os(FSString);
7499 FS.toString(os);
7500 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
7501 << FSString,
7502 E->getExprLoc(), false, CSR);
7503 return true;
7504 }
7505
7506 // Diagnose attempts to use '%P' with ObjC object types, which will result in
7507 // dumping raw class data (like is-a pointer), not actual data.
7508 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::PArg &&
7509 ExprTy->isObjCObjectPointerType()) {
7510 const CharSourceRange &CSR =
7511 getSpecifierRange(StartSpecifier, SpecifierLen);
7512 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
7513 E->getExprLoc(), false, CSR);
7514 return true;
7515 }
7516
7517 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
7518 ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
7519 ArgType::MatchKind OrigMatch = Match;
7520
7521 Match = handleFormatSignedness(Match, S.getDiagnostics(), E->getExprLoc());
7522 if (Match == ArgType::Match)
7523 return true;
7524
7525 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
7526 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
7527
7528 // Look through argument promotions for our error message's reported type.
7529 // This includes the integral and floating promotions, but excludes array
7530 // and function pointer decay (seeing that an argument intended to be a
7531 // string has type 'char [6]' is probably more confusing than 'char *') and
7532 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
7533 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7534 if (isArithmeticArgumentPromotion(S, ICE)) {
7535 E = ICE->getSubExpr();
7536 ExprTy = E->getType();
7537
7538 // Check if we didn't match because of an implicit cast from a 'char'
7539 // or 'short' to an 'int'. This is done because printf is a varargs
7540 // function.
7541 if (ICE->getType() == S.Context.IntTy ||
7542 ICE->getType() == S.Context.UnsignedIntTy) {
7543 // All further checking is done on the subexpression
7544 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
7545 if (OrigMatch == ArgType::NoMatchSignedness &&
7546 ImplicitMatch != ArgType::NoMatchSignedness)
7547 // If the original match was a signedness match this match on the
7548 // implicit cast type also need to be signedness match otherwise we
7549 // might introduce new unexpected warnings from -Wformat-signedness.
7550 return true;
7551 ImplicitMatch = handleFormatSignedness(
7552 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
7553 if (ImplicitMatch == ArgType::Match)
7554 return true;
7555 }
7556 }
7557 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
7558 // Special case for 'a', which has type 'int' in C.
7559 // Note, however, that we do /not/ want to treat multibyte constants like
7560 // 'MooV' as characters! This form is deprecated but still exists. In
7561 // addition, don't treat expressions as of type 'char' if one byte length
7562 // modifier is provided.
7563 if (ExprTy == S.Context.IntTy &&
7564 FS.getLengthModifier().getKind() != LengthModifier::AsChar)
7565 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
7566 ExprTy = S.Context.CharTy;
7567 // To improve check results, we consider a character literal in C
7568 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
7569 // more likely a type confusion situation, so we will suggest to
7570 // use '%hhd' instead by discarding the MatchPromotion.
7571 if (Match == ArgType::MatchPromotion)
7572 Match = ArgType::NoMatch;
7573 }
7574 }
7575 if (Match == ArgType::MatchPromotion) {
7576 // WG14 N2562 only clarified promotions in *printf
7577 // For NSLog in ObjC, just preserve -Wformat behavior
7578 if (!S.getLangOpts().ObjC &&
7579 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
7580 ImplicitMatch != ArgType::NoMatchTypeConfusion)
7581 return true;
7582 Match = ArgType::NoMatch;
7583 }
7584 if (ImplicitMatch == ArgType::NoMatchPedantic ||
7585 ImplicitMatch == ArgType::NoMatchTypeConfusion)
7586 Match = ImplicitMatch;
7587 assert(Match != ArgType::MatchPromotion);
7588
7589 // Look through unscoped enums to their underlying type.
7590 bool IsEnum = false;
7591 bool IsScopedEnum = false;
7592 QualType IntendedTy = ExprTy;
7593 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
7594 IntendedTy = EnumTy->getDecl()->getIntegerType();
7595 if (EnumTy->isUnscopedEnumerationType()) {
7596 ExprTy = IntendedTy;
7597 // This controls whether we're talking about the underlying type or not,
7598 // which we only want to do when it's an unscoped enum.
7599 IsEnum = true;
7600 } else {
7601 IsScopedEnum = true;
7602 }
7603 }
7604
7605 // %C in an Objective-C context prints a unichar, not a wchar_t.
7606 // If the argument is an integer of some kind, believe the %C and suggest
7607 // a cast instead of changing the conversion specifier.
7608 if (isObjCContext() &&
7609 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
7611 !ExprTy->isCharType()) {
7612 // 'unichar' is defined as a typedef of unsigned short, but we should
7613 // prefer using the typedef if it is visible.
7614 IntendedTy = S.Context.UnsignedShortTy;
7615
7616 // While we are here, check if the value is an IntegerLiteral that happens
7617 // to be within the valid range.
7618 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
7619 const llvm::APInt &V = IL->getValue();
7620 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
7621 return true;
7622 }
7623
7624 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
7626 if (S.LookupName(Result, S.getCurScope())) {
7627 NamedDecl *ND = Result.getFoundDecl();
7628 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
7629 if (TD->getUnderlyingType() == IntendedTy)
7630 IntendedTy = S.Context.getTypedefType(TD);
7631 }
7632 }
7633 }
7634
7635 // Special-case some of Darwin's platform-independence types by suggesting
7636 // casts to primitive types that are known to be large enough.
7637 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
7638 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
7639 QualType CastTy;
7640 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
7641 if (!CastTy.isNull()) {
7642 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
7643 // (long in ASTContext). Only complain to pedants or when they're the
7644 // underlying type of a scoped enum (which always needs a cast).
7645 if (!IsScopedEnum &&
7646 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
7647 (AT.isSizeT() || AT.isPtrdiffT()) &&
7648 AT.matchesType(S.Context, CastTy))
7649 Match = ArgType::NoMatchPedantic;
7650 IntendedTy = CastTy;
7651 ShouldNotPrintDirectly = true;
7652 }
7653 }
7654
7655 // We may be able to offer a FixItHint if it is a supported type.
7656 PrintfSpecifier fixedFS = FS;
7657 bool Success =
7658 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
7659
7660 if (Success) {
7661 // Get the fix string from the fixed format specifier
7662 SmallString<16> buf;
7663 llvm::raw_svector_ostream os(buf);
7664 fixedFS.toString(os);
7665
7666 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
7667
7668 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
7669 unsigned Diag;
7670 switch (Match) {
7671 case ArgType::Match:
7672 case ArgType::MatchPromotion:
7673 case ArgType::NoMatchPromotionTypeConfusion:
7674 case ArgType::NoMatchSignedness:
7675 llvm_unreachable("expected non-matching");
7676 case ArgType::NoMatchPedantic:
7677 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
7678 break;
7679 case ArgType::NoMatchTypeConfusion:
7680 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
7681 break;
7682 case ArgType::NoMatch:
7683 Diag = diag::warn_format_conversion_argument_type_mismatch;
7684 break;
7685 }
7686
7687 // In this case, the specifier is wrong and should be changed to match
7688 // the argument.
7689 EmitFormatDiagnostic(S.PDiag(Diag)
7691 << IntendedTy << IsEnum << E->getSourceRange(),
7692 E->getBeginLoc(),
7693 /*IsStringLocation*/ false, SpecRange,
7694 FixItHint::CreateReplacement(SpecRange, os.str()));
7695 } else {
7696 // The canonical type for formatting this value is different from the
7697 // actual type of the expression. (This occurs, for example, with Darwin's
7698 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
7699 // should be printed as 'long' for 64-bit compatibility.)
7700 // Rather than emitting a normal format/argument mismatch, we want to
7701 // add a cast to the recommended type (and correct the format string
7702 // if necessary). We should also do so for scoped enumerations.
7703 SmallString<16> CastBuf;
7704 llvm::raw_svector_ostream CastFix(CastBuf);
7705 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
7706 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
7707 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
7708
7710 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
7711 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
7712 E->getExprLoc());
7713 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
7714 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
7715
7716 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
7717 // If there's already a cast present, just replace it.
7718 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
7719 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
7720
7721 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
7722 // If the expression has high enough precedence,
7723 // just write the C-style cast.
7724 Hints.push_back(
7725 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
7726 } else {
7727 // Otherwise, add parens around the expression as well as the cast.
7728 CastFix << "(";
7729 Hints.push_back(
7730 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
7731
7732 // We don't use getLocForEndOfToken because it returns invalid source
7733 // locations for macro expansions (by design).
7737 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
7738 }
7739
7740 if (ShouldNotPrintDirectly && !IsScopedEnum) {
7741 // The expression has a type that should not be printed directly.
7742 // We extract the name from the typedef because we don't want to show
7743 // the underlying type in the diagnostic.
7744 StringRef Name;
7745 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
7746 Name = TypedefTy->getDecl()->getName();
7747 else
7748 Name = CastTyName;
7749 unsigned Diag = Match == ArgType::NoMatchPedantic
7750 ? diag::warn_format_argument_needs_cast_pedantic
7751 : diag::warn_format_argument_needs_cast;
7752 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
7753 << E->getSourceRange(),
7754 E->getBeginLoc(), /*IsStringLocation=*/false,
7755 SpecRange, Hints);
7756 } else {
7757 // In this case, the expression could be printed using a different
7758 // specifier, but we've decided that the specifier is probably correct
7759 // and we should cast instead. Just use the normal warning message.
7760
7761 unsigned Diag =
7762 IsScopedEnum
7763 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7764 : diag::warn_format_conversion_argument_type_mismatch;
7765
7766 EmitFormatDiagnostic(
7767 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
7768 << IsEnum << E->getSourceRange(),
7769 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
7770 }
7771 }
7772 } else {
7773 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
7774 SpecifierLen);
7775 // Since the warning for passing non-POD types to variadic functions
7776 // was deferred until now, we emit a warning for non-POD
7777 // arguments here.
7778 bool EmitTypeMismatch = false;
7779 switch (S.isValidVarArgType(ExprTy)) {
7780 case Sema::VAK_Valid:
7782 unsigned Diag;
7783 switch (Match) {
7784 case ArgType::Match:
7785 case ArgType::MatchPromotion:
7786 case ArgType::NoMatchPromotionTypeConfusion:
7787 case ArgType::NoMatchSignedness:
7788 llvm_unreachable("expected non-matching");
7789 case ArgType::NoMatchPedantic:
7790 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
7791 break;
7792 case ArgType::NoMatchTypeConfusion:
7793 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
7794 break;
7795 case ArgType::NoMatch:
7796 Diag = diag::warn_format_conversion_argument_type_mismatch;
7797 break;
7798 }
7799
7800 EmitFormatDiagnostic(
7801 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
7802 << IsEnum << CSR << E->getSourceRange(),
7803 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
7804 break;
7805 }
7808 if (CallType == Sema::VariadicDoesNotApply) {
7809 EmitTypeMismatch = true;
7810 } else {
7811 EmitFormatDiagnostic(
7812 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
7813 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
7814 << AT.getRepresentativeTypeName(S.Context) << CSR
7815 << E->getSourceRange(),
7816 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
7817 checkForCStrMembers(AT, E);
7818 }
7819 break;
7820
7821 case Sema::VAK_Invalid:
7822 if (CallType == Sema::VariadicDoesNotApply)
7823 EmitTypeMismatch = true;
7824 else if (ExprTy->isObjCObjectType())
7825 EmitFormatDiagnostic(
7826 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
7827 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
7828 << AT.getRepresentativeTypeName(S.Context) << CSR
7829 << E->getSourceRange(),
7830 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
7831 else
7832 // FIXME: If this is an initializer list, suggest removing the braces
7833 // or inserting a cast to the target type.
7834 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
7835 << isa<InitListExpr>(E) << ExprTy << CallType
7837 break;
7838 }
7839
7840 if (EmitTypeMismatch) {
7841 // The function is not variadic, so we do not generate warnings about
7842 // being allowed to pass that object as a variadic argument. Instead,
7843 // since there are inherently no printf specifiers for types which cannot
7844 // be passed as variadic arguments, emit a plain old specifier mismatch
7845 // argument.
7846 EmitFormatDiagnostic(
7847 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7848 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
7849 << E->getSourceRange(),
7850 E->getBeginLoc(), false, CSR);
7851 }
7852
7853 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
7854 "format string specifier index out of range");
7855 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
7856 }
7857
7858 return true;
7859}
7860
7861//===--- CHECK: Scanf format string checking ------------------------------===//
7862
7863namespace {
7864
7865class CheckScanfHandler : public CheckFormatHandler {
7866public:
7867 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
7868 const Expr *origFormatExpr, Sema::FormatStringType type,
7869 unsigned firstDataArg, unsigned numDataArgs,
7870 const char *beg, Sema::FormatArgumentPassingKind APK,
7871 ArrayRef<const Expr *> Args, unsigned formatIdx,
7872 bool inFunctionCall, Sema::VariadicCallType CallType,
7873 llvm::SmallBitVector &CheckedVarArgs,
7874 UncoveredArgHandler &UncoveredArg)
7875 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7876 numDataArgs, beg, APK, Args, formatIdx,
7877 inFunctionCall, CallType, CheckedVarArgs,
7878 UncoveredArg) {}
7879
7880 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
7881 const char *startSpecifier,
7882 unsigned specifierLen) override;
7883
7884 bool HandleInvalidScanfConversionSpecifier(
7886 const char *startSpecifier,
7887 unsigned specifierLen) override;
7888
7889 void HandleIncompleteScanList(const char *start, const char *end) override;
7890};
7891
7892} // namespace
7893
7894void CheckScanfHandler::HandleIncompleteScanList(const char *start,
7895 const char *end) {
7896 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
7897 getLocationOfByte(end), /*IsStringLocation*/true,
7898 getSpecifierRange(start, end - start));
7899}
7900
7901bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
7903 const char *startSpecifier,
7904 unsigned specifierLen) {
7906 FS.getConversionSpecifier();
7907
7908 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7909 getLocationOfByte(CS.getStart()),
7910 startSpecifier, specifierLen,
7911 CS.getStart(), CS.getLength());
7912}
7913
7914bool CheckScanfHandler::HandleScanfSpecifier(
7916 const char *startSpecifier,
7917 unsigned specifierLen) {
7918 using namespace analyze_scanf;
7919 using namespace analyze_format_string;
7920
7921 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
7922
7923 // Handle case where '%' and '*' don't consume an argument. These shouldn't
7924 // be used to decide if we are using positional arguments consistently.
7925 if (FS.consumesDataArgument()) {
7926 if (atFirstArg) {
7927 atFirstArg = false;
7928 usesPositionalArgs = FS.usesPositionalArg();
7929 }
7930 else if (usesPositionalArgs != FS.usesPositionalArg()) {
7931 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7932 startSpecifier, specifierLen);
7933 return false;
7934 }
7935 }
7936
7937 // Check if the field with is non-zero.
7938 const OptionalAmount &Amt = FS.getFieldWidth();
7939 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
7940 if (Amt.getConstantAmount() == 0) {
7941 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
7942 Amt.getConstantLength());
7943 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
7944 getLocationOfByte(Amt.getStart()),
7945 /*IsStringLocation*/true, R,
7947 }
7948 }
7949
7950 if (!FS.consumesDataArgument()) {
7951 // FIXME: Technically specifying a precision or field width here
7952 // makes no sense. Worth issuing a warning at some point.
7953 return true;
7954 }
7955
7956 // Consume the argument.
7957 unsigned argIndex = FS.getArgIndex();
7958 if (argIndex < NumDataArgs) {
7959 // The check to see if the argIndex is valid will come later.
7960 // We set the bit here because we may exit early from this
7961 // function if we encounter some other error.
7962 CoveredArgs.set(argIndex);
7963 }
7964
7965 // Check the length modifier is valid with the given conversion specifier.
7966 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7967 S.getLangOpts()))
7968 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7969 diag::warn_format_nonsensical_length);
7970 else if (!FS.hasStandardLengthModifier())
7971 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7972 else if (!FS.hasStandardLengthConversionCombination())
7973 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7974 diag::warn_format_non_standard_conversion_spec);
7975
7976 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7977 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7978
7979 // The remaining checks depend on the data arguments.
7980 if (ArgPassingKind == Sema::FAPK_VAList)
7981 return true;
7982
7983 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7984 return false;
7985
7986 // Check that the argument type matches the format specifier.
7987 const Expr *Ex = getDataArg(argIndex);
7988 if (!Ex)
7989 return true;
7990
7991 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
7992
7993 if (!AT.isValid()) {
7994 return true;
7995 }
7996
7998 AT.matchesType(S.Context, Ex->getType());
7999 Match = handleFormatSignedness(Match, S.getDiagnostics(), Ex->getExprLoc());
8002 return true;
8003
8004 ScanfSpecifier fixedFS = FS;
8005 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8006 S.getLangOpts(), S.Context);
8007
8008 unsigned Diag =
8009 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8010 : diag::warn_format_conversion_argument_type_mismatch;
8011
8012 if (Success) {
8013 // Get the fix string from the fixed format specifier.
8014 SmallString<128> buf;
8015 llvm::raw_svector_ostream os(buf);
8016 fixedFS.toString(os);
8017
8018 EmitFormatDiagnostic(
8020 << Ex->getType() << false << Ex->getSourceRange(),
8021 Ex->getBeginLoc(),
8022 /*IsStringLocation*/ false,
8023 getSpecifierRange(startSpecifier, specifierLen),
8025 getSpecifierRange(startSpecifier, specifierLen), os.str()));
8026 } else {
8027 EmitFormatDiagnostic(S.PDiag(Diag)
8029 << Ex->getType() << false << Ex->getSourceRange(),
8030 Ex->getBeginLoc(),
8031 /*IsStringLocation*/ false,
8032 getSpecifierRange(startSpecifier, specifierLen));
8033 }
8034
8035 return true;
8036}
8037
8039 Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr,
8041 unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type,
8042 bool inFunctionCall, Sema::VariadicCallType CallType,
8043 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
8044 bool IgnoreStringsWithoutSpecifiers) {
8045 // CHECK: is the format string a wide literal?
8046 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8047 CheckFormatHandler::EmitFormatDiagnostic(
8048 S, inFunctionCall, Args[format_idx],
8049 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8050 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8051 return;
8052 }
8053
8054 // Str - The format string. NOTE: this is NOT null-terminated!
8055 StringRef StrRef = FExpr->getString();
8056 const char *Str = StrRef.data();
8057 // Account for cases where the string literal is truncated in a declaration.
8058 const ConstantArrayType *T =
8059 S.Context.getAsConstantArrayType(FExpr->getType());
8060 assert(T && "String literal not of constant array type!");
8061 size_t TypeSize = T->getZExtSize();
8062 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8063 const unsigned numDataArgs = Args.size() - firstDataArg;
8064
8065 if (IgnoreStringsWithoutSpecifiers &&
8067 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8068 return;
8069
8070 // Emit a warning if the string literal is truncated and does not contain an
8071 // embedded null character.
8072 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
8073 CheckFormatHandler::EmitFormatDiagnostic(
8074 S, inFunctionCall, Args[format_idx],
8075 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8076 FExpr->getBeginLoc(),
8077 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8078 return;
8079 }
8080
8081 // CHECK: empty format string?
8082 if (StrLen == 0 && numDataArgs > 0) {
8083 CheckFormatHandler::EmitFormatDiagnostic(
8084 S, inFunctionCall, Args[format_idx],
8085 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8086 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8087 return;
8088 }
8089
8094 CheckPrintfHandler H(
8095 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8096 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, APK,
8097 Args, format_idx, inFunctionCall, CallType, CheckedVarArgs,
8098 UncoveredArg);
8099
8101 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
8103 H.DoneProcessing();
8104 } else if (Type == Sema::FST_Scanf) {
8105 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8106 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
8107 CallType, CheckedVarArgs, UncoveredArg);
8108
8110 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8111 H.DoneProcessing();
8112 } // TODO: handle other formats
8113}
8114
8116 // Str - The format string. NOTE: this is NOT null-terminated!
8117 StringRef StrRef = FExpr->getString();
8118 const char *Str = StrRef.data();
8119 // Account for cases where the string literal is truncated in a declaration.
8121 assert(T && "String literal not of constant array type!");
8122 size_t TypeSize = T->getZExtSize();
8123 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8124 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8125 getLangOpts(),
8127}
8128
8129//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8130
8131// Returns the related absolute value function that is larger, of 0 if one
8132// does not exist.
8133static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8134 switch (AbsFunction) {
8135 default:
8136 return 0;
8137
8138 case Builtin::BI__builtin_abs:
8139 return Builtin::BI__builtin_labs;
8140 case Builtin::BI__builtin_labs:
8141 return Builtin::BI__builtin_llabs;
8142 case Builtin::BI__builtin_llabs:
8143 return 0;
8144
8145 case Builtin::BI__builtin_fabsf:
8146 return Builtin::BI__builtin_fabs;
8147 case Builtin::BI__builtin_fabs:
8148 return Builtin::BI__builtin_fabsl;
8149 case Builtin::BI__builtin_fabsl:
8150 return 0;
8151
8152 case Builtin::BI__builtin_cabsf:
8153 return Builtin::BI__builtin_cabs;
8154 case Builtin::BI__builtin_cabs:
8155 return Builtin::BI__builtin_cabsl;
8156 case Builtin::BI__builtin_cabsl:
8157 return 0;
8158
8159 case Builtin::BIabs:
8160 return Builtin::BIlabs;
8161 case Builtin::BIlabs:
8162 return Builtin::BIllabs;
8163 case Builtin::BIllabs:
8164 return 0;
8165
8166 case Builtin::BIfabsf:
8167 return Builtin::BIfabs;
8168 case Builtin::BIfabs:
8169 return Builtin::BIfabsl;
8170 case Builtin::BIfabsl:
8171 return 0;
8172
8173 case Builtin::BIcabsf:
8174 return Builtin::BIcabs;
8175 case Builtin::BIcabs:
8176 return Builtin::BIcabsl;
8177 case Builtin::BIcabsl:
8178 return 0;
8179 }
8180}
8181
8182// Returns the argument type of the absolute value function.
8184 unsigned AbsType) {
8185 if (AbsType == 0)
8186 return QualType();
8187
8189 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8190 if (Error != ASTContext::GE_None)
8191 return QualType();
8192
8194 if (!FT)
8195 return QualType();
8196
8197 if (FT->getNumParams() != 1)
8198 return QualType();
8199
8200 return FT->getParamType(0);
8201}
8202
8203// Returns the best absolute value function, or zero, based on type and
8204// current absolute value function.
8205static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8206 unsigned AbsFunctionKind) {
8207 unsigned BestKind = 0;
8208 uint64_t ArgSize = Context.getTypeSize(ArgType);
8209 for (unsigned Kind = AbsFunctionKind; Kind != 0;
8210 Kind = getLargerAbsoluteValueFunction(Kind)) {
8211 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8212 if (Context.getTypeSize(ParamType) >= ArgSize) {
8213 if (BestKind == 0)
8214 BestKind = Kind;
8215 else if (Context.hasSameType(ParamType, ArgType)) {
8216 BestKind = Kind;
8217 break;
8218 }
8219 }
8220 }
8221 return BestKind;
8222}
8223
8229
8232 return AVK_Integer;
8233 if (T->isRealFloatingType())
8234 return AVK_Floating;
8235 if (T->isAnyComplexType())
8236 return AVK_Complex;
8237
8238 llvm_unreachable("Type not integer, floating, or complex");
8239}
8240
8241// Changes the absolute value function to a different type. Preserves whether
8242// the function is a builtin.
8243static unsigned changeAbsFunction(unsigned AbsKind,
8244 AbsoluteValueKind ValueKind) {
8245 switch (ValueKind) {
8246 case AVK_Integer:
8247 switch (AbsKind) {
8248 default:
8249 return 0;
8250 case Builtin::BI__builtin_fabsf:
8251 case Builtin::BI__builtin_fabs:
8252 case Builtin::BI__builtin_fabsl:
8253 case Builtin::BI__builtin_cabsf:
8254 case Builtin::BI__builtin_cabs:
8255 case Builtin::BI__builtin_cabsl:
8256 return Builtin::BI__builtin_abs;
8257 case Builtin::BIfabsf:
8258 case Builtin::BIfabs:
8259 case Builtin::BIfabsl:
8260 case Builtin::BIcabsf:
8261 case Builtin::BIcabs:
8262 case Builtin::BIcabsl:
8263 return Builtin::BIabs;
8264 }
8265 case AVK_Floating:
8266 switch (AbsKind) {
8267 default:
8268 return 0;
8269 case Builtin::BI__builtin_abs:
8270 case Builtin::BI__builtin_labs:
8271 case Builtin::BI__builtin_llabs:
8272 case Builtin::BI__builtin_cabsf:
8273 case Builtin::BI__builtin_cabs:
8274 case Builtin::BI__builtin_cabsl:
8275 return Builtin::BI__builtin_fabsf;
8276 case Builtin::BIabs:
8277 case Builtin::BIlabs:
8278 case Builtin::BIllabs:
8279 case Builtin::BIcabsf:
8280 case Builtin::BIcabs:
8281 case Builtin::BIcabsl:
8282 return Builtin::BIfabsf;
8283 }
8284 case AVK_Complex:
8285 switch (AbsKind) {
8286 default:
8287 return 0;
8288 case Builtin::BI__builtin_abs:
8289 case Builtin::BI__builtin_labs:
8290 case Builtin::BI__builtin_llabs:
8291 case Builtin::BI__builtin_fabsf:
8292 case Builtin::BI__builtin_fabs:
8293 case Builtin::BI__builtin_fabsl:
8294 return Builtin::BI__builtin_cabsf;
8295 case Builtin::BIabs:
8296 case Builtin::BIlabs:
8297 case Builtin::BIllabs:
8298 case Builtin::BIfabsf:
8299 case Builtin::BIfabs:
8300 case Builtin::BIfabsl:
8301 return Builtin::BIcabsf;
8302 }
8303 }
8304 llvm_unreachable("Unable to convert function");
8305}
8306
8307static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8308 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8309 if (!FnInfo)
8310 return 0;
8311
8312 switch (FDecl->getBuiltinID()) {
8313 default:
8314 return 0;
8315 case Builtin::BI__builtin_abs:
8316 case Builtin::BI__builtin_fabs:
8317 case Builtin::BI__builtin_fabsf:
8318 case Builtin::BI__builtin_fabsl:
8319 case Builtin::BI__builtin_labs:
8320 case Builtin::BI__builtin_llabs:
8321 case Builtin::BI__builtin_cabs:
8322 case Builtin::BI__builtin_cabsf:
8323 case Builtin::BI__builtin_cabsl:
8324 case Builtin::BIabs:
8325 case Builtin::BIlabs:
8326 case Builtin::BIllabs:
8327 case Builtin::BIfabs:
8328 case Builtin::BIfabsf:
8329 case Builtin::BIfabsl:
8330 case Builtin::BIcabs:
8331 case Builtin::BIcabsf:
8332 case Builtin::BIcabsl:
8333 return FDecl->getBuiltinID();
8334 }
8335 llvm_unreachable("Unknown Builtin type");
8336}
8337
8338// If the replacement is valid, emit a note with replacement function.
8339// Additionally, suggest including the proper header if not already included.
8341 unsigned AbsKind, QualType ArgType) {
8342 bool EmitHeaderHint = true;
8343 const char *HeaderName = nullptr;
8344 StringRef FunctionName;
8345 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8346 FunctionName = "std::abs";
8347 if (ArgType->isIntegralOrEnumerationType()) {
8348 HeaderName = "cstdlib";
8349 } else if (ArgType->isRealFloatingType()) {
8350 HeaderName = "cmath";
8351 } else {
8352 llvm_unreachable("Invalid Type");
8353 }
8354
8355 // Lookup all std::abs
8356 if (NamespaceDecl *Std = S.getStdNamespace()) {
8360
8361 for (const auto *I : R) {
8362 const FunctionDecl *FDecl = nullptr;
8363 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8364 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8365 } else {
8366 FDecl = dyn_cast<FunctionDecl>(I);
8367 }
8368 if (!FDecl)
8369 continue;
8370
8371 // Found std::abs(), check that they are the right ones.
8372 if (FDecl->getNumParams() != 1)
8373 continue;
8374
8375 // Check that the parameter type can handle the argument.
8376 QualType ParamType = FDecl->getParamDecl(0)->getType();
8377 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8378 S.Context.getTypeSize(ArgType) <=
8379 S.Context.getTypeSize(ParamType)) {
8380 // Found a function, don't need the header hint.
8381 EmitHeaderHint = false;
8382 break;
8383 }
8384 }
8385 }
8386 } else {
8387 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8388 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8389
8390 if (HeaderName) {
8391 DeclarationName DN(&S.Context.Idents.get(FunctionName));
8394 S.LookupName(R, S.getCurScope());
8395
8396 if (R.isSingleResult()) {
8397 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8398 if (FD && FD->getBuiltinID() == AbsKind) {
8399 EmitHeaderHint = false;
8400 } else {
8401 return;
8402 }
8403 } else if (!R.empty()) {
8404 return;
8405 }
8406 }
8407 }
8408
8409 S.Diag(Loc, diag::note_replace_abs_function)
8410 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8411
8412 if (!HeaderName)
8413 return;
8414
8415 if (!EmitHeaderHint)
8416 return;
8417
8418 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8419 << FunctionName;
8420}
8421
8422template <std::size_t StrLen>
8423static bool IsStdFunction(const FunctionDecl *FDecl,
8424 const char (&Str)[StrLen]) {
8425 if (!FDecl)
8426 return false;
8427 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8428 return false;
8429 if (!FDecl->isInStdNamespace())
8430 return false;
8431
8432 return true;
8433}
8434
8435enum class MathCheck { NaN, Inf };
8436static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
8437 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
8438 return std::any_of(names.begin(), names.end(), [&](llvm::StringRef name) {
8439 return calleeName == name;
8440 });
8441 };
8442
8443 switch (Check) {
8444 case MathCheck::NaN:
8445 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
8446 "__builtin_nanf16", "__builtin_nanf128"});
8447 case MathCheck::Inf:
8448 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
8449 "__builtin_inff16", "__builtin_inff128"});
8450 }
8451 llvm_unreachable("unknown MathCheck");
8452}
8453
8454void Sema::CheckInfNaNFunction(const CallExpr *Call,
8455 const FunctionDecl *FDecl) {
8456 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
8457 bool HasIdentifier = FDecl->getIdentifier() != nullptr;
8458 bool IsNaNOrIsUnordered =
8459 IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered");
8460 bool IsSpecialNaN =
8461 HasIdentifier && IsInfOrNanFunction(FDecl->getName(), MathCheck::NaN);
8462 if ((IsNaNOrIsUnordered || IsSpecialNaN) && FPO.getNoHonorNaNs()) {
8463 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
8464 << 1 << 0 << Call->getSourceRange();
8465 } else {
8466 bool IsInfOrIsFinite =
8467 IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite");
8468 bool IsInfinityOrIsSpecialInf =
8469 HasIdentifier && ((FDecl->getName() == "infinity") ||
8470 IsInfOrNanFunction(FDecl->getName(), MathCheck::Inf));
8471 if ((IsInfOrIsFinite || IsInfinityOrIsSpecialInf) && FPO.getNoHonorInfs())
8472 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
8473 << 0 << 0 << Call->getSourceRange();
8474 }
8475}
8476
8477void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
8478 const FunctionDecl *FDecl) {
8479 if (Call->getNumArgs() != 1)
8480 return;
8481
8482 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
8483 bool IsStdAbs = IsStdFunction(FDecl, "abs");
8484 if (AbsKind == 0 && !IsStdAbs)
8485 return;
8486
8487 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8488 QualType ParamType = Call->getArg(0)->getType();
8489
8490 // Unsigned types cannot be negative. Suggest removing the absolute value
8491 // function call.
8492 if (ArgType->isUnsignedIntegerType()) {
8493 StringRef FunctionName =
8494 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
8495 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8496 Diag(Call->getExprLoc(), diag::note_remove_abs)
8497 << FunctionName
8498 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8499 return;
8500 }
8501
8502 // Taking the absolute value of a pointer is very suspicious, they probably
8503 // wanted to index into an array, dereference a pointer, call a function, etc.
8504 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8505 unsigned DiagType = 0;
8506 if (ArgType->isFunctionType())
8507 DiagType = 1;
8508 else if (ArgType->isArrayType())
8509 DiagType = 2;
8510
8511 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8512 return;
8513 }
8514
8515 // std::abs has overloads which prevent most of the absolute value problems
8516 // from occurring.
8517 if (IsStdAbs)
8518 return;
8519
8520 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
8521 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
8522
8523 // The argument and parameter are the same kind. Check if they are the right
8524 // size.
8525 if (ArgValueKind == ParamValueKind) {
8526 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
8527 return;
8528
8529 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
8530 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8531 << FDecl << ArgType << ParamType;
8532
8533 if (NewAbsKind == 0)
8534 return;
8535
8536 emitReplacement(*this, Call->getExprLoc(),
8537 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8538 return;
8539 }
8540
8541 // ArgValueKind != ParamValueKind
8542 // The wrong type of absolute value function was used. Attempt to find the
8543 // proper one.
8544 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
8545 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
8546 if (NewAbsKind == 0)
8547 return;
8548
8549 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
8550 << FDecl << ParamValueKind << ArgValueKind;
8551
8552 emitReplacement(*this, Call->getExprLoc(),
8553 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8554}
8555
8556//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
8557void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
8558 const FunctionDecl *FDecl) {
8559 if (!Call || !FDecl) return;
8560
8561 // Ignore template specializations and macros.
8562 if (inTemplateInstantiation()) return;
8563 if (Call->getExprLoc().isMacroID()) return;
8564
8565 // Only care about the one template argument, two function parameter std::max
8566 if (Call->getNumArgs() != 2) return;
8567 if (!IsStdFunction(FDecl, "max")) return;
8568 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
8569 if (!ArgList) return;
8570 if (ArgList->size() != 1) return;
8571
8572 // Check that template type argument is unsigned integer.
8573 const auto& TA = ArgList->get(0);
8574 if (TA.getKind() != TemplateArgument::Type) return;
8575 QualType ArgType = TA.getAsType();
8576 if (!ArgType->isUnsignedIntegerType()) return;
8577
8578 // See if either argument is a literal zero.
8579 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
8580 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
8581 if (!MTE) return false;
8582 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
8583 if (!Num) return false;
8584 if (Num->getValue() != 0) return false;
8585 return true;
8586 };
8587
8588 const Expr *FirstArg = Call->getArg(0);
8589 const Expr *SecondArg = Call->getArg(1);
8590 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
8591 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
8592
8593 // Only warn when exactly one argument is zero.
8594 if (IsFirstArgZero == IsSecondArgZero) return;
8595
8596 SourceRange FirstRange = FirstArg->getSourceRange();
8597 SourceRange SecondRange = SecondArg->getSourceRange();
8598
8599 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
8600
8601 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
8602 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
8603
8604 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
8605 SourceRange RemovalRange;
8606 if (IsFirstArgZero) {
8607 RemovalRange = SourceRange(FirstRange.getBegin(),
8608 SecondRange.getBegin().getLocWithOffset(-1));
8609 } else {
8610 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
8611 SecondRange.getEnd());
8612 }
8613
8614 Diag(Call->getExprLoc(), diag::note_remove_max_call)
8615 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
8616 << FixItHint::CreateRemoval(RemovalRange);
8617}
8618
8619//===--- CHECK: Standard memory functions ---------------------------------===//
8620
8621/// Takes the expression passed to the size_t parameter of functions
8622/// such as memcmp, strncat, etc and warns if it's a comparison.
8623///
8624/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
8626 IdentifierInfo *FnName,
8627 SourceLocation FnLoc,
8628 SourceLocation RParenLoc) {
8629 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
8630 if (!Size)
8631 return false;
8632
8633 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
8634 if (!Size->isComparisonOp() && !Size->isLogicalOp())
8635 return false;
8636
8637 SourceRange SizeRange = Size->getSourceRange();
8638 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
8639 << SizeRange << FnName;
8640 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
8641 << FnName
8643 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
8644 << FixItHint::CreateRemoval(RParenLoc);
8645 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
8646 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
8648 ")");
8649
8650 return true;
8651}
8652
8653/// Determine whether the given type is or contains a dynamic class type
8654/// (e.g., whether it has a vtable).
8656 bool &IsContained) {
8657 // Look through array types while ignoring qualifiers.
8658 const Type *Ty = T->getBaseElementTypeUnsafe();
8659 IsContained = false;
8660
8661 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
8662 RD = RD ? RD->getDefinition() : nullptr;
8663 if (!RD || RD->isInvalidDecl())
8664 return nullptr;
8665
8666 if (RD->isDynamicClass())
8667 return RD;
8668
8669 // Check all the fields. If any bases were dynamic, the class is dynamic.
8670 // It's impossible for a class to transitively contain itself by value, so
8671 // infinite recursion is impossible.
8672 for (auto *FD : RD->fields()) {
8673 bool SubContained;
8674 if (const CXXRecordDecl *ContainedRD =
8675 getContainedDynamicClass(FD->getType(), SubContained)) {
8676 IsContained = true;
8677 return ContainedRD;
8678 }
8679 }
8680
8681 return nullptr;
8682}
8683
8685 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
8686 if (Unary->getKind() == UETT_SizeOf)
8687 return Unary;
8688 return nullptr;
8689}
8690
8691/// If E is a sizeof expression, returns its argument expression,
8692/// otherwise returns NULL.
8693static const Expr *getSizeOfExprArg(const Expr *E) {
8695 if (!SizeOf->isArgumentType())
8696 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
8697 return nullptr;
8698}
8699
8700/// If E is a sizeof expression, returns its argument type.
8703 return SizeOf->getTypeOfArgument();
8704 return QualType();
8705}
8706
8707namespace {
8708
8709struct SearchNonTrivialToInitializeField
8710 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
8711 using Super =
8713
8714 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
8715
8716 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
8717 SourceLocation SL) {
8718 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8719 asDerived().visitArray(PDIK, AT, SL);
8720 return;
8721 }
8722
8723 Super::visitWithKind(PDIK, FT, SL);
8724 }
8725
8726 void visitARCStrong(QualType FT, SourceLocation SL) {
8727 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8728 }
8729 void visitARCWeak(QualType FT, SourceLocation SL) {
8730 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8731 }
8732 void visitStruct(QualType FT, SourceLocation SL) {
8733 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8734 visit(FD->getType(), FD->getLocation());
8735 }
8736 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
8737 const ArrayType *AT, SourceLocation SL) {
8738 visit(getContext().getBaseElementType(AT), SL);
8739 }
8740 void visitTrivial(QualType FT, SourceLocation SL) {}
8741
8742 static void diag(QualType RT, const Expr *E, Sema &S) {
8743 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
8744 }
8745
8746 ASTContext &getContext() { return S.getASTContext(); }
8747
8748 const Expr *E;
8749 Sema &S;
8750};
8751
8752struct SearchNonTrivialToCopyField
8753 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
8755
8756 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
8757
8758 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
8759 SourceLocation SL) {
8760 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8761 asDerived().visitArray(PCK, AT, SL);
8762 return;
8763 }
8764
8765 Super::visitWithKind(PCK, FT, SL);
8766 }
8767
8768 void visitARCStrong(QualType FT, SourceLocation SL) {
8769 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8770 }
8771 void visitARCWeak(QualType FT, SourceLocation SL) {
8772 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8773 }
8774 void visitStruct(QualType FT, SourceLocation SL) {
8775 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8776 visit(FD->getType(), FD->getLocation());
8777 }
8778 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
8779 SourceLocation SL) {
8780 visit(getContext().getBaseElementType(AT), SL);
8781 }
8782 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
8783 SourceLocation SL) {}
8784 void visitTrivial(QualType FT, SourceLocation SL) {}
8785 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
8786
8787 static void diag(QualType RT, const Expr *E, Sema &S) {
8788 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
8789 }
8790
8791 ASTContext &getContext() { return S.getASTContext(); }
8792
8793 const Expr *E;
8794 Sema &S;
8795};
8796
8797}
8798
8799/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
8800static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
8801 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
8802
8803 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
8804 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
8805 return false;
8806
8807 return doesExprLikelyComputeSize(BO->getLHS()) ||
8808 doesExprLikelyComputeSize(BO->getRHS());
8809 }
8810
8811 return getAsSizeOfExpr(SizeofExpr) != nullptr;
8812}
8813
8814/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
8815///
8816/// \code
8817/// #define MACRO 0
8818/// foo(MACRO);
8819/// foo(0);
8820/// \endcode
8821///
8822/// This should return true for the first call to foo, but not for the second
8823/// (regardless of whether foo is a macro or function).
8825 SourceLocation CallLoc,
8826 SourceLocation ArgLoc) {
8827 if (!CallLoc.isMacroID())
8828 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
8829
8830 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
8831 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
8832}
8833
8834/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
8835/// last two arguments transposed.
8836static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
8837 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
8838 return;
8839
8840 const Expr *SizeArg =
8841 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
8842
8843 auto isLiteralZero = [](const Expr *E) {
8844 return (isa<IntegerLiteral>(E) &&
8845 cast<IntegerLiteral>(E)->getValue() == 0) ||
8846 (isa<CharacterLiteral>(E) &&
8847 cast<CharacterLiteral>(E)->getValue() == 0);
8848 };
8849
8850 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
8851 SourceLocation CallLoc = Call->getRParenLoc();
8853 if (isLiteralZero(SizeArg) &&
8854 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
8855
8856 SourceLocation DiagLoc = SizeArg->getExprLoc();
8857
8858 // Some platforms #define bzero to __builtin_memset. See if this is the
8859 // case, and if so, emit a better diagnostic.
8860 if (BId == Builtin::BIbzero ||
8862 CallLoc, SM, S.getLangOpts()) == "bzero")) {
8863 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
8864 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
8865 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
8866 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
8867 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
8868 }
8869 return;
8870 }
8871
8872 // If the second argument to a memset is a sizeof expression and the third
8873 // isn't, this is also likely an error. This should catch
8874 // 'memset(buf, sizeof(buf), 0xff)'.
8875 if (BId == Builtin::BImemset &&
8876 doesExprLikelyComputeSize(Call->getArg(1)) &&
8877 !doesExprLikelyComputeSize(Call->getArg(2))) {
8878 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
8879 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
8880 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
8881 return;
8882 }
8883}
8884
8885void Sema::CheckMemaccessArguments(const CallExpr *Call,
8886 unsigned BId,
8887 IdentifierInfo *FnName) {
8888 assert(BId != 0);
8889
8890 // It is possible to have a non-standard definition of memset. Validate
8891 // we have enough arguments, and if not, abort further checking.
8892 unsigned ExpectedNumArgs =
8893 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
8894 if (Call->getNumArgs() < ExpectedNumArgs)
8895 return;
8896
8897 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
8898 BId == Builtin::BIstrndup ? 1 : 2);
8899 unsigned LenArg =
8900 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
8901 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
8902
8903 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
8904 Call->getBeginLoc(), Call->getRParenLoc()))
8905 return;
8906
8907 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
8908 CheckMemaccessSize(*this, BId, Call);
8909
8910 // We have special checking when the length is a sizeof expression.
8911 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
8912 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
8913 llvm::FoldingSetNodeID SizeOfArgID;
8914
8915 // Although widely used, 'bzero' is not a standard function. Be more strict
8916 // with the argument types before allowing diagnostics and only allow the
8917 // form bzero(ptr, sizeof(...)).
8918 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8919 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
8920 return;
8921
8922 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
8923 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
8924 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
8925
8926 QualType DestTy = Dest->getType();
8927 QualType PointeeTy;
8928 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
8929 PointeeTy = DestPtrTy->getPointeeType();
8930
8931 // Never warn about void type pointers. This can be used to suppress
8932 // false positives.
8933 if (PointeeTy->isVoidType())
8934 continue;
8935
8936 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
8937 // actually comparing the expressions for equality. Because computing the
8938 // expression IDs can be expensive, we only do this if the diagnostic is
8939 // enabled.
8940 if (SizeOfArg &&
8941 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
8942 SizeOfArg->getExprLoc())) {
8943 // We only compute IDs for expressions if the warning is enabled, and
8944 // cache the sizeof arg's ID.
8945 if (SizeOfArgID == llvm::FoldingSetNodeID())
8946 SizeOfArg->Profile(SizeOfArgID, Context, true);
8947 llvm::FoldingSetNodeID DestID;
8948 Dest->Profile(DestID, Context, true);
8949 if (DestID == SizeOfArgID) {
8950 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
8951 // over sizeof(src) as well.
8952 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
8953 StringRef ReadableName = FnName->getName();
8954
8955 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
8956 if (UnaryOp->getOpcode() == UO_AddrOf)
8957 ActionIdx = 1; // If its an address-of operator, just remove it.
8958 if (!PointeeTy->isIncompleteType() &&
8959 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
8960 ActionIdx = 2; // If the pointee's size is sizeof(char),
8961 // suggest an explicit length.
8962
8963 // If the function is defined as a builtin macro, do not show macro
8964 // expansion.
8965 SourceLocation SL = SizeOfArg->getExprLoc();
8966 SourceRange DSR = Dest->getSourceRange();
8967 SourceRange SSR = SizeOfArg->getSourceRange();
8969
8970 if (SM.isMacroArgExpansion(SL)) {
8971 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
8972 SL = SM.getSpellingLoc(SL);
8973 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
8974 SM.getSpellingLoc(DSR.getEnd()));
8975 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
8976 SM.getSpellingLoc(SSR.getEnd()));
8977 }
8978
8979 DiagRuntimeBehavior(SL, SizeOfArg,
8980 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
8981 << ReadableName
8982 << PointeeTy
8983 << DestTy
8984 << DSR
8985 << SSR);
8986 DiagRuntimeBehavior(SL, SizeOfArg,
8987 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
8988 << ActionIdx
8989 << SSR);
8990
8991 break;
8992 }
8993 }
8994
8995 // Also check for cases where the sizeof argument is the exact same
8996 // type as the memory argument, and where it points to a user-defined
8997 // record type.
8998 if (SizeOfArgTy != QualType()) {
8999 if (PointeeTy->isRecordType() &&
9000 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9001 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9002 PDiag(diag::warn_sizeof_pointer_type_memaccess)
9003 << FnName << SizeOfArgTy << ArgIdx
9004 << PointeeTy << Dest->getSourceRange()
9005 << LenExpr->getSourceRange());
9006 break;
9007 }
9008 }
9009 } else if (DestTy->isArrayType()) {
9010 PointeeTy = DestTy;
9011 }
9012
9013 if (PointeeTy == QualType())
9014 continue;
9015
9016 // Always complain about dynamic classes.
9017 bool IsContained;
9018 if (const CXXRecordDecl *ContainedRD =
9019 getContainedDynamicClass(PointeeTy, IsContained)) {
9020
9021 unsigned OperationType = 0;
9022 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9023 // "overwritten" if we're warning about the destination for any call
9024 // but memcmp; otherwise a verb appropriate to the call.
9025 if (ArgIdx != 0 || IsCmp) {
9026 if (BId == Builtin::BImemcpy)
9027 OperationType = 1;
9028 else if(BId == Builtin::BImemmove)
9029 OperationType = 2;
9030 else if (IsCmp)
9031 OperationType = 3;
9032 }
9033
9034 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9035 PDiag(diag::warn_dyn_class_memaccess)
9036 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9037 << IsContained << ContainedRD << OperationType
9038 << Call->getCallee()->getSourceRange());
9039 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9040 BId != Builtin::BImemset)
9042 Dest->getExprLoc(), Dest,
9043 PDiag(diag::warn_arc_object_memaccess)
9044 << ArgIdx << FnName << PointeeTy
9045 << Call->getCallee()->getSourceRange());
9046 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9047
9048 // FIXME: Do not consider incomplete types even though they may be
9049 // completed later. GCC does not diagnose such code, but we may want to
9050 // consider diagnosing it in the future, perhaps under a different, but
9051 // related, diagnostic group.
9052 bool MayBeTriviallyCopyableCXXRecord =
9053 RT->isIncompleteType() ||
9054 RT->desugar().isTriviallyCopyableType(Context);
9055
9056 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9057 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9058 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9059 PDiag(diag::warn_cstruct_memaccess)
9060 << ArgIdx << FnName << PointeeTy << 0);
9061 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9062 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9063 !MayBeTriviallyCopyableCXXRecord && ArgIdx == 0) {
9064 // FIXME: Limiting this warning to dest argument until we decide
9065 // whether it's valid for source argument too.
9066 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9067 PDiag(diag::warn_cxxstruct_memaccess)
9068 << FnName << PointeeTy);
9069 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9070 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9071 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9072 PDiag(diag::warn_cstruct_memaccess)
9073 << ArgIdx << FnName << PointeeTy << 1);
9074 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9075 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9076 !MayBeTriviallyCopyableCXXRecord && ArgIdx == 0) {
9077 // FIXME: Limiting this warning to dest argument until we decide
9078 // whether it's valid for source argument too.
9079 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9080 PDiag(diag::warn_cxxstruct_memaccess)
9081 << FnName << PointeeTy);
9082 } else {
9083 continue;
9084 }
9085 } else
9086 continue;
9087
9089 Dest->getExprLoc(), Dest,
9090 PDiag(diag::note_bad_memaccess_silence)
9091 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9092 break;
9093 }
9094}
9095
9096// A little helper routine: ignore addition and subtraction of integer literals.
9097// This intentionally does not ignore all integer constant expressions because
9098// we don't want to remove sizeof().
9099static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9100 Ex = Ex->IgnoreParenCasts();
9101
9102 while (true) {
9103 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9104 if (!BO || !BO->isAdditiveOp())
9105 break;
9106
9107 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9108 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9109
9110 if (isa<IntegerLiteral>(RHS))
9111 Ex = LHS;
9112 else if (isa<IntegerLiteral>(LHS))
9113 Ex = RHS;
9114 else
9115 break;
9116 }
9117
9118 return Ex;
9119}
9120
9122 ASTContext &Context) {
9123 // Only handle constant-sized or VLAs, but not flexible members.
9124 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9125 // Only issue the FIXIT for arrays of size > 1.
9126 if (CAT->getZExtSize() <= 1)
9127 return false;
9128 } else if (!Ty->isVariableArrayType()) {
9129 return false;
9130 }
9131 return true;
9132}
9133
9134void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9135 IdentifierInfo *FnName) {
9136
9137 // Don't crash if the user has the wrong number of arguments
9138 unsigned NumArgs = Call->getNumArgs();
9139 if ((NumArgs != 3) && (NumArgs != 4))
9140 return;
9141
9142 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9143 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9144 const Expr *CompareWithSrc = nullptr;
9145
9146 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9147 Call->getBeginLoc(), Call->getRParenLoc()))
9148 return;
9149
9150 // Look for 'strlcpy(dst, x, sizeof(x))'
9151 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9152 CompareWithSrc = Ex;
9153 else {
9154 // Look for 'strlcpy(dst, x, strlen(x))'
9155 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9156 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9157 SizeCall->getNumArgs() == 1)
9158 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9159 }
9160 }
9161
9162 if (!CompareWithSrc)
9163 return;
9164
9165 // Determine if the argument to sizeof/strlen is equal to the source
9166 // argument. In principle there's all kinds of things you could do
9167 // here, for instance creating an == expression and evaluating it with
9168 // EvaluateAsBooleanCondition, but this uses a more direct technique:
9169 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9170 if (!SrcArgDRE)
9171 return;
9172
9173 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9174 if (!CompareWithSrcDRE ||
9175 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9176 return;
9177
9178 const Expr *OriginalSizeArg = Call->getArg(2);
9179 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9180 << OriginalSizeArg->getSourceRange() << FnName;
9181
9182 // Output a FIXIT hint if the destination is an array (rather than a
9183 // pointer to an array). This could be enhanced to handle some
9184 // pointers if we know the actual size, like if DstArg is 'array+2'
9185 // we could say 'sizeof(array)-2'.
9186 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9188 return;
9189
9190 SmallString<128> sizeString;
9191 llvm::raw_svector_ostream OS(sizeString);
9192 OS << "sizeof(";
9193 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9194 OS << ")";
9195
9196 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9197 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9198 OS.str());
9199}
9200
9201/// Check if two expressions refer to the same declaration.
9202static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9203 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9204 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9205 return D1->getDecl() == D2->getDecl();
9206 return false;
9207}
9208
9209static const Expr *getStrlenExprArg(const Expr *E) {
9210 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9211 const FunctionDecl *FD = CE->getDirectCallee();
9212 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9213 return nullptr;
9214 return CE->getArg(0)->IgnoreParenCasts();
9215 }
9216 return nullptr;
9217}
9218
9219void Sema::CheckStrncatArguments(const CallExpr *CE,
9220 IdentifierInfo *FnName) {
9221 // Don't crash if the user has the wrong number of arguments.
9222 if (CE->getNumArgs() < 3)
9223 return;
9224 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9225 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9226 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9227
9228 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9229 CE->getRParenLoc()))
9230 return;
9231
9232 // Identify common expressions, which are wrongly used as the size argument
9233 // to strncat and may lead to buffer overflows.
9234 unsigned PatternType = 0;
9235 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9236 // - sizeof(dst)
9237 if (referToTheSameDecl(SizeOfArg, DstArg))
9238 PatternType = 1;
9239 // - sizeof(src)
9240 else if (referToTheSameDecl(SizeOfArg, SrcArg))
9241 PatternType = 2;
9242 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9243 if (BE->getOpcode() == BO_Sub) {
9244 const Expr *L = BE->getLHS()->IgnoreParenCasts();
9245 const Expr *R = BE->getRHS()->IgnoreParenCasts();
9246 // - sizeof(dst) - strlen(dst)
9247 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9249 PatternType = 1;
9250 // - sizeof(src) - (anything)
9251 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9252 PatternType = 2;
9253 }
9254 }
9255
9256 if (PatternType == 0)
9257 return;
9258
9259 // Generate the diagnostic.
9260 SourceLocation SL = LenArg->getBeginLoc();
9261 SourceRange SR = LenArg->getSourceRange();
9263
9264 // If the function is defined as a builtin macro, do not show macro expansion.
9265 if (SM.isMacroArgExpansion(SL)) {
9266 SL = SM.getSpellingLoc(SL);
9267 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9268 SM.getSpellingLoc(SR.getEnd()));
9269 }
9270
9271 // Check if the destination is an array (rather than a pointer to an array).
9272 QualType DstTy = DstArg->getType();
9273 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9274 Context);
9275 if (!isKnownSizeArray) {
9276 if (PatternType == 1)
9277 Diag(SL, diag::warn_strncat_wrong_size) << SR;
9278 else
9279 Diag(SL, diag::warn_strncat_src_size) << SR;
9280 return;
9281 }
9282
9283 if (PatternType == 1)
9284 Diag(SL, diag::warn_strncat_large_size) << SR;
9285 else
9286 Diag(SL, diag::warn_strncat_src_size) << SR;
9287
9288 SmallString<128> sizeString;
9289 llvm::raw_svector_ostream OS(sizeString);
9290 OS << "sizeof(";
9291 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9292 OS << ") - ";
9293 OS << "strlen(";
9294 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9295 OS << ") - 1";
9296
9297 Diag(SL, diag::note_strncat_wrong_size)
9298 << FixItHint::CreateReplacement(SR, OS.str());
9299}
9300
9301namespace {
9302void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
9303 const UnaryOperator *UnaryExpr, const Decl *D) {
9304 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
9305 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
9306 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
9307 return;
9308 }
9309}
9310
9311void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
9312 const UnaryOperator *UnaryExpr) {
9313 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
9314 const Decl *D = Lvalue->getDecl();
9315 if (isa<DeclaratorDecl>(D))
9316 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
9317 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
9318 }
9319
9320 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
9321 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
9322 Lvalue->getMemberDecl());
9323}
9324
9325void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
9326 const UnaryOperator *UnaryExpr) {
9327 const auto *Lambda = dyn_cast<LambdaExpr>(
9329 if (!Lambda)
9330 return;
9331
9332 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
9333 << CalleeName << 2 /*object: lambda expression*/;
9334}
9335
9336void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
9337 const DeclRefExpr *Lvalue) {
9338 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
9339 if (Var == nullptr)
9340 return;
9341
9342 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
9343 << CalleeName << 0 /*object: */ << Var;
9344}
9345
9346void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
9347 const CastExpr *Cast) {
9348 SmallString<128> SizeString;
9349 llvm::raw_svector_ostream OS(SizeString);
9350
9351 clang::CastKind Kind = Cast->getCastKind();
9352 if (Kind == clang::CK_BitCast &&
9353 !Cast->getSubExpr()->getType()->isFunctionPointerType())
9354 return;
9355 if (Kind == clang::CK_IntegralToPointer &&
9356 !isa<IntegerLiteral>(
9357 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
9358 return;
9359
9360 switch (Cast->getCastKind()) {
9361 case clang::CK_BitCast:
9362 case clang::CK_IntegralToPointer:
9363 case clang::CK_FunctionToPointerDecay:
9364 OS << '\'';
9365 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
9366 OS << '\'';
9367 break;
9368 default:
9369 return;
9370 }
9371
9372 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
9373 << CalleeName << 0 /*object: */ << OS.str();
9374}
9375} // namespace
9376
9377void Sema::CheckFreeArguments(const CallExpr *E) {
9378 const std::string CalleeName =
9379 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
9380
9381 { // Prefer something that doesn't involve a cast to make things simpler.
9382 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
9383 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
9384 switch (UnaryExpr->getOpcode()) {
9385 case UnaryOperator::Opcode::UO_AddrOf:
9386 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
9387 case UnaryOperator::Opcode::UO_Plus:
9388 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
9389 default:
9390 break;
9391 }
9392
9393 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
9394 if (Lvalue->getType()->isArrayType())
9395 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
9396
9397 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
9398 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
9399 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
9400 return;
9401 }
9402
9403 if (isa<BlockExpr>(Arg)) {
9404 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
9405 << CalleeName << 1 /*object: block*/;
9406 return;
9407 }
9408 }
9409 // Maybe the cast was important, check after the other cases.
9410 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
9411 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
9412}
9413
9414void
9415Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9416 SourceLocation ReturnLoc,
9417 bool isObjCMethod,
9418 const AttrVec *Attrs,
9419 const FunctionDecl *FD) {
9420 // Check if the return value is null but should not be.
9421 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9422 (!isObjCMethod && isNonNullType(lhsType))) &&
9423 CheckNonNullExpr(*this, RetValExp))
9424 Diag(ReturnLoc, diag::warn_null_ret)
9425 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9426
9427 // C++11 [basic.stc.dynamic.allocation]p4:
9428 // If an allocation function declared with a non-throwing
9429 // exception-specification fails to allocate storage, it shall return
9430 // a null pointer. Any other allocation function that fails to allocate
9431 // storage shall indicate failure only by throwing an exception [...]
9432 if (FD) {
9434 if (Op == OO_New || Op == OO_Array_New) {
9435 const FunctionProtoType *Proto
9436 = FD->getType()->castAs<FunctionProtoType>();
9437 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9438 CheckNonNullExpr(*this, RetValExp))
9439 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9440 << FD << getLangOpts().CPlusPlus11;
9441 }
9442 }
9443
9444 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
9445 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
9446 }
9447
9448 // PPC MMA non-pointer types are not allowed as return type. Checking the type
9449 // here prevent the user from using a PPC MMA type as trailing return type.
9450 if (Context.getTargetInfo().getTriple().isPPC64())
9451 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
9452}
9453
9455 BinaryOperatorKind Opcode) {
9456 if (!BinaryOperator::isEqualityOp(Opcode))
9457 return;
9458
9459 // Match and capture subexpressions such as "(float) X == 0.1".
9460 FloatingLiteral *FPLiteral;
9461 CastExpr *FPCast;
9462 auto getCastAndLiteral = [&FPLiteral, &FPCast](Expr *L, Expr *R) {
9463 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
9464 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
9465 return FPLiteral && FPCast;
9466 };
9467
9468 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
9469 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
9470 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
9471 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
9472 TargetTy->isFloatingPoint()) {
9473 bool Lossy;
9474 llvm::APFloat TargetC = FPLiteral->getValue();
9475 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
9476 llvm::APFloat::rmNearestTiesToEven, &Lossy);
9477 if (Lossy) {
9478 // If the literal cannot be represented in the source type, then a
9479 // check for == is always false and check for != is always true.
9480 Diag(Loc, diag::warn_float_compare_literal)
9481 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
9482 << LHS->getSourceRange() << RHS->getSourceRange();
9483 return;
9484 }
9485 }
9486 }
9487
9488 // Match a more general floating-point equality comparison (-Wfloat-equal).
9489 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9490 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9491
9492 // Special case: check for x == x (which is OK).
9493 // Do not emit warnings for such cases.
9494 if (auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9495 if (auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9496 if (DRL->getDecl() == DRR->getDecl())
9497 return;
9498
9499 // Special case: check for comparisons against literals that can be exactly
9500 // represented by APFloat. In such cases, do not emit a warning. This
9501 // is a heuristic: often comparison against such literals are used to
9502 // detect if a value in a variable has not changed. This clearly can
9503 // lead to false negatives.
9504 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9505 if (FLL->isExact())
9506 return;
9507 } else
9508 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9509 if (FLR->isExact())
9510 return;
9511
9512 // Check for comparisons with builtin types.
9513 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9514 if (CL->getBuiltinCallee())
9515 return;
9516
9517 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9518 if (CR->getBuiltinCallee())
9519 return;
9520
9521 // Emit the diagnostic.
9522 Diag(Loc, diag::warn_floatingpoint_eq)
9523 << LHS->getSourceRange() << RHS->getSourceRange();
9524}
9525
9526//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9527//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9528
9529namespace {
9530
9531/// Structure recording the 'active' range of an integer-valued
9532/// expression.
9533struct IntRange {
9534 /// The number of bits active in the int. Note that this includes exactly one
9535 /// sign bit if !NonNegative.
9536 unsigned Width;
9537
9538 /// True if the int is known not to have negative values. If so, all leading
9539 /// bits before Width are known zero, otherwise they are known to be the
9540 /// same as the MSB within Width.
9541 bool NonNegative;
9542
9543 IntRange(unsigned Width, bool NonNegative)
9544 : Width(Width), NonNegative(NonNegative) {}
9545
9546 /// Number of bits excluding the sign bit.
9547 unsigned valueBits() const {
9548 return NonNegative ? Width : Width - 1;
9549 }
9550
9551 /// Returns the range of the bool type.
9552 static IntRange forBoolType() {
9553 return IntRange(1, true);
9554 }
9555
9556 /// Returns the range of an opaque value of the given integral type.
9557 static IntRange forValueOfType(ASTContext &C, QualType T) {
9558 return forValueOfCanonicalType(C,
9560 }
9561
9562 /// Returns the range of an opaque value of a canonical integral type.
9563 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9564 assert(T->isCanonicalUnqualified());
9565
9566 if (const VectorType *VT = dyn_cast<VectorType>(T))
9567 T = VT->getElementType().getTypePtr();
9568 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9569 T = CT->getElementType().getTypePtr();
9570 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9571 T = AT->getValueType().getTypePtr();
9572
9573 if (!C.getLangOpts().CPlusPlus) {
9574 // For enum types in C code, use the underlying datatype.
9575 if (const EnumType *ET = dyn_cast<EnumType>(T))
9576 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9577 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9578 // For enum types in C++, use the known bit width of the enumerators.
9579 EnumDecl *Enum = ET->getDecl();
9580 // In C++11, enums can have a fixed underlying type. Use this type to
9581 // compute the range.
9582 if (Enum->isFixed()) {
9583 return IntRange(C.getIntWidth(QualType(T, 0)),
9584 !ET->isSignedIntegerOrEnumerationType());
9585 }
9586
9587 unsigned NumPositive = Enum->getNumPositiveBits();
9588 unsigned NumNegative = Enum->getNumNegativeBits();
9589
9590 if (NumNegative == 0)
9591 return IntRange(NumPositive, true/*NonNegative*/);
9592 else
9593 return IntRange(std::max(NumPositive + 1, NumNegative),
9594 false/*NonNegative*/);
9595 }
9596
9597 if (const auto *EIT = dyn_cast<BitIntType>(T))
9598 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
9599
9600 const BuiltinType *BT = cast<BuiltinType>(T);
9601 assert(BT->isInteger());
9602
9603 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9604 }
9605
9606 /// Returns the "target" range of a canonical integral type, i.e.
9607 /// the range of values expressible in the type.
9608 ///
9609 /// This matches forValueOfCanonicalType except that enums have the
9610 /// full range of their type, not the range of their enumerators.
9611 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9612 assert(T->isCanonicalUnqualified());
9613
9614 if (const VectorType *VT = dyn_cast<VectorType>(T))
9615 T = VT->getElementType().getTypePtr();
9616 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9617 T = CT->getElementType().getTypePtr();
9618 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9619 T = AT->getValueType().getTypePtr();
9620 if (const EnumType *ET = dyn_cast<EnumType>(T))
9621 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9622
9623 if (const auto *EIT = dyn_cast<BitIntType>(T))
9624 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
9625
9626 const BuiltinType *BT = cast<BuiltinType>(T);
9627 assert(BT->isInteger());
9628
9629 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9630 }
9631
9632 /// Returns the supremum of two ranges: i.e. their conservative merge.
9633 static IntRange join(IntRange L, IntRange R) {
9634 bool Unsigned = L.NonNegative && R.NonNegative;
9635 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
9636 L.NonNegative && R.NonNegative);
9637 }
9638
9639 /// Return the range of a bitwise-AND of the two ranges.
9640 static IntRange bit_and(IntRange L, IntRange R) {
9641 unsigned Bits = std::max(L.Width, R.Width);
9642 bool NonNegative = false;
9643 if (L.NonNegative) {
9644 Bits = std::min(Bits, L.Width);
9645 NonNegative = true;
9646 }
9647 if (R.NonNegative) {
9648 Bits = std::min(Bits, R.Width);
9649 NonNegative = true;
9650 }
9651 return IntRange(Bits, NonNegative);
9652 }
9653
9654 /// Return the range of a sum of the two ranges.
9655 static IntRange sum(IntRange L, IntRange R) {
9656 bool Unsigned = L.NonNegative && R.NonNegative;
9657 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
9658 Unsigned);
9659 }
9660
9661 /// Return the range of a difference of the two ranges.
9662 static IntRange difference(IntRange L, IntRange R) {
9663 // We need a 1-bit-wider range if:
9664 // 1) LHS can be negative: least value can be reduced.
9665 // 2) RHS can be negative: greatest value can be increased.
9666 bool CanWiden = !L.NonNegative || !R.NonNegative;
9667 bool Unsigned = L.NonNegative && R.Width == 0;
9668 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
9669 !Unsigned,
9670 Unsigned);
9671 }
9672
9673 /// Return the range of a product of the two ranges.
9674 static IntRange product(IntRange L, IntRange R) {
9675 // If both LHS and RHS can be negative, we can form
9676 // -2^L * -2^R = 2^(L + R)
9677 // which requires L + R + 1 value bits to represent.
9678 bool CanWiden = !L.NonNegative && !R.NonNegative;
9679 bool Unsigned = L.NonNegative && R.NonNegative;
9680 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
9681 Unsigned);
9682 }
9683
9684 /// Return the range of a remainder operation between the two ranges.
9685 static IntRange rem(IntRange L, IntRange R) {
9686 // The result of a remainder can't be larger than the result of
9687 // either side. The sign of the result is the sign of the LHS.
9688 bool Unsigned = L.NonNegative;
9689 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
9690 Unsigned);
9691 }
9692};
9693
9694} // namespace
9695
9696static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9697 unsigned MaxWidth) {
9698 if (value.isSigned() && value.isNegative())
9699 return IntRange(value.getSignificantBits(), false);
9700
9701 if (value.getBitWidth() > MaxWidth)
9702 value = value.trunc(MaxWidth);
9703
9704 // isNonNegative() just checks the sign bit without considering
9705 // signedness.
9706 return IntRange(value.getActiveBits(), true);
9707}
9708
9709static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9710 unsigned MaxWidth) {
9711 if (result.isInt())
9712 return GetValueRange(C, result.getInt(), MaxWidth);
9713
9714 if (result.isVector()) {
9715 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9716 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9717 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9718 R = IntRange::join(R, El);
9719 }
9720 return R;
9721 }
9722
9723 if (result.isComplexInt()) {
9724 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9725 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9726 return IntRange::join(R, I);
9727 }
9728
9729 // This can happen with lossless casts to intptr_t of "based" lvalues.
9730 // Assume it might use arbitrary bits.
9731 // FIXME: The only reason we need to pass the type in here is to get
9732 // the sign right on this one case. It would be nice if APValue
9733 // preserved this.
9734 assert(result.isLValue() || result.isAddrLabelDiff());
9735 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
9736}
9737
9738static QualType GetExprType(const Expr *E) {
9739 QualType Ty = E->getType();
9740 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9741 Ty = AtomicRHS->getValueType();
9742 return Ty;
9743}
9744
9745/// Attempts to estimate an approximate range for the given integer expression.
9746/// Returns a range if successful, otherwise it returns \c std::nullopt if a
9747/// reliable estimation cannot be determined.
9748///
9749/// \param MaxWidth The width to which the value will be truncated.
9750/// \param InConstantContext If \c true, interpret the expression within a
9751/// constant context.
9752/// \param Approximate If \c true, provide a likely range of values by assuming
9753/// that arithmetic on narrower types remains within those types.
9754/// If \c false, return a range that includes all possible values
9755/// resulting from the expression.
9756/// \returns A range of values that the expression might take, or
9757/// std::nullopt if a reliable estimation cannot be determined.
9758static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
9759 unsigned MaxWidth,
9760 bool InConstantContext,
9761 bool Approximate) {
9762 E = E->IgnoreParens();
9763
9764 // Try a full evaluation first.
9765 Expr::EvalResult result;
9766 if (E->EvaluateAsRValue(result, C, InConstantContext))
9767 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
9768
9769 // I think we only want to look through implicit casts here; if the
9770 // user has an explicit widening cast, we should treat the value as
9771 // being of the new, wider type.
9772 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
9773 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
9774 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
9775 Approximate);
9776
9777 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
9778
9779 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9780 CE->getCastKind() == CK_BooleanToSignedIntegral;
9781
9782 // Assume that non-integer casts can span the full range of the type.
9783 if (!isIntegerCast)
9784 return OutputTypeRange;
9785
9786 std::optional<IntRange> SubRange = TryGetExprRange(
9787 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
9788 InConstantContext, Approximate);
9789 if (!SubRange)
9790 return std::nullopt;
9791
9792 // Bail out if the subexpr's range is as wide as the cast type.
9793 if (SubRange->Width >= OutputTypeRange.Width)
9794 return OutputTypeRange;
9795
9796 // Otherwise, we take the smaller width, and we're non-negative if
9797 // either the output type or the subexpr is.
9798 return IntRange(SubRange->Width,
9799 SubRange->NonNegative || OutputTypeRange.NonNegative);
9800 }
9801
9802 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
9803 // If we can fold the condition, just take that operand.
9804 bool CondResult;
9805 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9806 return TryGetExprRange(
9807 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
9808 InConstantContext, Approximate);
9809
9810 // Otherwise, conservatively merge.
9811 // TryGetExprRange requires an integer expression, but a throw expression
9812 // results in a void type.
9813 Expr *TrueExpr = CO->getTrueExpr();
9814 if (TrueExpr->getType()->isVoidType())
9815 return std::nullopt;
9816
9817 std::optional<IntRange> L =
9818 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
9819 if (!L)
9820 return std::nullopt;
9821
9822 Expr *FalseExpr = CO->getFalseExpr();
9823 if (FalseExpr->getType()->isVoidType())
9824 return std::nullopt;
9825
9826 std::optional<IntRange> R =
9827 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
9828 if (!R)
9829 return std::nullopt;
9830
9831 return IntRange::join(*L, *R);
9832 }
9833
9834 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
9835 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
9836
9837 switch (BO->getOpcode()) {
9838 case BO_Cmp:
9839 llvm_unreachable("builtin <=> should have class type");
9840
9841 // Boolean-valued operations are single-bit and positive.
9842 case BO_LAnd:
9843 case BO_LOr:
9844 case BO_LT:
9845 case BO_GT:
9846 case BO_LE:
9847 case BO_GE:
9848 case BO_EQ:
9849 case BO_NE:
9850 return IntRange::forBoolType();
9851
9852 // The type of the assignments is the type of the LHS, so the RHS
9853 // is not necessarily the same type.
9854 case BO_MulAssign:
9855 case BO_DivAssign:
9856 case BO_RemAssign:
9857 case BO_AddAssign:
9858 case BO_SubAssign:
9859 case BO_XorAssign:
9860 case BO_OrAssign:
9861 // TODO: bitfields?
9862 return IntRange::forValueOfType(C, GetExprType(E));
9863
9864 // Simple assignments just pass through the RHS, which will have
9865 // been coerced to the LHS type.
9866 case BO_Assign:
9867 // TODO: bitfields?
9868 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
9869 Approximate);
9870
9871 // Operations with opaque sources are black-listed.
9872 case BO_PtrMemD:
9873 case BO_PtrMemI:
9874 return IntRange::forValueOfType(C, GetExprType(E));
9875
9876 // Bitwise-and uses the *infinum* of the two source ranges.
9877 case BO_And:
9878 case BO_AndAssign:
9879 Combine = IntRange::bit_and;
9880 break;
9881
9882 // Left shift gets black-listed based on a judgement call.
9883 case BO_Shl:
9884 // ...except that we want to treat '1 << (blah)' as logically
9885 // positive. It's an important idiom.
9886 if (IntegerLiteral *I
9887 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9888 if (I->getValue() == 1) {
9889 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
9890 return IntRange(R.Width, /*NonNegative*/ true);
9891 }
9892 }
9893 [[fallthrough]];
9894
9895 case BO_ShlAssign:
9896 return IntRange::forValueOfType(C, GetExprType(E));
9897
9898 // Right shift by a constant can narrow its left argument.
9899 case BO_Shr:
9900 case BO_ShrAssign: {
9901 std::optional<IntRange> L = TryGetExprRange(
9902 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
9903 if (!L)
9904 return std::nullopt;
9905
9906 // If the shift amount is a positive constant, drop the width by
9907 // that much.
9908 if (std::optional<llvm::APSInt> shift =
9909 BO->getRHS()->getIntegerConstantExpr(C)) {
9910 if (shift->isNonNegative()) {
9911 if (shift->uge(L->Width))
9912 L->Width = (L->NonNegative ? 0 : 1);
9913 else
9914 L->Width -= shift->getZExtValue();
9915 }
9916 }
9917
9918 return L;
9919 }
9920
9921 // Comma acts as its right operand.
9922 case BO_Comma:
9923 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
9924 Approximate);
9925
9926 case BO_Add:
9927 if (!Approximate)
9928 Combine = IntRange::sum;
9929 break;
9930
9931 case BO_Sub:
9932 if (BO->getLHS()->getType()->isPointerType())
9933 return IntRange::forValueOfType(C, GetExprType(E));
9934 if (!Approximate)
9935 Combine = IntRange::difference;
9936 break;
9937
9938 case BO_Mul:
9939 if (!Approximate)
9940 Combine = IntRange::product;
9941 break;
9942
9943 // The width of a division result is mostly determined by the size
9944 // of the LHS.
9945 case BO_Div: {
9946 // Don't 'pre-truncate' the operands.
9947 unsigned opWidth = C.getIntWidth(GetExprType(E));
9948 std::optional<IntRange> L = TryGetExprRange(
9949 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
9950 if (!L)
9951 return std::nullopt;
9952
9953 // If the divisor is constant, use that.
9954 if (std::optional<llvm::APSInt> divisor =
9955 BO->getRHS()->getIntegerConstantExpr(C)) {
9956 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
9957 if (log2 >= L->Width)
9958 L->Width = (L->NonNegative ? 0 : 1);
9959 else
9960 L->Width = std::min(L->Width - log2, MaxWidth);
9961 return L;
9962 }
9963
9964 // Otherwise, just use the LHS's width.
9965 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
9966 // could be -1.
9967 std::optional<IntRange> R = TryGetExprRange(
9968 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
9969 if (!R)
9970 return std::nullopt;
9971
9972 return IntRange(L->Width, L->NonNegative && R->NonNegative);
9973 }
9974
9975 case BO_Rem:
9976 Combine = IntRange::rem;
9977 break;
9978
9979 // The default behavior is okay for these.
9980 case BO_Xor:
9981 case BO_Or:
9982 break;
9983 }
9984
9985 // Combine the two ranges, but limit the result to the type in which we
9986 // performed the computation.
9988 unsigned opWidth = C.getIntWidth(T);
9989 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
9990 InConstantContext, Approximate);
9991 if (!L)
9992 return std::nullopt;
9993
9994 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
9995 InConstantContext, Approximate);
9996 if (!R)
9997 return std::nullopt;
9998
9999 IntRange C = Combine(*L, *R);
10000 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
10001 C.Width = std::min(C.Width, MaxWidth);
10002 return C;
10003 }
10004
10005 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10006 switch (UO->getOpcode()) {
10007 // Boolean-valued operations are white-listed.
10008 case UO_LNot:
10009 return IntRange::forBoolType();
10010
10011 // Operations with opaque sources are black-listed.
10012 case UO_Deref:
10013 case UO_AddrOf: // should be impossible
10014 return IntRange::forValueOfType(C, GetExprType(E));
10015
10016 default:
10017 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
10018 Approximate);
10019 }
10020 }
10021
10022 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10023 return TryGetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
10024 Approximate);
10025
10026 if (const auto *BitField = E->getSourceBitField())
10027 return IntRange(BitField->getBitWidthValue(C),
10028 BitField->getType()->isUnsignedIntegerOrEnumerationType());
10029
10030 if (GetExprType(E)->isVoidType())
10031 return std::nullopt;
10032
10033 return IntRange::forValueOfType(C, GetExprType(E));
10034}
10035
10036static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
10037 bool InConstantContext,
10038 bool Approximate) {
10039 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
10040 Approximate);
10041}
10042
10043/// Checks whether the given value, which currently has the given
10044/// source semantics, has the same value when coerced through the
10045/// target semantics.
10046static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10047 const llvm::fltSemantics &Src,
10048 const llvm::fltSemantics &Tgt) {
10049 llvm::APFloat truncated = value;
10050
10051 bool ignored;
10052 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10053 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10054
10055 return truncated.bitwiseIsEqual(value);
10056}
10057
10058/// Checks whether the given value, which currently has the given
10059/// source semantics, has the same value when coerced through the
10060/// target semantics.
10061///
10062/// The value might be a vector of floats (or a complex number).
10063static bool IsSameFloatAfterCast(const APValue &value,
10064 const llvm::fltSemantics &Src,
10065 const llvm::fltSemantics &Tgt) {
10066 if (value.isFloat())
10067 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10068
10069 if (value.isVector()) {
10070 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10071 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10072 return false;
10073 return true;
10074 }
10075
10076 assert(value.isComplexFloat());
10077 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10078 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10079}
10080
10082 bool IsListInit = false);
10083
10085 // Suppress cases where we are comparing against an enum constant.
10086 if (const DeclRefExpr *DR =
10087 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10088 if (isa<EnumConstantDecl>(DR->getDecl()))
10089 return true;
10090
10091 // Suppress cases where the value is expanded from a macro, unless that macro
10092 // is how a language represents a boolean literal. This is the case in both C
10093 // and Objective-C.
10094 SourceLocation BeginLoc = E->getBeginLoc();
10095 if (BeginLoc.isMacroID()) {
10096 StringRef MacroName = Lexer::getImmediateMacroName(
10097 BeginLoc, S.getSourceManager(), S.getLangOpts());
10098 return MacroName != "YES" && MacroName != "NO" &&
10099 MacroName != "true" && MacroName != "false";
10100 }
10101
10102 return false;
10103}
10104
10106 return E->getType()->isIntegerType() &&
10107 (!E->getType()->isSignedIntegerType() ||
10109}
10110
10111namespace {
10112/// The promoted range of values of a type. In general this has the
10113/// following structure:
10114///
10115/// |-----------| . . . |-----------|
10116/// ^ ^ ^ ^
10117/// Min HoleMin HoleMax Max
10118///
10119/// ... where there is only a hole if a signed type is promoted to unsigned
10120/// (in which case Min and Max are the smallest and largest representable
10121/// values).
10122struct PromotedRange {
10123 // Min, or HoleMax if there is a hole.
10124 llvm::APSInt PromotedMin;
10125 // Max, or HoleMin if there is a hole.
10126 llvm::APSInt PromotedMax;
10127
10128 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10129 if (R.Width == 0)
10130 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10131 else if (R.Width >= BitWidth && !Unsigned) {
10132 // Promotion made the type *narrower*. This happens when promoting
10133 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10134 // Treat all values of 'signed int' as being in range for now.
10135 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10136 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10137 } else {
10138 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10139 .extOrTrunc(BitWidth);
10140 PromotedMin.setIsUnsigned(Unsigned);
10141
10142 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10143 .extOrTrunc(BitWidth);
10144 PromotedMax.setIsUnsigned(Unsigned);
10145 }
10146 }
10147
10148 // Determine whether this range is contiguous (has no hole).
10149 bool isContiguous() const { return PromotedMin <= PromotedMax; }
10150
10151 // Where a constant value is within the range.
10152 enum ComparisonResult {
10153 LT = 0x1,
10154 LE = 0x2,
10155 GT = 0x4,
10156 GE = 0x8,
10157 EQ = 0x10,
10158 NE = 0x20,
10159 InRangeFlag = 0x40,
10160
10161 Less = LE | LT | NE,
10162 Min = LE | InRangeFlag,
10163 InRange = InRangeFlag,
10164 Max = GE | InRangeFlag,
10165 Greater = GE | GT | NE,
10166
10167 OnlyValue = LE | GE | EQ | InRangeFlag,
10168 InHole = NE
10169 };
10170
10171 ComparisonResult compare(const llvm::APSInt &Value) const {
10172 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10173 Value.isUnsigned() == PromotedMin.isUnsigned());
10174 if (!isContiguous()) {
10175 assert(Value.isUnsigned() && "discontiguous range for signed compare");
10176 if (Value.isMinValue()) return Min;
10177 if (Value.isMaxValue()) return Max;
10178 if (Value >= PromotedMin) return InRange;
10179 if (Value <= PromotedMax) return InRange;
10180 return InHole;
10181 }
10182
10183 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10184 case -1: return Less;
10185 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10186 case 1:
10187 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10188 case -1: return InRange;
10189 case 0: return Max;
10190 case 1: return Greater;
10191 }
10192 }
10193
10194 llvm_unreachable("impossible compare result");
10195 }
10196
10197 static std::optional<StringRef>
10198 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10199 if (Op == BO_Cmp) {
10200 ComparisonResult LTFlag = LT, GTFlag = GT;
10201 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10202
10203 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10204 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10205 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10206 return std::nullopt;
10207 }
10208
10209 ComparisonResult TrueFlag, FalseFlag;
10210 if (Op == BO_EQ) {
10211 TrueFlag = EQ;
10212 FalseFlag = NE;
10213 } else if (Op == BO_NE) {
10214 TrueFlag = NE;
10215 FalseFlag = EQ;
10216 } else {
10217 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10218 TrueFlag = LT;
10219 FalseFlag = GE;
10220 } else {
10221 TrueFlag = GT;
10222 FalseFlag = LE;
10223 }
10224 if (Op == BO_GE || Op == BO_LE)
10225 std::swap(TrueFlag, FalseFlag);
10226 }
10227 if (R & TrueFlag)
10228 return StringRef("true");
10229 if (R & FalseFlag)
10230 return StringRef("false");
10231 return std::nullopt;
10232 }
10233};
10234}
10235
10236static bool HasEnumType(Expr *E) {
10237 // Strip off implicit integral promotions.
10238 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10239 if (ICE->getCastKind() != CK_IntegralCast &&
10240 ICE->getCastKind() != CK_NoOp)
10241 break;
10242 E = ICE->getSubExpr();
10243 }
10244
10245 return E->getType()->isEnumeralType();
10246}
10247
10248static int classifyConstantValue(Expr *Constant) {
10249 // The values of this enumeration are used in the diagnostics
10250 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10251 enum ConstantValueKind {
10252 Miscellaneous = 0,
10253 LiteralTrue,
10254 LiteralFalse
10255 };
10256 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10257 return BL->getValue() ? ConstantValueKind::LiteralTrue
10258 : ConstantValueKind::LiteralFalse;
10259 return ConstantValueKind::Miscellaneous;
10260}
10261
10263 Expr *Constant, Expr *Other,
10264 const llvm::APSInt &Value,
10265 bool RhsConstant) {
10267 return false;
10268
10269 Expr *OriginalOther = Other;
10270
10271 Constant = Constant->IgnoreParenImpCasts();
10272 Other = Other->IgnoreParenImpCasts();
10273
10274 // Suppress warnings on tautological comparisons between values of the same
10275 // enumeration type. There are only two ways we could warn on this:
10276 // - If the constant is outside the range of representable values of
10277 // the enumeration. In such a case, we should warn about the cast
10278 // to enumeration type, not about the comparison.
10279 // - If the constant is the maximum / minimum in-range value. For an
10280 // enumeratin type, such comparisons can be meaningful and useful.
10281 if (Constant->getType()->isEnumeralType() &&
10282 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10283 return false;
10284
10285 std::optional<IntRange> OtherValueRange = TryGetExprRange(
10286 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
10287 if (!OtherValueRange)
10288 return false;
10289
10290 QualType OtherT = Other->getType();
10291 if (const auto *AT = OtherT->getAs<AtomicType>())
10292 OtherT = AT->getValueType();
10293 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
10294
10295 // Special case for ObjC BOOL on targets where its a typedef for a signed char
10296 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
10297 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10298 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
10299 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10300
10301 // Whether we're treating Other as being a bool because of the form of
10302 // expression despite it having another type (typically 'int' in C).
10303 bool OtherIsBooleanDespiteType =
10304 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10305 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10306 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
10307
10308 // Check if all values in the range of possible values of this expression
10309 // lead to the same comparison outcome.
10310 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
10311 Value.isUnsigned());
10312 auto Cmp = OtherPromotedValueRange.compare(Value);
10313 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10314 if (!Result)
10315 return false;
10316
10317 // Also consider the range determined by the type alone. This allows us to
10318 // classify the warning under the proper diagnostic group.
10319 bool TautologicalTypeCompare = false;
10320 {
10321 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
10322 Value.isUnsigned());
10323 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
10324 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
10325 RhsConstant)) {
10326 TautologicalTypeCompare = true;
10327 Cmp = TypeCmp;
10329 }
10330 }
10331
10332 // Don't warn if the non-constant operand actually always evaluates to the
10333 // same value.
10334 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
10335 return false;
10336
10337 // Suppress the diagnostic for an in-range comparison if the constant comes
10338 // from a macro or enumerator. We don't want to diagnose
10339 //
10340 // some_long_value <= INT_MAX
10341 //
10342 // when sizeof(int) == sizeof(long).
10343 bool InRange = Cmp & PromotedRange::InRangeFlag;
10344 if (InRange && IsEnumConstOrFromMacro(S, Constant))
10345 return false;
10346
10347 // A comparison of an unsigned bit-field against 0 is really a type problem,
10348 // even though at the type level the bit-field might promote to 'signed int'.
10349 if (Other->refersToBitField() && InRange && Value == 0 &&
10350 Other->getType()->isUnsignedIntegerOrEnumerationType())
10351 TautologicalTypeCompare = true;
10352
10353 // If this is a comparison to an enum constant, include that
10354 // constant in the diagnostic.
10355 const EnumConstantDecl *ED = nullptr;
10356 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10357 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10358
10359 // Should be enough for uint128 (39 decimal digits)
10360 SmallString<64> PrettySourceValue;
10361 llvm::raw_svector_ostream OS(PrettySourceValue);
10362 if (ED) {
10363 OS << '\'' << *ED << "' (" << Value << ")";
10364 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10365 Constant->IgnoreParenImpCasts())) {
10366 OS << (BL->getValue() ? "YES" : "NO");
10367 } else {
10368 OS << Value;
10369 }
10370
10371 if (!TautologicalTypeCompare) {
10372 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
10373 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
10374 << E->getOpcodeStr() << OS.str() << *Result
10375 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10376 return true;
10377 }
10378
10379 if (IsObjCSignedCharBool) {
10380 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10381 S.PDiag(diag::warn_tautological_compare_objc_bool)
10382 << OS.str() << *Result);
10383 return true;
10384 }
10385
10386 // FIXME: We use a somewhat different formatting for the in-range cases and
10387 // cases involving boolean values for historical reasons. We should pick a
10388 // consistent way of presenting these diagnostics.
10389 if (!InRange || Other->isKnownToHaveBooleanValue()) {
10390
10392 E->getOperatorLoc(), E,
10393 S.PDiag(!InRange ? diag::warn_out_of_range_compare
10394 : diag::warn_tautological_bool_compare)
10395 << OS.str() << classifyConstantValue(Constant) << OtherT
10396 << OtherIsBooleanDespiteType << *Result
10397 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10398 } else {
10399 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
10400 unsigned Diag =
10401 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10402 ? (HasEnumType(OriginalOther)
10403 ? diag::warn_unsigned_enum_always_true_comparison
10404 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
10405 : diag::warn_unsigned_always_true_comparison)
10406 : diag::warn_tautological_constant_compare;
10407
10408 S.Diag(E->getOperatorLoc(), Diag)
10409 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10410 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10411 }
10412
10413 return true;
10414}
10415
10416/// Analyze the operands of the given comparison. Implements the
10417/// fallback case from AnalyzeComparison.
10419 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10420 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10421}
10422
10423/// Implements -Wsign-compare.
10424///
10425/// \param E the binary operator to check for warnings
10427 // The type the comparison is being performed in.
10428 QualType T = E->getLHS()->getType();
10429
10430 // Only analyze comparison operators where both sides have been converted to
10431 // the same type.
10432 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10433 return AnalyzeImpConvsInComparison(S, E);
10434
10435 // Don't analyze value-dependent comparisons directly.
10436 if (E->isValueDependent())
10437 return AnalyzeImpConvsInComparison(S, E);
10438
10439 Expr *LHS = E->getLHS();
10440 Expr *RHS = E->getRHS();
10441
10442 if (T->isIntegralType(S.Context)) {
10443 std::optional<llvm::APSInt> RHSValue =
10445 std::optional<llvm::APSInt> LHSValue =
10447
10448 // We don't care about expressions whose result is a constant.
10449 if (RHSValue && LHSValue)
10450 return AnalyzeImpConvsInComparison(S, E);
10451
10452 // We only care about expressions where just one side is literal
10453 if ((bool)RHSValue ^ (bool)LHSValue) {
10454 // Is the constant on the RHS or LHS?
10455 const bool RhsConstant = (bool)RHSValue;
10456 Expr *Const = RhsConstant ? RHS : LHS;
10457 Expr *Other = RhsConstant ? LHS : RHS;
10458 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
10459
10460 // Check whether an integer constant comparison results in a value
10461 // of 'true' or 'false'.
10462 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10463 return AnalyzeImpConvsInComparison(S, E);
10464 }
10465 }
10466
10468 // We don't do anything special if this isn't an unsigned integral
10469 // comparison: we're only interested in integral comparisons, and
10470 // signed comparisons only happen in cases we don't care to warn about.
10471 return AnalyzeImpConvsInComparison(S, E);
10472 }
10473
10474 LHS = LHS->IgnoreParenImpCasts();
10475 RHS = RHS->IgnoreParenImpCasts();
10476
10477 if (!S.getLangOpts().CPlusPlus) {
10478 // Avoid warning about comparison of integers with different signs when
10479 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10480 // the type of `E`.
10481 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10482 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10483 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10484 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10485 }
10486
10487 // Check to see if one of the (unmodified) operands is of different
10488 // signedness.
10489 Expr *signedOperand, *unsignedOperand;
10491 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10492 "unsigned comparison between two signed integer expressions?");
10493 signedOperand = LHS;
10494 unsignedOperand = RHS;
10495 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10496 signedOperand = RHS;
10497 unsignedOperand = LHS;
10498 } else {
10499 return AnalyzeImpConvsInComparison(S, E);
10500 }
10501
10502 // Otherwise, calculate the effective range of the signed operand.
10503 std::optional<IntRange> signedRange =
10505 /*Approximate=*/true);
10506 if (!signedRange)
10507 return;
10508
10509 // Go ahead and analyze implicit conversions in the operands. Note
10510 // that we skip the implicit conversions on both sides.
10511 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10512 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10513
10514 // If the signed range is non-negative, -Wsign-compare won't fire.
10515 if (signedRange->NonNegative)
10516 return;
10517
10518 // For (in)equality comparisons, if the unsigned operand is a
10519 // constant which cannot collide with a overflowed signed operand,
10520 // then reinterpreting the signed operand as unsigned will not
10521 // change the result of the comparison.
10522 if (E->isEqualityOp()) {
10523 unsigned comparisonWidth = S.Context.getIntWidth(T);
10524 std::optional<IntRange> unsignedRange = TryGetExprRange(
10525 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
10526 /*Approximate=*/true);
10527 if (!unsignedRange)
10528 return;
10529
10530 // We should never be unable to prove that the unsigned operand is
10531 // non-negative.
10532 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
10533
10534 if (unsignedRange->Width < comparisonWidth)
10535 return;
10536 }
10537
10538 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10539 S.PDiag(diag::warn_mixed_sign_comparison)
10540 << LHS->getType() << RHS->getType()
10541 << LHS->getSourceRange() << RHS->getSourceRange());
10542}
10543
10544/// Analyzes an attempt to assign the given value to a bitfield.
10545///
10546/// Returns true if there was something fishy about the attempt.
10548 SourceLocation InitLoc) {
10549 assert(Bitfield->isBitField());
10550 if (Bitfield->isInvalidDecl())
10551 return false;
10552
10553 // White-list bool bitfields.
10554 QualType BitfieldType = Bitfield->getType();
10555 if (BitfieldType->isBooleanType())
10556 return false;
10557
10558 if (BitfieldType->isEnumeralType()) {
10559 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10560 // If the underlying enum type was not explicitly specified as an unsigned
10561 // type and the enum contain only positive values, MSVC++ will cause an
10562 // inconsistency by storing this as a signed type.
10563 if (S.getLangOpts().CPlusPlus11 &&
10564 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10565 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10566 BitfieldEnumDecl->getNumNegativeBits() == 0) {
10567 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10568 << BitfieldEnumDecl;
10569 }
10570 }
10571
10572 // Ignore value- or type-dependent expressions.
10573 if (Bitfield->getBitWidth()->isValueDependent() ||
10574 Bitfield->getBitWidth()->isTypeDependent() ||
10575 Init->isValueDependent() ||
10576 Init->isTypeDependent())
10577 return false;
10578
10579 Expr *OriginalInit = Init->IgnoreParenImpCasts();
10580 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10581
10583 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10585 // The RHS is not constant. If the RHS has an enum type, make sure the
10586 // bitfield is wide enough to hold all the values of the enum without
10587 // truncation.
10588 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10589 EnumDecl *ED = EnumTy->getDecl();
10590 bool SignedBitfield = BitfieldType->isSignedIntegerType();
10591
10592 // Enum types are implicitly signed on Windows, so check if there are any
10593 // negative enumerators to see if the enum was intended to be signed or
10594 // not.
10595 bool SignedEnum = ED->getNumNegativeBits() > 0;
10596
10597 // Check for surprising sign changes when assigning enum values to a
10598 // bitfield of different signedness. If the bitfield is signed and we
10599 // have exactly the right number of bits to store this unsigned enum,
10600 // suggest changing the enum to an unsigned type. This typically happens
10601 // on Windows where unfixed enums always use an underlying type of 'int'.
10602 unsigned DiagID = 0;
10603 if (SignedEnum && !SignedBitfield) {
10604 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10605 } else if (SignedBitfield && !SignedEnum &&
10606 ED->getNumPositiveBits() == FieldWidth) {
10607 DiagID = diag::warn_signed_bitfield_enum_conversion;
10608 }
10609
10610 if (DiagID) {
10611 S.Diag(InitLoc, DiagID) << Bitfield << ED;
10612 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10613 SourceRange TypeRange =
10614 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10615 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10616 << SignedEnum << TypeRange;
10617 }
10618
10619 // Compute the required bitwidth. If the enum has negative values, we need
10620 // one more bit than the normal number of positive bits to represent the
10621 // sign bit.
10622 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10623 ED->getNumNegativeBits())
10624 : ED->getNumPositiveBits();
10625
10626 // Check the bitwidth.
10627 if (BitsNeeded > FieldWidth) {
10628 Expr *WidthExpr = Bitfield->getBitWidth();
10629 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10630 << Bitfield << ED;
10631 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10632 << BitsNeeded << ED << WidthExpr->getSourceRange();
10633 }
10634 }
10635
10636 return false;
10637 }
10638
10639 llvm::APSInt Value = Result.Val.getInt();
10640
10641 unsigned OriginalWidth = Value.getBitWidth();
10642
10643 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
10644 // false positives where the user is demonstrating they intend to use the
10645 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
10646 // to a one-bit bit-field to see if the value came from a macro named 'true'.
10647 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
10648 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
10649 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
10650 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
10651 S.findMacroSpelling(MaybeMacroLoc, "true"))
10652 return false;
10653 }
10654
10655 if (!Value.isSigned() || Value.isNegative())
10656 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10657 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10658 OriginalWidth = Value.getSignificantBits();
10659
10660 if (OriginalWidth <= FieldWidth)
10661 return false;
10662
10663 // Compute the value which the bitfield will contain.
10664 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10665 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10666
10667 // Check whether the stored value is equal to the original value.
10668 TruncatedValue = TruncatedValue.extend(OriginalWidth);
10669 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10670 return false;
10671
10672 std::string PrettyValue = toString(Value, 10);
10673 std::string PrettyTrunc = toString(TruncatedValue, 10);
10674
10675 S.Diag(InitLoc, OneAssignedToOneBitBitfield
10676 ? diag::warn_impcast_single_bit_bitield_precision_constant
10677 : diag::warn_impcast_bitfield_precision_constant)
10678 << PrettyValue << PrettyTrunc << OriginalInit->getType()
10679 << Init->getSourceRange();
10680
10681 return true;
10682}
10683
10684/// Analyze the given simple or compound assignment for warning-worthy
10685/// operations.
10687 // Just recurse on the LHS.
10688 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10689
10690 // We want to recurse on the RHS as normal unless we're assigning to
10691 // a bitfield.
10692 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10693 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10694 E->getOperatorLoc())) {
10695 // Recurse, ignoring any implicit conversions on the RHS.
10696 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10697 E->getOperatorLoc());
10698 }
10699 }
10700
10701 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10702
10703 // Diagnose implicitly sequentially-consistent atomic assignment.
10704 if (E->getLHS()->getType()->isAtomicType())
10705 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10706}
10707
10708/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
10709static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10710 SourceLocation CContext, unsigned diag,
10711 bool pruneControlFlow = false) {
10712 if (pruneControlFlow) {
10714 S.PDiag(diag)
10715 << SourceType << T << E->getSourceRange()
10716 << SourceRange(CContext));
10717 return;
10718 }
10719 S.Diag(E->getExprLoc(), diag)
10720 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10721}
10722
10723/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
10725 SourceLocation CContext,
10726 unsigned diag, bool pruneControlFlow = false) {
10727 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10728}
10729
10730/// Diagnose an implicit cast from a floating point value to an integer value.
10732 SourceLocation CContext) {
10733 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10734 const bool PruneWarnings = S.inTemplateInstantiation();
10735
10736 Expr *InnerE = E->IgnoreParenImpCasts();
10737 // We also want to warn on, e.g., "int i = -1.234"
10738 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10739 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10740 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10741
10742 const bool IsLiteral =
10743 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10744
10745 llvm::APFloat Value(0.0);
10746 bool IsConstant =
10748 if (!IsConstant) {
10749 if (S.ObjC().isSignedCharBool(T)) {
10751 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
10752 << E->getType());
10753 }
10754
10755 return DiagnoseImpCast(S, E, T, CContext,
10756 diag::warn_impcast_float_integer, PruneWarnings);
10757 }
10758
10759 bool isExact = false;
10760
10761 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10763 llvm::APFloat::opStatus Result = Value.convertToInteger(
10764 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10765
10766 // FIXME: Force the precision of the source value down so we don't print
10767 // digits which are usually useless (we don't really care here if we
10768 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
10769 // would automatically print the shortest representation, but it's a bit
10770 // tricky to implement.
10771 SmallString<16> PrettySourceValue;
10772 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10773 precision = (precision * 59 + 195) / 196;
10774 Value.toString(PrettySourceValue, precision);
10775
10776 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
10778 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
10779 << PrettySourceValue);
10780 }
10781
10782 if (Result == llvm::APFloat::opOK && isExact) {
10783 if (IsLiteral) return;
10784 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10785 PruneWarnings);
10786 }
10787
10788 // Conversion of a floating-point value to a non-bool integer where the
10789 // integral part cannot be represented by the integer type is undefined.
10790 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10791 return DiagnoseImpCast(
10792 S, E, T, CContext,
10793 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
10794 : diag::warn_impcast_float_to_integer_out_of_range,
10795 PruneWarnings);
10796
10797 unsigned DiagID = 0;
10798 if (IsLiteral) {
10799 // Warn on floating point literal to integer.
10800 DiagID = diag::warn_impcast_literal_float_to_integer;
10801 } else if (IntegerValue == 0) {
10802 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
10803 return DiagnoseImpCast(S, E, T, CContext,
10804 diag::warn_impcast_float_integer, PruneWarnings);
10805 }
10806 // Warn on non-zero to zero conversion.
10807 DiagID = diag::warn_impcast_float_to_integer_zero;
10808 } else {
10809 if (IntegerValue.isUnsigned()) {
10810 if (!IntegerValue.isMaxValue()) {
10811 return DiagnoseImpCast(S, E, T, CContext,
10812 diag::warn_impcast_float_integer, PruneWarnings);
10813 }
10814 } else { // IntegerValue.isSigned()
10815 if (!IntegerValue.isMaxSignedValue() &&
10816 !IntegerValue.isMinSignedValue()) {
10817 return DiagnoseImpCast(S, E, T, CContext,
10818 diag::warn_impcast_float_integer, PruneWarnings);
10819 }
10820 }
10821 // Warn on evaluatable floating point expression to integer conversion.
10822 DiagID = diag::warn_impcast_float_to_integer;
10823 }
10824
10825 SmallString<16> PrettyTargetValue;
10826 if (IsBool)
10827 PrettyTargetValue = Value.isZero() ? "false" : "true";
10828 else
10829 IntegerValue.toString(PrettyTargetValue);
10830
10831 if (PruneWarnings) {
10833 S.PDiag(DiagID)
10834 << E->getType() << T.getUnqualifiedType()
10835 << PrettySourceValue << PrettyTargetValue
10836 << E->getSourceRange() << SourceRange(CContext));
10837 } else {
10838 S.Diag(E->getExprLoc(), DiagID)
10839 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10840 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10841 }
10842}
10843
10844/// Analyze the given compound assignment for the possible losing of
10845/// floating-point precision.
10847 assert(isa<CompoundAssignOperator>(E) &&
10848 "Must be compound assignment operation");
10849 // Recurse on the LHS and RHS in here
10850 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10851 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10852
10853 if (E->getLHS()->getType()->isAtomicType())
10854 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
10855
10856 // Now check the outermost expression
10857 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10858 const auto *RBT = cast<CompoundAssignOperator>(E)
10859 ->getComputationResultType()
10860 ->getAs<BuiltinType>();
10861
10862 // The below checks assume source is floating point.
10863 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
10864
10865 // If source is floating point but target is an integer.
10866 if (ResultBT->isInteger())
10867 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
10868 E->getExprLoc(), diag::warn_impcast_float_integer);
10869
10870 if (!ResultBT->isFloatingPoint())
10871 return;
10872
10873 // If both source and target are floating points, warn about losing precision.
10875 QualType(ResultBT, 0), QualType(RBT, 0));
10876 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
10877 // warn about dropping FP rank.
10878 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
10879 diag::warn_impcast_float_result_precision);
10880}
10881
10882static std::string PrettyPrintInRange(const llvm::APSInt &Value,
10883 IntRange Range) {
10884 if (!Range.Width) return "0";
10885
10886 llvm::APSInt ValueInRange = Value;
10887 ValueInRange.setIsSigned(!Range.NonNegative);
10888 ValueInRange = ValueInRange.trunc(Range.Width);
10889 return toString(ValueInRange, 10);
10890}
10891
10892static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
10893 if (!isa<ImplicitCastExpr>(Ex))
10894 return false;
10895
10896 Expr *InnerE = Ex->IgnoreParenImpCasts();
10898 const Type *Source =
10900 if (Target->isDependentType())
10901 return false;
10902
10903 const BuiltinType *FloatCandidateBT =
10904 dyn_cast<BuiltinType>(ToBool ? Source : Target);
10905 const Type *BoolCandidateType = ToBool ? Target : Source;
10906
10907 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
10908 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
10909}
10910
10912 SourceLocation CC) {
10913 unsigned NumArgs = TheCall->getNumArgs();
10914 for (unsigned i = 0; i < NumArgs; ++i) {
10915 Expr *CurrA = TheCall->getArg(i);
10916 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
10917 continue;
10918
10919 bool IsSwapped = ((i > 0) &&
10920 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
10921 IsSwapped |= ((i < (NumArgs - 1)) &&
10922 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
10923 if (IsSwapped) {
10924 // Warn on this floating-point to bool conversion.
10926 CurrA->getType(), CC,
10927 diag::warn_impcast_floating_point_to_bool);
10928 }
10929 }
10930}
10931
10933 SourceLocation CC) {
10934 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
10935 E->getExprLoc()))
10936 return;
10937
10938 // Don't warn on functions which have return type nullptr_t.
10939 if (isa<CallExpr>(E))
10940 return;
10941
10942 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
10943 const Expr *NewE = E->IgnoreParenImpCasts();
10944 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
10945 bool HasNullPtrType = NewE->getType()->isNullPtrType();
10946 if (!IsGNUNullExpr && !HasNullPtrType)
10947 return;
10948
10949 // Return if target type is a safe conversion.
10950 if (T->isAnyPointerType() || T->isBlockPointerType() ||
10952 return;
10953
10955
10956 // Venture through the macro stacks to get to the source of macro arguments.
10957 // The new location is a better location than the complete location that was
10958 // passed in.
10961
10962 // __null is usually wrapped in a macro. Go up a macro if that is the case.
10963 if (IsGNUNullExpr && Loc.isMacroID()) {
10964 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
10965 Loc, S.SourceMgr, S.getLangOpts());
10966 if (MacroName == "NULL")
10968 }
10969
10970 // Only warn if the null and context location are in the same macro expansion.
10971 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10972 return;
10973
10974 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
10975 << HasNullPtrType << T << SourceRange(CC)
10978}
10979
10980// Helper function to filter out cases for constant width constant conversion.
10981// Don't warn on char array initialization or for non-decimal values.
10983 SourceLocation CC) {
10984 // If initializing from a constant, and the constant starts with '0',
10985 // then it is a binary, octal, or hexadecimal. Allow these constants
10986 // to fill all the bits, even if there is a sign change.
10987 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10988 const char FirstLiteralCharacter =
10989 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
10990 if (FirstLiteralCharacter == '0')
10991 return false;
10992 }
10993
10994 // If the CC location points to a '{', and the type is char, then assume
10995 // assume it is an array initialization.
10996 if (CC.isValid() && T->isCharType()) {
10997 const char FirstContextCharacter =
10999 if (FirstContextCharacter == '{')
11000 return false;
11001 }
11002
11003 return true;
11004}
11005
11007 const auto *IL = dyn_cast<IntegerLiteral>(E);
11008 if (!IL) {
11009 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11010 if (UO->getOpcode() == UO_Minus)
11011 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11012 }
11013 }
11014
11015 return IL;
11016}
11017
11019 E = E->IgnoreParenImpCasts();
11020 SourceLocation ExprLoc = E->getExprLoc();
11021
11022 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11023 BinaryOperator::Opcode Opc = BO->getOpcode();
11025 // Do not diagnose unsigned shifts.
11026 if (Opc == BO_Shl) {
11027 const auto *LHS = getIntegerLiteral(BO->getLHS());
11028 const auto *RHS = getIntegerLiteral(BO->getRHS());
11029 if (LHS && LHS->getValue() == 0)
11030 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11031 else if (!E->isValueDependent() && LHS && RHS &&
11032 RHS->getValue().isNonNegative() &&
11034 S.Diag(ExprLoc, diag::warn_left_shift_always)
11035 << (Result.Val.getInt() != 0);
11036 else if (E->getType()->isSignedIntegerType())
11037 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11038 }
11039 }
11040
11041 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11042 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11043 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11044 if (!LHS || !RHS)
11045 return;
11046 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11047 (RHS->getValue() == 0 || RHS->getValue() == 1))
11048 // Do not diagnose common idioms.
11049 return;
11050 if (LHS->getValue() != 0 && RHS->getValue() != 0)
11051 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11052 }
11053}
11054
11056 bool *ICContext, bool IsListInit) {
11057 if (E->isTypeDependent() || E->isValueDependent()) return;
11058
11059 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
11061 if (Source == Target) return;
11062 if (Target->isDependentType()) return;
11063
11064 // If the conversion context location is invalid don't complain. We also
11065 // don't want to emit a warning if the issue occurs from the expansion of
11066 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11067 // delay this check as long as possible. Once we detect we are in that
11068 // scenario, we just return.
11069 if (CC.isInvalid())
11070 return;
11071
11072 if (Source->isAtomicType())
11073 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11074
11075 // Diagnose implicit casts to bool.
11076 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11077 if (isa<StringLiteral>(E))
11078 // Warn on string literal to bool. Checks for string literals in logical
11079 // and expressions, for instance, assert(0 && "error here"), are
11080 // prevented by a check in AnalyzeImplicitConversions().
11081 return DiagnoseImpCast(*this, E, T, CC,
11082 diag::warn_impcast_string_literal_to_bool);
11083 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11084 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11085 // This covers the literal expressions that evaluate to Objective-C
11086 // objects.
11087 return DiagnoseImpCast(*this, E, T, CC,
11088 diag::warn_impcast_objective_c_literal_to_bool);
11089 }
11090 if (Source->isPointerType() || Source->canDecayToPointerType()) {
11091 // Warn on pointer to bool conversion that is always true.
11093 SourceRange(CC));
11094 }
11095 }
11096
11097 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11098 // is a typedef for signed char (macOS), then that constant value has to be 1
11099 // or 0.
11100 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
11103 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11105 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11106 << toString(Result.Val.getInt(), 10));
11107 }
11108 return;
11109 }
11110 }
11111
11112 // Check implicit casts from Objective-C collection literals to specialized
11113 // collection types, e.g., NSArray<NSString *> *.
11114 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11115 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
11116 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11117 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
11118
11119 // Strip vector types.
11120 if (isa<VectorType>(Source)) {
11121 if (Target->isSveVLSBuiltinType() &&
11123 QualType(Source, 0)) ||
11125 QualType(Source, 0))))
11126 return;
11127
11128 if (Target->isRVVVLSBuiltinType() &&
11130 QualType(Source, 0)) ||
11132 QualType(Source, 0))))
11133 return;
11134
11135 if (!isa<VectorType>(Target)) {
11136 if (SourceMgr.isInSystemMacro(CC))
11137 return;
11138 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
11139 } else if (getLangOpts().HLSL &&
11140 Target->castAs<VectorType>()->getNumElements() <
11141 Source->castAs<VectorType>()->getNumElements()) {
11142 // Diagnose vector truncation but don't return. We may also want to
11143 // diagnose an element conversion.
11144 DiagnoseImpCast(*this, E, T, CC,
11145 diag::warn_hlsl_impcast_vector_truncation);
11146 }
11147
11148 // If the vector cast is cast between two vectors of the same size, it is
11149 // a bitcast, not a conversion, except under HLSL where it is a conversion.
11150 if (!getLangOpts().HLSL &&
11152 return;
11153
11154 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11155 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11156 }
11157 if (auto VecTy = dyn_cast<VectorType>(Target))
11158 Target = VecTy->getElementType().getTypePtr();
11159
11160 // Strip complex types.
11161 if (isa<ComplexType>(Source)) {
11162 if (!isa<ComplexType>(Target)) {
11163 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11164 return;
11165
11166 return DiagnoseImpCast(*this, E, T, CC,
11168 ? diag::err_impcast_complex_scalar
11169 : diag::warn_impcast_complex_scalar);
11170 }
11171
11172 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11173 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11174 }
11175
11176 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11177 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11178
11179 // Strip SVE vector types
11180 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
11181 // Need the original target type for vector type checks
11182 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
11183 // Handle conversion from scalable to fixed when msve-vector-bits is
11184 // specified
11185 if (Context.areCompatibleSveTypes(QualType(OriginalTarget, 0),
11186 QualType(Source, 0)) ||
11187 Context.areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
11188 QualType(Source, 0)))
11189 return;
11190
11191 // If the vector cast is cast between two vectors of the same size, it is
11192 // a bitcast, not a conversion.
11194 return;
11195
11196 Source = SourceBT->getSveEltType(Context).getTypePtr();
11197 }
11198
11199 if (TargetBT && TargetBT->isSveVLSBuiltinType())
11200 Target = TargetBT->getSveEltType(Context).getTypePtr();
11201
11202 // If the source is floating point...
11203 if (SourceBT && SourceBT->isFloatingPoint()) {
11204 // ...and the target is floating point...
11205 if (TargetBT && TargetBT->isFloatingPoint()) {
11206 // ...then warn if we're dropping FP rank.
11207
11209 QualType(SourceBT, 0), QualType(TargetBT, 0));
11210 if (Order > 0) {
11211 // Don't warn about float constants that are precisely
11212 // representable in the target type.
11213 Expr::EvalResult result;
11214 if (E->EvaluateAsRValue(result, Context)) {
11215 // Value might be a float, a float vector, or a float complex.
11217 result.Val,
11219 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11220 return;
11221 }
11222
11223 if (SourceMgr.isInSystemMacro(CC))
11224 return;
11225
11226 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
11227 }
11228 // ... or possibly if we're increasing rank, too
11229 else if (Order < 0) {
11230 if (SourceMgr.isInSystemMacro(CC))
11231 return;
11232
11233 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
11234 }
11235 return;
11236 }
11237
11238 // If the target is integral, always warn.
11239 if (TargetBT && TargetBT->isInteger()) {
11240 if (SourceMgr.isInSystemMacro(CC))
11241 return;
11242
11243 DiagnoseFloatingImpCast(*this, E, T, CC);
11244 }
11245
11246 // Detect the case where a call result is converted from floating-point to
11247 // to bool, and the final argument to the call is converted from bool, to
11248 // discover this typo:
11249 //
11250 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
11251 //
11252 // FIXME: This is an incredibly special case; is there some more general
11253 // way to detect this class of misplaced-parentheses bug?
11254 if (Target->isBooleanType() && isa<CallExpr>(E)) {
11255 // Check last argument of function call to see if it is an
11256 // implicit cast from a type matching the type the result
11257 // is being cast to.
11258 CallExpr *CEx = cast<CallExpr>(E);
11259 if (unsigned NumArgs = CEx->getNumArgs()) {
11260 Expr *LastA = CEx->getArg(NumArgs - 1);
11261 Expr *InnerE = LastA->IgnoreParenImpCasts();
11262 if (isa<ImplicitCastExpr>(LastA) &&
11263 InnerE->getType()->isBooleanType()) {
11264 // Warn on this floating-point to bool conversion
11265 DiagnoseImpCast(*this, E, T, CC,
11266 diag::warn_impcast_floating_point_to_bool);
11267 }
11268 }
11269 }
11270 return;
11271 }
11272
11273 // Valid casts involving fixed point types should be accounted for here.
11274 if (Source->isFixedPointType()) {
11275 if (Target->isUnsaturatedFixedPointType()) {
11279 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
11280 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
11281 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
11282 if (Value > MaxVal || Value < MinVal) {
11284 PDiag(diag::warn_impcast_fixed_point_range)
11285 << Value.toString() << T
11286 << E->getSourceRange()
11287 << clang::SourceRange(CC));
11288 return;
11289 }
11290 }
11291 } else if (Target->isIntegerType()) {
11295 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
11296
11297 bool Overflowed;
11298 llvm::APSInt IntResult = FXResult.convertToInt(
11299 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
11300 &Overflowed);
11301
11302 if (Overflowed) {
11304 PDiag(diag::warn_impcast_fixed_point_range)
11305 << FXResult.toString() << T
11306 << E->getSourceRange()
11307 << clang::SourceRange(CC));
11308 return;
11309 }
11310 }
11311 }
11312 } else if (Target->isUnsaturatedFixedPointType()) {
11313 if (Source->isIntegerType()) {
11317 llvm::APSInt Value = Result.Val.getInt();
11318
11319 bool Overflowed;
11320 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
11321 Value, Context.getFixedPointSemantics(T), &Overflowed);
11322
11323 if (Overflowed) {
11325 PDiag(diag::warn_impcast_fixed_point_range)
11326 << toString(Value, /*Radix=*/10) << T
11327 << E->getSourceRange()
11328 << clang::SourceRange(CC));
11329 return;
11330 }
11331 }
11332 }
11333 }
11334
11335 // If we are casting an integer type to a floating point type without
11336 // initialization-list syntax, we might lose accuracy if the floating
11337 // point type has a narrower significand than the integer type.
11338 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11339 TargetBT->isFloatingType() && !IsListInit) {
11340 // Determine the number of precision bits in the source integer type.
11341 std::optional<IntRange> SourceRange =
11343 /*Approximate=*/true);
11344 if (!SourceRange)
11345 return;
11346 unsigned int SourcePrecision = SourceRange->Width;
11347
11348 // Determine the number of precision bits in the
11349 // target floating point type.
11350 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11351 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11352
11353 if (SourcePrecision > 0 && TargetPrecision > 0 &&
11354 SourcePrecision > TargetPrecision) {
11355
11356 if (std::optional<llvm::APSInt> SourceInt =
11358 // If the source integer is a constant, convert it to the target
11359 // floating point type. Issue a warning if the value changes
11360 // during the whole conversion.
11361 llvm::APFloat TargetFloatValue(
11362 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11363 llvm::APFloat::opStatus ConversionStatus =
11364 TargetFloatValue.convertFromAPInt(
11365 *SourceInt, SourceBT->isSignedInteger(),
11366 llvm::APFloat::rmNearestTiesToEven);
11367
11368 if (ConversionStatus != llvm::APFloat::opOK) {
11369 SmallString<32> PrettySourceValue;
11370 SourceInt->toString(PrettySourceValue, 10);
11371 SmallString<32> PrettyTargetValue;
11372 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11373
11375 E->getExprLoc(), E,
11376 PDiag(diag::warn_impcast_integer_float_precision_constant)
11377 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11378 << E->getSourceRange() << clang::SourceRange(CC));
11379 }
11380 } else {
11381 // Otherwise, the implicit conversion may lose precision.
11382 DiagnoseImpCast(*this, E, T, CC,
11383 diag::warn_impcast_integer_float_precision);
11384 }
11385 }
11386 }
11387
11388 DiagnoseNullConversion(*this, E, T, CC);
11389
11391
11392 if (Target->isBooleanType())
11394
11395 if (!Source->isIntegerType() || !Target->isIntegerType())
11396 return;
11397
11398 // TODO: remove this early return once the false positives for constant->bool
11399 // in templates, macros, etc, are reduced or removed.
11400 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11401 return;
11402
11403 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
11404 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
11406 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11407 << E->getType());
11408 }
11409 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
11410 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
11411 if (!LikelySourceRange)
11412 return;
11413
11414 IntRange SourceTypeRange =
11415 IntRange::forTargetOfCanonicalType(Context, Source);
11416 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
11417
11418 if (LikelySourceRange->Width > TargetRange.Width) {
11419 // If the source is a constant, use a default-on diagnostic.
11420 // TODO: this should happen for bitfield stores, too.
11424 llvm::APSInt Value(32);
11425 Value = Result.Val.getInt();
11426
11427 if (SourceMgr.isInSystemMacro(CC))
11428 return;
11429
11430 std::string PrettySourceValue = toString(Value, 10);
11431 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11432
11434 PDiag(diag::warn_impcast_integer_precision_constant)
11435 << PrettySourceValue << PrettyTargetValue
11436 << E->getType() << T << E->getSourceRange()
11437 << SourceRange(CC));
11438 return;
11439 }
11440
11441 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11442 if (SourceMgr.isInSystemMacro(CC))
11443 return;
11444
11445 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
11446 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
11447 /* pruneControlFlow */ true);
11448 return DiagnoseImpCast(*this, E, T, CC,
11449 diag::warn_impcast_integer_precision);
11450 }
11451
11452 if (TargetRange.Width > SourceTypeRange.Width) {
11453 if (auto *UO = dyn_cast<UnaryOperator>(E))
11454 if (UO->getOpcode() == UO_Minus)
11455 if (Source->isUnsignedIntegerType()) {
11456 if (Target->isUnsignedIntegerType())
11457 return DiagnoseImpCast(*this, E, T, CC,
11458 diag::warn_impcast_high_order_zero_bits);
11459 if (Target->isSignedIntegerType())
11460 return DiagnoseImpCast(*this, E, T, CC,
11461 diag::warn_impcast_nonnegative_result);
11462 }
11463 }
11464
11465 if (TargetRange.Width == LikelySourceRange->Width &&
11466 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
11467 Source->isSignedIntegerType()) {
11468 // Warn when doing a signed to signed conversion, warn if the positive
11469 // source value is exactly the width of the target type, which will
11470 // cause a negative value to be stored.
11471
11475 llvm::APSInt Value = Result.Val.getInt();
11476 if (isSameWidthConstantConversion(*this, E, T, CC)) {
11477 std::string PrettySourceValue = toString(Value, 10);
11478 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11479
11480 Diag(E->getExprLoc(),
11481 PDiag(diag::warn_impcast_integer_precision_constant)
11482 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11483 << E->getSourceRange() << SourceRange(CC));
11484 return;
11485 }
11486 }
11487
11488 // Fall through for non-constants to give a sign conversion warning.
11489 }
11490
11491 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
11492 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
11493 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
11494 LikelySourceRange->Width == TargetRange.Width))) {
11495 if (SourceMgr.isInSystemMacro(CC))
11496 return;
11497
11498 if (SourceBT && SourceBT->isInteger() && TargetBT &&
11499 TargetBT->isInteger() &&
11500 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
11501 return;
11502 }
11503
11504 unsigned DiagID = diag::warn_impcast_integer_sign;
11505
11506 // Traditionally, gcc has warned about this under -Wsign-compare.
11507 // We also want to warn about it in -Wconversion.
11508 // So if -Wconversion is off, use a completely identical diagnostic
11509 // in the sign-compare group.
11510 // The conditional-checking code will
11511 if (ICContext) {
11512 DiagID = diag::warn_impcast_integer_sign_conditional;
11513 *ICContext = true;
11514 }
11515
11516 return DiagnoseImpCast(*this, E, T, CC, DiagID);
11517 }
11518
11519 // Diagnose conversions between different enumeration types.
11520 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11521 // type, to give us better diagnostics.
11522 QualType SourceType = E->getEnumCoercedType(Context);
11523 Source = Context.getCanonicalType(SourceType).getTypePtr();
11524
11525 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11526 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11527 if (SourceEnum->getDecl()->hasNameForLinkage() &&
11528 TargetEnum->getDecl()->hasNameForLinkage() &&
11529 SourceEnum != TargetEnum) {
11530 if (SourceMgr.isInSystemMacro(CC))
11531 return;
11532
11533 return DiagnoseImpCast(*this, E, SourceType, T, CC,
11534 diag::warn_impcast_different_enum_types);
11535 }
11536}
11537
11540
11542 SourceLocation CC, bool &ICContext) {
11543 E = E->IgnoreParenImpCasts();
11544 // Diagnose incomplete type for second or third operand in C.
11545 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
11546 S.RequireCompleteExprType(E, diag::err_incomplete_type);
11547
11548 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
11549 return CheckConditionalOperator(S, CO, CC, T);
11550
11552 if (E->getType() != T)
11553 return S.CheckImplicitConversion(E, T, CC, &ICContext);
11554}
11555
11558 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11559
11560 Expr *TrueExpr = E->getTrueExpr();
11561 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
11562 TrueExpr = BCO->getCommon();
11563
11564 bool Suspicious = false;
11565 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
11566 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11567
11568 if (T->isBooleanType())
11570
11571 // If -Wconversion would have warned about either of the candidates
11572 // for a signedness conversion to the context type...
11573 if (!Suspicious) return;
11574
11575 // ...but it's currently ignored...
11576 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11577 return;
11578
11579 // ...then check whether it would have warned about either of the
11580 // candidates for a signedness conversion to the condition type.
11581 if (E->getType() == T) return;
11582
11583 Suspicious = false;
11585 &Suspicious);
11586 if (!Suspicious)
11587 S.CheckImplicitConversion(E->getFalseExpr()->IgnoreParenImpCasts(),
11588 E->getType(), CC, &Suspicious);
11589}
11590
11591/// Check conversion of given expression to boolean.
11592/// Input argument E is a logical expression.
11594 // Run the bool-like conversion checks only for C since there bools are
11595 // still not used as the return type from "boolean" operators or as the input
11596 // type for conditional operators.
11597 if (S.getLangOpts().CPlusPlus)
11598 return;
11600 return;
11602}
11603
11604namespace {
11605struct AnalyzeImplicitConversionsWorkItem {
11606 Expr *E;
11607 SourceLocation CC;
11608 bool IsListInit;
11609};
11610}
11611
11612/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
11613/// that should be visited are added to WorkList.
11615 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
11617 Expr *OrigE = Item.E;
11618 SourceLocation CC = Item.CC;
11619
11620 QualType T = OrigE->getType();
11621 Expr *E = OrigE->IgnoreParenImpCasts();
11622
11623 // Propagate whether we are in a C++ list initialization expression.
11624 // If so, we do not issue warnings for implicit int-float conversion
11625 // precision loss, because C++11 narrowing already handles it.
11626 bool IsListInit = Item.IsListInit ||
11627 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
11628
11629 if (E->isTypeDependent() || E->isValueDependent())
11630 return;
11631
11632 Expr *SourceExpr = E;
11633 // Examine, but don't traverse into the source expression of an
11634 // OpaqueValueExpr, since it may have multiple parents and we don't want to
11635 // emit duplicate diagnostics. Its fine to examine the form or attempt to
11636 // evaluate it in the context of checking the specific conversion to T though.
11637 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11638 if (auto *Src = OVE->getSourceExpr())
11639 SourceExpr = Src;
11640
11641 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
11642 if (UO->getOpcode() == UO_Not &&
11643 UO->getSubExpr()->isKnownToHaveBooleanValue())
11644 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
11645 << OrigE->getSourceRange() << T->isBooleanType()
11646 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
11647
11648 if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
11649 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
11650 BO->getLHS()->isKnownToHaveBooleanValue() &&
11651 BO->getRHS()->isKnownToHaveBooleanValue() &&
11652 BO->getLHS()->HasSideEffects(S.Context) &&
11653 BO->getRHS()->HasSideEffects(S.Context)) {
11655 const LangOptions &LO = S.getLangOpts();
11656 SourceLocation BLoc = BO->getOperatorLoc();
11657 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
11658 StringRef SR = clang::Lexer::getSourceText(
11659 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
11660 // To reduce false positives, only issue the diagnostic if the operator
11661 // is explicitly spelled as a punctuator. This suppresses the diagnostic
11662 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
11663 // in C, along with other macro spellings the user might invent.
11664 if (SR.str() == "&" || SR.str() == "|") {
11665
11666 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
11667 << (BO->getOpcode() == BO_And ? "&" : "|")
11668 << OrigE->getSourceRange()
11670 BO->getOperatorLoc(),
11671 (BO->getOpcode() == BO_And ? "&&" : "||"));
11672 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
11673 }
11674 }
11675
11676 // For conditional operators, we analyze the arguments as if they
11677 // were being fed directly into the output.
11678 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
11679 CheckConditionalOperator(S, CO, CC, T);
11680 return;
11681 }
11682
11683 // Check implicit argument conversions for function calls.
11684 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
11686
11687 // Go ahead and check any implicit conversions we might have skipped.
11688 // The non-canonical typecheck is just an optimization;
11689 // CheckImplicitConversion will filter out dead implicit conversions.
11690 if (SourceExpr->getType() != T)
11691 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
11692
11693 // Now continue drilling into this expression.
11694
11695 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11696 // The bound subexpressions in a PseudoObjectExpr are not reachable
11697 // as transitive children.
11698 // FIXME: Use a more uniform representation for this.
11699 for (auto *SE : POE->semantics())
11700 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11701 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
11702 }
11703
11704 // Skip past explicit casts.
11705 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11706 E = CE->getSubExpr()->IgnoreParenImpCasts();
11707 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11708 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11709 WorkList.push_back({E, CC, IsListInit});
11710 return;
11711 }
11712
11713 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
11714 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
11715 // The base expression is only used to initialize the parameter for
11716 // arguments to `inout` parameters, so we only traverse down the base
11717 // expression for `inout` cases.
11718 if (OutArgE->isInOut())
11719 WorkList.push_back(
11720 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
11721 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
11722 return;
11723 }
11724
11725 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11726 // Do a somewhat different check with comparison operators.
11727 if (BO->isComparisonOp())
11728 return AnalyzeComparison(S, BO);
11729
11730 // And with simple assignments.
11731 if (BO->getOpcode() == BO_Assign)
11732 return AnalyzeAssignment(S, BO);
11733 // And with compound assignments.
11734 if (BO->isAssignmentOp())
11735 return AnalyzeCompoundAssignment(S, BO);
11736 }
11737
11738 // These break the otherwise-useful invariant below. Fortunately,
11739 // we don't really need to recurse into them, because any internal
11740 // expressions should have been analyzed already when they were
11741 // built into statements.
11742 if (isa<StmtExpr>(E)) return;
11743
11744 // Don't descend into unevaluated contexts.
11745 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11746
11747 // Now just recurse over the expression's children.
11748 CC = E->getExprLoc();
11749 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11750 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11751 for (Stmt *SubStmt : E->children()) {
11752 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11753 if (!ChildExpr)
11754 continue;
11755
11756 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
11757 if (ChildExpr == CSE->getOperand())
11758 // Do not recurse over a CoroutineSuspendExpr's operand.
11759 // The operand is also a subexpression of getCommonExpr(), and
11760 // recursing into it directly would produce duplicate diagnostics.
11761 continue;
11762
11763 if (IsLogicalAndOperator &&
11764 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11765 // Ignore checking string literals that are in logical and operators.
11766 // This is a common pattern for asserts.
11767 continue;
11768 WorkList.push_back({ChildExpr, CC, IsListInit});
11769 }
11770
11771 if (BO && BO->isLogicalOp()) {
11772 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11773 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11774 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11775
11776 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11777 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11778 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11779 }
11780
11781 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11782 if (U->getOpcode() == UO_LNot) {
11783 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11784 } else if (U->getOpcode() != UO_AddrOf) {
11785 if (U->getSubExpr()->getType()->isAtomicType())
11786 S.Diag(U->getSubExpr()->getBeginLoc(),
11787 diag::warn_atomic_implicit_seq_cst);
11788 }
11789 }
11790}
11791
11792/// AnalyzeImplicitConversions - Find and report any interesting
11793/// implicit conversions in the given expression. There are a couple
11794/// of competing diagnostics here, -Wconversion and -Wsign-compare.
11796 bool IsListInit/*= false*/) {
11798 WorkList.push_back({OrigE, CC, IsListInit});
11799 while (!WorkList.empty())
11800 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
11801}
11802
11803// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11804// Returns true when emitting a warning about taking the address of a reference.
11805static bool CheckForReference(Sema &SemaRef, const Expr *E,
11806 const PartialDiagnostic &PD) {
11807 E = E->IgnoreParenImpCasts();
11808
11809 const FunctionDecl *FD = nullptr;
11810
11811 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11812 if (!DRE->getDecl()->getType()->isReferenceType())
11813 return false;
11814 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11815 if (!M->getMemberDecl()->getType()->isReferenceType())
11816 return false;
11817 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
11818 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
11819 return false;
11820 FD = Call->getDirectCallee();
11821 } else {
11822 return false;
11823 }
11824
11825 SemaRef.Diag(E->getExprLoc(), PD);
11826
11827 // If possible, point to location of function.
11828 if (FD) {
11829 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11830 }
11831
11832 return true;
11833}
11834
11835// Returns true if the SourceLocation is expanded from any macro body.
11836// Returns false if the SourceLocation is invalid, is from not in a macro
11837// expansion, or is from expanded from a top-level macro argument.
11839 if (Loc.isInvalid())
11840 return false;
11841
11842 while (Loc.isMacroID()) {
11843 if (SM.isMacroBodyExpansion(Loc))
11844 return true;
11845 Loc = SM.getImmediateMacroCallerLoc(Loc);
11846 }
11847
11848 return false;
11849}
11850
11853 bool IsEqual, SourceRange Range) {
11854 if (!E)
11855 return;
11856
11857 // Don't warn inside macros.
11858 if (E->getExprLoc().isMacroID()) {
11860 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11862 return;
11863 }
11864 E = E->IgnoreImpCasts();
11865
11866 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
11867
11868 if (isa<CXXThisExpr>(E)) {
11869 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
11870 : diag::warn_this_bool_conversion;
11871 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11872 return;
11873 }
11874
11875 bool IsAddressOf = false;
11876
11877 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
11878 if (UO->getOpcode() != UO_AddrOf)
11879 return;
11880 IsAddressOf = true;
11881 E = UO->getSubExpr();
11882 }
11883
11884 if (IsAddressOf) {
11885 unsigned DiagID = IsCompare
11886 ? diag::warn_address_of_reference_null_compare
11887 : diag::warn_address_of_reference_bool_conversion;
11888 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11889 << IsEqual;
11890 if (CheckForReference(*this, E, PD)) {
11891 return;
11892 }
11893 }
11894
11895 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
11896 bool IsParam = isa<NonNullAttr>(NonnullAttr);
11897 std::string Str;
11898 llvm::raw_string_ostream S(Str);
11899 E->printPretty(S, nullptr, getPrintingPolicy());
11900 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
11901 : diag::warn_cast_nonnull_to_bool;
11902 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11903 << E->getSourceRange() << Range << IsEqual;
11904 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
11905 };
11906
11907 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
11908 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
11909 if (auto *Callee = Call->getDirectCallee()) {
11910 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
11911 ComplainAboutNonnullParamOrCall(A);
11912 return;
11913 }
11914 }
11915 }
11916
11917 // Complain if we are converting a lambda expression to a boolean value
11918 // outside of instantiation.
11919 if (!inTemplateInstantiation()) {
11920 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
11921 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
11922 MRecordDecl && MRecordDecl->isLambda()) {
11923 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
11924 << /*LambdaPointerConversionOperatorType=*/3
11925 << MRecordDecl->getSourceRange() << Range << IsEqual;
11926 return;
11927 }
11928 }
11929 }
11930
11931 // Expect to find a single Decl. Skip anything more complicated.
11932 ValueDecl *D = nullptr;
11933 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
11934 D = R->getDecl();
11935 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11936 D = M->getMemberDecl();
11937 }
11938
11939 // Weak Decls can be null.
11940 if (!D || D->isWeak())
11941 return;
11942
11943 // Check for parameter decl with nonnull attribute
11944 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
11945 if (getCurFunction() &&
11946 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
11947 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
11948 ComplainAboutNonnullParamOrCall(A);
11949 return;
11950 }
11951
11952 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
11953 // Skip function template not specialized yet.
11955 return;
11956 auto ParamIter = llvm::find(FD->parameters(), PV);
11957 assert(ParamIter != FD->param_end());
11958 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
11959
11960 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
11961 if (!NonNull->args_size()) {
11962 ComplainAboutNonnullParamOrCall(NonNull);
11963 return;
11964 }
11965
11966 for (const ParamIdx &ArgNo : NonNull->args()) {
11967 if (ArgNo.getASTIndex() == ParamNo) {
11968 ComplainAboutNonnullParamOrCall(NonNull);
11969 return;
11970 }
11971 }
11972 }
11973 }
11974 }
11975 }
11976
11977 QualType T = D->getType();
11978 const bool IsArray = T->isArrayType();
11979 const bool IsFunction = T->isFunctionType();
11980
11981 // Address of function is used to silence the function warning.
11982 if (IsAddressOf && IsFunction) {
11983 return;
11984 }
11985
11986 // Found nothing.
11987 if (!IsAddressOf && !IsFunction && !IsArray)
11988 return;
11989
11990 // Pretty print the expression for the diagnostic.
11991 std::string Str;
11992 llvm::raw_string_ostream S(Str);
11993 E->printPretty(S, nullptr, getPrintingPolicy());
11994
11995 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
11996 : diag::warn_impcast_pointer_to_bool;
11997 enum {
11998 AddressOf,
11999 FunctionPointer,
12000 ArrayPointer
12001 } DiagType;
12002 if (IsAddressOf)
12003 DiagType = AddressOf;
12004 else if (IsFunction)
12005 DiagType = FunctionPointer;
12006 else if (IsArray)
12007 DiagType = ArrayPointer;
12008 else
12009 llvm_unreachable("Could not determine diagnostic.");
12010 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12011 << Range << IsEqual;
12012
12013 if (!IsFunction)
12014 return;
12015
12016 // Suggest '&' to silence the function warning.
12017 Diag(E->getExprLoc(), diag::note_function_warning_silence)
12019
12020 // Check to see if '()' fixit should be emitted.
12021 QualType ReturnType;
12022 UnresolvedSet<4> NonTemplateOverloads;
12023 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12024 if (ReturnType.isNull())
12025 return;
12026
12027 if (IsCompare) {
12028 // There are two cases here. If there is null constant, the only suggest
12029 // for a pointer return type. If the null is 0, then suggest if the return
12030 // type is a pointer or an integer type.
12031 if (!ReturnType->isPointerType()) {
12032 if (NullKind == Expr::NPCK_ZeroExpression ||
12033 NullKind == Expr::NPCK_ZeroLiteral) {
12034 if (!ReturnType->isIntegerType())
12035 return;
12036 } else {
12037 return;
12038 }
12039 }
12040 } else { // !IsCompare
12041 // For function to bool, only suggest if the function pointer has bool
12042 // return type.
12043 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12044 return;
12045 }
12046 Diag(E->getExprLoc(), diag::note_function_to_function_call)
12048}
12049
12050void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12051 // Don't diagnose in unevaluated contexts.
12053 return;
12054
12055 // Don't diagnose for value- or type-dependent expressions.
12056 if (E->isTypeDependent() || E->isValueDependent())
12057 return;
12058
12059 // Check for array bounds violations in cases where the check isn't triggered
12060 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12061 // ArraySubscriptExpr is on the RHS of a variable initialization.
12062 CheckArrayAccess(E);
12063
12064 // This is not the right CC for (e.g.) a variable initialization.
12065 AnalyzeImplicitConversions(*this, E, CC);
12066}
12067
12068void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12069 ::CheckBoolLikeConversion(*this, E, CC);
12070}
12071
12072void Sema::CheckForIntOverflow (const Expr *E) {
12073 // Use a work list to deal with nested struct initializers.
12075
12076 do {
12077 const Expr *OriginalE = Exprs.pop_back_val();
12078 const Expr *E = OriginalE->IgnoreParenCasts();
12079
12080 if (isa<BinaryOperator, UnaryOperator>(E)) {
12082 continue;
12083 }
12084
12085 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
12086 Exprs.append(InitList->inits().begin(), InitList->inits().end());
12087 else if (isa<ObjCBoxedExpr>(OriginalE))
12089 else if (const auto *Call = dyn_cast<CallExpr>(E))
12090 Exprs.append(Call->arg_begin(), Call->arg_end());
12091 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
12092 Exprs.append(Message->arg_begin(), Message->arg_end());
12093 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
12094 Exprs.append(Construct->arg_begin(), Construct->arg_end());
12095 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
12096 Exprs.push_back(Temporary->getSubExpr());
12097 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
12098 Exprs.push_back(Array->getIdx());
12099 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
12100 Exprs.push_back(Compound->getInitializer());
12101 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
12102 New && New->isArray()) {
12103 if (auto ArraySize = New->getArraySize())
12104 Exprs.push_back(*ArraySize);
12105 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
12106 Exprs.push_back(MTE->getSubExpr());
12107 } while (!Exprs.empty());
12108}
12109
12110namespace {
12111
12112/// Visitor for expressions which looks for unsequenced operations on the
12113/// same object.
12114class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
12116
12117 /// A tree of sequenced regions within an expression. Two regions are
12118 /// unsequenced if one is an ancestor or a descendent of the other. When we
12119 /// finish processing an expression with sequencing, such as a comma
12120 /// expression, we fold its tree nodes into its parent, since they are
12121 /// unsequenced with respect to nodes we will visit later.
12122 class SequenceTree {
12123 struct Value {
12124 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12125 unsigned Parent : 31;
12126 LLVM_PREFERRED_TYPE(bool)
12127 unsigned Merged : 1;
12128 };
12129 SmallVector<Value, 8> Values;
12130
12131 public:
12132 /// A region within an expression which may be sequenced with respect
12133 /// to some other region.
12134 class Seq {
12135 friend class SequenceTree;
12136
12137 unsigned Index;
12138
12139 explicit Seq(unsigned N) : Index(N) {}
12140
12141 public:
12142 Seq() : Index(0) {}
12143 };
12144
12145 SequenceTree() { Values.push_back(Value(0)); }
12146 Seq root() const { return Seq(0); }
12147
12148 /// Create a new sequence of operations, which is an unsequenced
12149 /// subset of \p Parent. This sequence of operations is sequenced with
12150 /// respect to other children of \p Parent.
12151 Seq allocate(Seq Parent) {
12152 Values.push_back(Value(Parent.Index));
12153 return Seq(Values.size() - 1);
12154 }
12155
12156 /// Merge a sequence of operations into its parent.
12157 void merge(Seq S) {
12158 Values[S.Index].Merged = true;
12159 }
12160
12161 /// Determine whether two operations are unsequenced. This operation
12162 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12163 /// should have been merged into its parent as appropriate.
12164 bool isUnsequenced(Seq Cur, Seq Old) {
12165 unsigned C = representative(Cur.Index);
12166 unsigned Target = representative(Old.Index);
12167 while (C >= Target) {
12168 if (C == Target)
12169 return true;
12170 C = Values[C].Parent;
12171 }
12172 return false;
12173 }
12174
12175 private:
12176 /// Pick a representative for a sequence.
12177 unsigned representative(unsigned K) {
12178 if (Values[K].Merged)
12179 // Perform path compression as we go.
12180 return Values[K].Parent = representative(Values[K].Parent);
12181 return K;
12182 }
12183 };
12184
12185 /// An object for which we can track unsequenced uses.
12186 using Object = const NamedDecl *;
12187
12188 /// Different flavors of object usage which we track. We only track the
12189 /// least-sequenced usage of each kind.
12190 enum UsageKind {
12191 /// A read of an object. Multiple unsequenced reads are OK.
12192 UK_Use,
12193
12194 /// A modification of an object which is sequenced before the value
12195 /// computation of the expression, such as ++n in C++.
12196 UK_ModAsValue,
12197
12198 /// A modification of an object which is not sequenced before the value
12199 /// computation of the expression, such as n++.
12200 UK_ModAsSideEffect,
12201
12202 UK_Count = UK_ModAsSideEffect + 1
12203 };
12204
12205 /// Bundle together a sequencing region and the expression corresponding
12206 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
12207 struct Usage {
12208 const Expr *UsageExpr = nullptr;
12209 SequenceTree::Seq Seq;
12210
12211 Usage() = default;
12212 };
12213
12214 struct UsageInfo {
12215 Usage Uses[UK_Count];
12216
12217 /// Have we issued a diagnostic for this object already?
12218 bool Diagnosed = false;
12219
12220 UsageInfo();
12221 };
12222 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12223
12224 Sema &SemaRef;
12225
12226 /// Sequenced regions within the expression.
12227 SequenceTree Tree;
12228
12229 /// Declaration modifications and references which we have seen.
12230 UsageInfoMap UsageMap;
12231
12232 /// The region we are currently within.
12233 SequenceTree::Seq Region;
12234
12235 /// Filled in with declarations which were modified as a side-effect
12236 /// (that is, post-increment operations).
12237 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12238
12239 /// Expressions to check later. We defer checking these to reduce
12240 /// stack usage.
12242
12243 /// RAII object wrapping the visitation of a sequenced subexpression of an
12244 /// expression. At the end of this process, the side-effects of the evaluation
12245 /// become sequenced with respect to the value computation of the result, so
12246 /// we downgrade any UK_ModAsSideEffect within the evaluation to
12247 /// UK_ModAsValue.
12248 struct SequencedSubexpression {
12249 SequencedSubexpression(SequenceChecker &Self)
12250 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12251 Self.ModAsSideEffect = &ModAsSideEffect;
12252 }
12253
12254 ~SequencedSubexpression() {
12255 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
12256 // Add a new usage with usage kind UK_ModAsValue, and then restore
12257 // the previous usage with UK_ModAsSideEffect (thus clearing it if
12258 // the previous one was empty).
12259 UsageInfo &UI = Self.UsageMap[M.first];
12260 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
12261 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
12262 SideEffectUsage = M.second;
12263 }
12264 Self.ModAsSideEffect = OldModAsSideEffect;
12265 }
12266
12267 SequenceChecker &Self;
12268 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12269 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12270 };
12271
12272 /// RAII object wrapping the visitation of a subexpression which we might
12273 /// choose to evaluate as a constant. If any subexpression is evaluated and
12274 /// found to be non-constant, this allows us to suppress the evaluation of
12275 /// the outer expression.
12276 class EvaluationTracker {
12277 public:
12278 EvaluationTracker(SequenceChecker &Self)
12279 : Self(Self), Prev(Self.EvalTracker) {
12280 Self.EvalTracker = this;
12281 }
12282
12283 ~EvaluationTracker() {
12284 Self.EvalTracker = Prev;
12285 if (Prev)
12286 Prev->EvalOK &= EvalOK;
12287 }
12288
12289 bool evaluate(const Expr *E, bool &Result) {
12290 if (!EvalOK || E->isValueDependent())
12291 return false;
12292 EvalOK = E->EvaluateAsBooleanCondition(
12293 Result, Self.SemaRef.Context,
12294 Self.SemaRef.isConstantEvaluatedContext());
12295 return EvalOK;
12296 }
12297
12298 private:
12299 SequenceChecker &Self;
12300 EvaluationTracker *Prev;
12301 bool EvalOK = true;
12302 } *EvalTracker = nullptr;
12303
12304 /// Find the object which is produced by the specified expression,
12305 /// if any.
12306 Object getObject(const Expr *E, bool Mod) const {
12307 E = E->IgnoreParenCasts();
12308 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12309 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12310 return getObject(UO->getSubExpr(), Mod);
12311 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12312 if (BO->getOpcode() == BO_Comma)
12313 return getObject(BO->getRHS(), Mod);
12314 if (Mod && BO->isAssignmentOp())
12315 return getObject(BO->getLHS(), Mod);
12316 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12317 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12318 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12319 return ME->getMemberDecl();
12320 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12321 // FIXME: If this is a reference, map through to its value.
12322 return DRE->getDecl();
12323 return nullptr;
12324 }
12325
12326 /// Note that an object \p O was modified or used by an expression
12327 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
12328 /// the object \p O as obtained via the \p UsageMap.
12329 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
12330 // Get the old usage for the given object and usage kind.
12331 Usage &U = UI.Uses[UK];
12332 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
12333 // If we have a modification as side effect and are in a sequenced
12334 // subexpression, save the old Usage so that we can restore it later
12335 // in SequencedSubexpression::~SequencedSubexpression.
12336 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12337 ModAsSideEffect->push_back(std::make_pair(O, U));
12338 // Then record the new usage with the current sequencing region.
12339 U.UsageExpr = UsageExpr;
12340 U.Seq = Region;
12341 }
12342 }
12343
12344 /// Check whether a modification or use of an object \p O in an expression
12345 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
12346 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
12347 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
12348 /// usage and false we are checking for a mod-use unsequenced usage.
12349 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
12350 UsageKind OtherKind, bool IsModMod) {
12351 if (UI.Diagnosed)
12352 return;
12353
12354 const Usage &U = UI.Uses[OtherKind];
12355 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
12356 return;
12357
12358 const Expr *Mod = U.UsageExpr;
12359 const Expr *ModOrUse = UsageExpr;
12360 if (OtherKind == UK_Use)
12361 std::swap(Mod, ModOrUse);
12362
12363 SemaRef.DiagRuntimeBehavior(
12364 Mod->getExprLoc(), {Mod, ModOrUse},
12365 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12366 : diag::warn_unsequenced_mod_use)
12367 << O << SourceRange(ModOrUse->getExprLoc()));
12368 UI.Diagnosed = true;
12369 }
12370
12371 // A note on note{Pre, Post}{Use, Mod}:
12372 //
12373 // (It helps to follow the algorithm with an expression such as
12374 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
12375 // operations before C++17 and both are well-defined in C++17).
12376 //
12377 // When visiting a node which uses/modify an object we first call notePreUse
12378 // or notePreMod before visiting its sub-expression(s). At this point the
12379 // children of the current node have not yet been visited and so the eventual
12380 // uses/modifications resulting from the children of the current node have not
12381 // been recorded yet.
12382 //
12383 // We then visit the children of the current node. After that notePostUse or
12384 // notePostMod is called. These will 1) detect an unsequenced modification
12385 // as side effect (as in "k++ + k") and 2) add a new usage with the
12386 // appropriate usage kind.
12387 //
12388 // We also have to be careful that some operation sequences modification as
12389 // side effect as well (for example: || or ,). To account for this we wrap
12390 // the visitation of such a sub-expression (for example: the LHS of || or ,)
12391 // with SequencedSubexpression. SequencedSubexpression is an RAII object
12392 // which record usages which are modifications as side effect, and then
12393 // downgrade them (or more accurately restore the previous usage which was a
12394 // modification as side effect) when exiting the scope of the sequenced
12395 // subexpression.
12396
12397 void notePreUse(Object O, const Expr *UseExpr) {
12398 UsageInfo &UI = UsageMap[O];
12399 // Uses conflict with other modifications.
12400 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
12401 }
12402
12403 void notePostUse(Object O, const Expr *UseExpr) {
12404 UsageInfo &UI = UsageMap[O];
12405 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
12406 /*IsModMod=*/false);
12407 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
12408 }
12409
12410 void notePreMod(Object O, const Expr *ModExpr) {
12411 UsageInfo &UI = UsageMap[O];
12412 // Modifications conflict with other modifications and with uses.
12413 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
12414 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
12415 }
12416
12417 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
12418 UsageInfo &UI = UsageMap[O];
12419 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
12420 /*IsModMod=*/true);
12421 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
12422 }
12423
12424public:
12425 SequenceChecker(Sema &S, const Expr *E,
12427 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12428 Visit(E);
12429 // Silence a -Wunused-private-field since WorkList is now unused.
12430 // TODO: Evaluate if it can be used, and if not remove it.
12431 (void)this->WorkList;
12432 }
12433
12434 void VisitStmt(const Stmt *S) {
12435 // Skip all statements which aren't expressions for now.
12436 }
12437
12438 void VisitExpr(const Expr *E) {
12439 // By default, just recurse to evaluated subexpressions.
12440 Base::VisitStmt(E);
12441 }
12442
12443 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
12444 for (auto *Sub : CSE->children()) {
12445 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
12446 if (!ChildExpr)
12447 continue;
12448
12449 if (ChildExpr == CSE->getOperand())
12450 // Do not recurse over a CoroutineSuspendExpr's operand.
12451 // The operand is also a subexpression of getCommonExpr(), and
12452 // recursing into it directly could confuse object management
12453 // for the sake of sequence tracking.
12454 continue;
12455
12456 Visit(Sub);
12457 }
12458 }
12459
12460 void VisitCastExpr(const CastExpr *E) {
12461 Object O = Object();
12462 if (E->getCastKind() == CK_LValueToRValue)
12463 O = getObject(E->getSubExpr(), false);
12464
12465 if (O)
12466 notePreUse(O, E);
12467 VisitExpr(E);
12468 if (O)
12469 notePostUse(O, E);
12470 }
12471
12472 void VisitSequencedExpressions(const Expr *SequencedBefore,
12473 const Expr *SequencedAfter) {
12474 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12475 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12476 SequenceTree::Seq OldRegion = Region;
12477
12478 {
12479 SequencedSubexpression SeqBefore(*this);
12480 Region = BeforeRegion;
12481 Visit(SequencedBefore);
12482 }
12483
12484 Region = AfterRegion;
12485 Visit(SequencedAfter);
12486
12487 Region = OldRegion;
12488
12489 Tree.merge(BeforeRegion);
12490 Tree.merge(AfterRegion);
12491 }
12492
12493 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
12494 // C++17 [expr.sub]p1:
12495 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12496 // expression E1 is sequenced before the expression E2.
12497 if (SemaRef.getLangOpts().CPlusPlus17)
12498 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12499 else {
12500 Visit(ASE->getLHS());
12501 Visit(ASE->getRHS());
12502 }
12503 }
12504
12505 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12506 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12507 void VisitBinPtrMem(const BinaryOperator *BO) {
12508 // C++17 [expr.mptr.oper]p4:
12509 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
12510 // the expression E1 is sequenced before the expression E2.
12511 if (SemaRef.getLangOpts().CPlusPlus17)
12512 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12513 else {
12514 Visit(BO->getLHS());
12515 Visit(BO->getRHS());
12516 }
12517 }
12518
12519 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12520 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12521 void VisitBinShlShr(const BinaryOperator *BO) {
12522 // C++17 [expr.shift]p4:
12523 // The expression E1 is sequenced before the expression E2.
12524 if (SemaRef.getLangOpts().CPlusPlus17)
12525 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12526 else {
12527 Visit(BO->getLHS());
12528 Visit(BO->getRHS());
12529 }
12530 }
12531
12532 void VisitBinComma(const BinaryOperator *BO) {
12533 // C++11 [expr.comma]p1:
12534 // Every value computation and side effect associated with the left
12535 // expression is sequenced before every value computation and side
12536 // effect associated with the right expression.
12537 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12538 }
12539
12540 void VisitBinAssign(const BinaryOperator *BO) {
12541 SequenceTree::Seq RHSRegion;
12542 SequenceTree::Seq LHSRegion;
12543 if (SemaRef.getLangOpts().CPlusPlus17) {
12544 RHSRegion = Tree.allocate(Region);
12545 LHSRegion = Tree.allocate(Region);
12546 } else {
12547 RHSRegion = Region;
12548 LHSRegion = Region;
12549 }
12550 SequenceTree::Seq OldRegion = Region;
12551
12552 // C++11 [expr.ass]p1:
12553 // [...] the assignment is sequenced after the value computation
12554 // of the right and left operands, [...]
12555 //
12556 // so check it before inspecting the operands and update the
12557 // map afterwards.
12558 Object O = getObject(BO->getLHS(), /*Mod=*/true);
12559 if (O)
12560 notePreMod(O, BO);
12561
12562 if (SemaRef.getLangOpts().CPlusPlus17) {
12563 // C++17 [expr.ass]p1:
12564 // [...] The right operand is sequenced before the left operand. [...]
12565 {
12566 SequencedSubexpression SeqBefore(*this);
12567 Region = RHSRegion;
12568 Visit(BO->getRHS());
12569 }
12570
12571 Region = LHSRegion;
12572 Visit(BO->getLHS());
12573
12574 if (O && isa<CompoundAssignOperator>(BO))
12575 notePostUse(O, BO);
12576
12577 } else {
12578 // C++11 does not specify any sequencing between the LHS and RHS.
12579 Region = LHSRegion;
12580 Visit(BO->getLHS());
12581
12582 if (O && isa<CompoundAssignOperator>(BO))
12583 notePostUse(O, BO);
12584
12585 Region = RHSRegion;
12586 Visit(BO->getRHS());
12587 }
12588
12589 // C++11 [expr.ass]p1:
12590 // the assignment is sequenced [...] before the value computation of the
12591 // assignment expression.
12592 // C11 6.5.16/3 has no such rule.
12593 Region = OldRegion;
12594 if (O)
12595 notePostMod(O, BO,
12596 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12597 : UK_ModAsSideEffect);
12598 if (SemaRef.getLangOpts().CPlusPlus17) {
12599 Tree.merge(RHSRegion);
12600 Tree.merge(LHSRegion);
12601 }
12602 }
12603
12604 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
12605 VisitBinAssign(CAO);
12606 }
12607
12608 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12609 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12610 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
12611 Object O = getObject(UO->getSubExpr(), true);
12612 if (!O)
12613 return VisitExpr(UO);
12614
12615 notePreMod(O, UO);
12616 Visit(UO->getSubExpr());
12617 // C++11 [expr.pre.incr]p1:
12618 // the expression ++x is equivalent to x+=1
12619 notePostMod(O, UO,
12620 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12621 : UK_ModAsSideEffect);
12622 }
12623
12624 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12625 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12626 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
12627 Object O = getObject(UO->getSubExpr(), true);
12628 if (!O)
12629 return VisitExpr(UO);
12630
12631 notePreMod(O, UO);
12632 Visit(UO->getSubExpr());
12633 notePostMod(O, UO, UK_ModAsSideEffect);
12634 }
12635
12636 void VisitBinLOr(const BinaryOperator *BO) {
12637 // C++11 [expr.log.or]p2:
12638 // If the second expression is evaluated, every value computation and
12639 // side effect associated with the first expression is sequenced before
12640 // every value computation and side effect associated with the
12641 // second expression.
12642 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12643 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12644 SequenceTree::Seq OldRegion = Region;
12645
12646 EvaluationTracker Eval(*this);
12647 {
12648 SequencedSubexpression Sequenced(*this);
12649 Region = LHSRegion;
12650 Visit(BO->getLHS());
12651 }
12652
12653 // C++11 [expr.log.or]p1:
12654 // [...] the second operand is not evaluated if the first operand
12655 // evaluates to true.
12656 bool EvalResult = false;
12657 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12658 bool ShouldVisitRHS = !EvalOK || !EvalResult;
12659 if (ShouldVisitRHS) {
12660 Region = RHSRegion;
12661 Visit(BO->getRHS());
12662 }
12663
12664 Region = OldRegion;
12665 Tree.merge(LHSRegion);
12666 Tree.merge(RHSRegion);
12667 }
12668
12669 void VisitBinLAnd(const BinaryOperator *BO) {
12670 // C++11 [expr.log.and]p2:
12671 // If the second expression is evaluated, every value computation and
12672 // side effect associated with the first expression is sequenced before
12673 // every value computation and side effect associated with the
12674 // second expression.
12675 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12676 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12677 SequenceTree::Seq OldRegion = Region;
12678
12679 EvaluationTracker Eval(*this);
12680 {
12681 SequencedSubexpression Sequenced(*this);
12682 Region = LHSRegion;
12683 Visit(BO->getLHS());
12684 }
12685
12686 // C++11 [expr.log.and]p1:
12687 // [...] the second operand is not evaluated if the first operand is false.
12688 bool EvalResult = false;
12689 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12690 bool ShouldVisitRHS = !EvalOK || EvalResult;
12691 if (ShouldVisitRHS) {
12692 Region = RHSRegion;
12693 Visit(BO->getRHS());
12694 }
12695
12696 Region = OldRegion;
12697 Tree.merge(LHSRegion);
12698 Tree.merge(RHSRegion);
12699 }
12700
12701 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
12702 // C++11 [expr.cond]p1:
12703 // [...] Every value computation and side effect associated with the first
12704 // expression is sequenced before every value computation and side effect
12705 // associated with the second or third expression.
12706 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
12707
12708 // No sequencing is specified between the true and false expression.
12709 // However since exactly one of both is going to be evaluated we can
12710 // consider them to be sequenced. This is needed to avoid warning on
12711 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
12712 // both the true and false expressions because we can't evaluate x.
12713 // This will still allow us to detect an expression like (pre C++17)
12714 // "(x ? y += 1 : y += 2) = y".
12715 //
12716 // We don't wrap the visitation of the true and false expression with
12717 // SequencedSubexpression because we don't want to downgrade modifications
12718 // as side effect in the true and false expressions after the visition
12719 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
12720 // not warn between the two "y++", but we should warn between the "y++"
12721 // and the "y".
12722 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
12723 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
12724 SequenceTree::Seq OldRegion = Region;
12725
12726 EvaluationTracker Eval(*this);
12727 {
12728 SequencedSubexpression Sequenced(*this);
12729 Region = ConditionRegion;
12730 Visit(CO->getCond());
12731 }
12732
12733 // C++11 [expr.cond]p1:
12734 // [...] The first expression is contextually converted to bool (Clause 4).
12735 // It is evaluated and if it is true, the result of the conditional
12736 // expression is the value of the second expression, otherwise that of the
12737 // third expression. Only one of the second and third expressions is
12738 // evaluated. [...]
12739 bool EvalResult = false;
12740 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
12741 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
12742 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
12743 if (ShouldVisitTrueExpr) {
12744 Region = TrueRegion;
12745 Visit(CO->getTrueExpr());
12746 }
12747 if (ShouldVisitFalseExpr) {
12748 Region = FalseRegion;
12749 Visit(CO->getFalseExpr());
12750 }
12751
12752 Region = OldRegion;
12753 Tree.merge(ConditionRegion);
12754 Tree.merge(TrueRegion);
12755 Tree.merge(FalseRegion);
12756 }
12757
12758 void VisitCallExpr(const CallExpr *CE) {
12759 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12760
12761 if (CE->isUnevaluatedBuiltinCall(Context))
12762 return;
12763
12764 // C++11 [intro.execution]p15:
12765 // When calling a function [...], every value computation and side effect
12766 // associated with any argument expression, or with the postfix expression
12767 // designating the called function, is sequenced before execution of every
12768 // expression or statement in the body of the function [and thus before
12769 // the value computation of its result].
12770 SequencedSubexpression Sequenced(*this);
12771 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
12772 // C++17 [expr.call]p5
12773 // The postfix-expression is sequenced before each expression in the
12774 // expression-list and any default argument. [...]
12775 SequenceTree::Seq CalleeRegion;
12776 SequenceTree::Seq OtherRegion;
12777 if (SemaRef.getLangOpts().CPlusPlus17) {
12778 CalleeRegion = Tree.allocate(Region);
12779 OtherRegion = Tree.allocate(Region);
12780 } else {
12781 CalleeRegion = Region;
12782 OtherRegion = Region;
12783 }
12784 SequenceTree::Seq OldRegion = Region;
12785
12786 // Visit the callee expression first.
12787 Region = CalleeRegion;
12788 if (SemaRef.getLangOpts().CPlusPlus17) {
12789 SequencedSubexpression Sequenced(*this);
12790 Visit(CE->getCallee());
12791 } else {
12792 Visit(CE->getCallee());
12793 }
12794
12795 // Then visit the argument expressions.
12796 Region = OtherRegion;
12797 for (const Expr *Argument : CE->arguments())
12798 Visit(Argument);
12799
12800 Region = OldRegion;
12801 if (SemaRef.getLangOpts().CPlusPlus17) {
12802 Tree.merge(CalleeRegion);
12803 Tree.merge(OtherRegion);
12804 }
12805 });
12806 }
12807
12808 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
12809 // C++17 [over.match.oper]p2:
12810 // [...] the operator notation is first transformed to the equivalent
12811 // function-call notation as summarized in Table 12 (where @ denotes one
12812 // of the operators covered in the specified subclause). However, the
12813 // operands are sequenced in the order prescribed for the built-in
12814 // operator (Clause 8).
12815 //
12816 // From the above only overloaded binary operators and overloaded call
12817 // operators have sequencing rules in C++17 that we need to handle
12818 // separately.
12819 if (!SemaRef.getLangOpts().CPlusPlus17 ||
12820 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
12821 return VisitCallExpr(CXXOCE);
12822
12823 enum {
12824 NoSequencing,
12825 LHSBeforeRHS,
12826 RHSBeforeLHS,
12827 LHSBeforeRest
12828 } SequencingKind;
12829 switch (CXXOCE->getOperator()) {
12830 case OO_Equal:
12831 case OO_PlusEqual:
12832 case OO_MinusEqual:
12833 case OO_StarEqual:
12834 case OO_SlashEqual:
12835 case OO_PercentEqual:
12836 case OO_CaretEqual:
12837 case OO_AmpEqual:
12838 case OO_PipeEqual:
12839 case OO_LessLessEqual:
12840 case OO_GreaterGreaterEqual:
12841 SequencingKind = RHSBeforeLHS;
12842 break;
12843
12844 case OO_LessLess:
12845 case OO_GreaterGreater:
12846 case OO_AmpAmp:
12847 case OO_PipePipe:
12848 case OO_Comma:
12849 case OO_ArrowStar:
12850 case OO_Subscript:
12851 SequencingKind = LHSBeforeRHS;
12852 break;
12853
12854 case OO_Call:
12855 SequencingKind = LHSBeforeRest;
12856 break;
12857
12858 default:
12859 SequencingKind = NoSequencing;
12860 break;
12861 }
12862
12863 if (SequencingKind == NoSequencing)
12864 return VisitCallExpr(CXXOCE);
12865
12866 // This is a call, so all subexpressions are sequenced before the result.
12867 SequencedSubexpression Sequenced(*this);
12868
12869 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
12870 assert(SemaRef.getLangOpts().CPlusPlus17 &&
12871 "Should only get there with C++17 and above!");
12872 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
12873 "Should only get there with an overloaded binary operator"
12874 " or an overloaded call operator!");
12875
12876 if (SequencingKind == LHSBeforeRest) {
12877 assert(CXXOCE->getOperator() == OO_Call &&
12878 "We should only have an overloaded call operator here!");
12879
12880 // This is very similar to VisitCallExpr, except that we only have the
12881 // C++17 case. The postfix-expression is the first argument of the
12882 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
12883 // are in the following arguments.
12884 //
12885 // Note that we intentionally do not visit the callee expression since
12886 // it is just a decayed reference to a function.
12887 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
12888 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
12889 SequenceTree::Seq OldRegion = Region;
12890
12891 assert(CXXOCE->getNumArgs() >= 1 &&
12892 "An overloaded call operator must have at least one argument"
12893 " for the postfix-expression!");
12894 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
12895 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
12896 CXXOCE->getNumArgs() - 1);
12897
12898 // Visit the postfix-expression first.
12899 {
12900 Region = PostfixExprRegion;
12901 SequencedSubexpression Sequenced(*this);
12902 Visit(PostfixExpr);
12903 }
12904
12905 // Then visit the argument expressions.
12906 Region = ArgsRegion;
12907 for (const Expr *Arg : Args)
12908 Visit(Arg);
12909
12910 Region = OldRegion;
12911 Tree.merge(PostfixExprRegion);
12912 Tree.merge(ArgsRegion);
12913 } else {
12914 assert(CXXOCE->getNumArgs() == 2 &&
12915 "Should only have two arguments here!");
12916 assert((SequencingKind == LHSBeforeRHS ||
12917 SequencingKind == RHSBeforeLHS) &&
12918 "Unexpected sequencing kind!");
12919
12920 // We do not visit the callee expression since it is just a decayed
12921 // reference to a function.
12922 const Expr *E1 = CXXOCE->getArg(0);
12923 const Expr *E2 = CXXOCE->getArg(1);
12924 if (SequencingKind == RHSBeforeLHS)
12925 std::swap(E1, E2);
12926
12927 return VisitSequencedExpressions(E1, E2);
12928 }
12929 });
12930 }
12931
12932 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
12933 // This is a call, so all subexpressions are sequenced before the result.
12934 SequencedSubexpression Sequenced(*this);
12935
12936 if (!CCE->isListInitialization())
12937 return VisitExpr(CCE);
12938
12939 // In C++11, list initializations are sequenced.
12940 SequenceExpressionsInOrder(
12941 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
12942 }
12943
12944 void VisitInitListExpr(const InitListExpr *ILE) {
12945 if (!SemaRef.getLangOpts().CPlusPlus11)
12946 return VisitExpr(ILE);
12947
12948 // In C++11, list initializations are sequenced.
12949 SequenceExpressionsInOrder(ILE->inits());
12950 }
12951
12952 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
12953 // C++20 parenthesized list initializations are sequenced. See C++20
12954 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
12955 SequenceExpressionsInOrder(PLIE->getInitExprs());
12956 }
12957
12958private:
12959 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
12961 SequenceTree::Seq Parent = Region;
12962 for (const Expr *E : ExpressionList) {
12963 if (!E)
12964 continue;
12965 Region = Tree.allocate(Parent);
12966 Elts.push_back(Region);
12967 Visit(E);
12968 }
12969
12970 // Forget that the initializers are sequenced.
12971 Region = Parent;
12972 for (unsigned I = 0; I < Elts.size(); ++I)
12973 Tree.merge(Elts[I]);
12974 }
12975};
12976
12977SequenceChecker::UsageInfo::UsageInfo() = default;
12978
12979} // namespace
12980
12981void Sema::CheckUnsequencedOperations(const Expr *E) {
12983 WorkList.push_back(E);
12984 while (!WorkList.empty()) {
12985 const Expr *Item = WorkList.pop_back_val();
12986 SequenceChecker(*this, Item, WorkList);
12987 }
12988}
12989
12990void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12991 bool IsConstexpr) {
12993 IsConstexpr || isa<ConstantExpr>(E));
12994 CheckImplicitConversions(E, CheckLoc);
12996 CheckUnsequencedOperations(E);
12997 if (!IsConstexpr && !E->isValueDependent())
12998 CheckForIntOverflow(E);
13000}
13001
13002void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13003 FieldDecl *BitField,
13004 Expr *Init) {
13005 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13006}
13007
13010 if (!PType->isVariablyModifiedType())
13011 return;
13012 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13013 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13014 return;
13015 }
13016 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13017 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13018 return;
13019 }
13020 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13021 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13022 return;
13023 }
13024
13025 const ArrayType *AT = S.Context.getAsArrayType(PType);
13026 if (!AT)
13027 return;
13028
13031 return;
13032 }
13033
13034 S.Diag(Loc, diag::err_array_star_in_function_definition);
13035}
13036
13038 bool CheckParameterNames) {
13039 bool HasInvalidParm = false;
13040 for (ParmVarDecl *Param : Parameters) {
13041 assert(Param && "null in a parameter list");
13042 // C99 6.7.5.3p4: the parameters in a parameter type list in a
13043 // function declarator that is part of a function definition of
13044 // that function shall not have incomplete type.
13045 //
13046 // C++23 [dcl.fct.def.general]/p2
13047 // The type of a parameter [...] for a function definition
13048 // shall not be a (possibly cv-qualified) class type that is incomplete
13049 // or abstract within the function body unless the function is deleted.
13050 if (!Param->isInvalidDecl() &&
13051 (RequireCompleteType(Param->getLocation(), Param->getType(),
13052 diag::err_typecheck_decl_incomplete_type) ||
13053 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
13054 diag::err_abstract_type_in_decl,
13056 Param->setInvalidDecl();
13057 HasInvalidParm = true;
13058 }
13059
13060 // C99 6.9.1p5: If the declarator includes a parameter type list, the
13061 // declaration of each parameter shall include an identifier.
13062 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
13063 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
13064 // Diagnose this as an extension in C17 and earlier.
13065 if (!getLangOpts().C23)
13066 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
13067 }
13068
13069 // C99 6.7.5.3p12:
13070 // If the function declarator is not part of a definition of that
13071 // function, parameters may have incomplete type and may use the [*]
13072 // notation in their sequences of declarator specifiers to specify
13073 // variable length array types.
13074 QualType PType = Param->getOriginalType();
13075 // FIXME: This diagnostic should point the '[*]' if source-location
13076 // information is added for it.
13077 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13078
13079 // If the parameter is a c++ class type and it has to be destructed in the
13080 // callee function, declare the destructor so that it can be called by the
13081 // callee function. Do not perform any direct access check on the dtor here.
13082 if (!Param->isInvalidDecl()) {
13083 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13084 if (!ClassDecl->isInvalidDecl() &&
13085 !ClassDecl->hasIrrelevantDestructor() &&
13086 !ClassDecl->isDependentContext() &&
13087 ClassDecl->isParamDestroyedInCallee()) {
13089 MarkFunctionReferenced(Param->getLocation(), Destructor);
13090 DiagnoseUseOfDecl(Destructor, Param->getLocation());
13091 }
13092 }
13093 }
13094
13095 // Parameters with the pass_object_size attribute only need to be marked
13096 // constant at function definitions. Because we lack information about
13097 // whether we're on a declaration or definition when we're instantiating the
13098 // attribute, we need to check for constness here.
13099 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13100 if (!Param->getType().isConstQualified())
13101 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13102 << Attr->getSpelling() << 1;
13103
13104 // Check for parameter names shadowing fields from the class.
13105 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13106 // The owning context for the parameter should be the function, but we
13107 // want to see if this function's declaration context is a record.
13108 DeclContext *DC = Param->getDeclContext();
13109 if (DC && DC->isFunctionOrMethod()) {
13110 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13111 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13112 RD, /*DeclIsField*/ false);
13113 }
13114 }
13115
13116 if (!Param->isInvalidDecl() &&
13117 Param->getOriginalType()->isWebAssemblyTableType()) {
13118 Param->setInvalidDecl();
13119 HasInvalidParm = true;
13120 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
13121 }
13122 }
13123
13124 return HasInvalidParm;
13125}
13126
13127std::optional<std::pair<
13129 *E,
13131 &Ctx);
13132
13133/// Compute the alignment and offset of the base class object given the
13134/// derived-to-base cast expression and the alignment and offset of the derived
13135/// class object.
13136static std::pair<CharUnits, CharUnits>
13138 CharUnits BaseAlignment, CharUnits Offset,
13139 ASTContext &Ctx) {
13140 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
13141 ++PathI) {
13142 const CXXBaseSpecifier *Base = *PathI;
13143 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
13144 if (Base->isVirtual()) {
13145 // The complete object may have a lower alignment than the non-virtual
13146 // alignment of the base, in which case the base may be misaligned. Choose
13147 // the smaller of the non-virtual alignment and BaseAlignment, which is a
13148 // conservative lower bound of the complete object alignment.
13149 CharUnits NonVirtualAlignment =
13151 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
13152 Offset = CharUnits::Zero();
13153 } else {
13154 const ASTRecordLayout &RL =
13155 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
13156 Offset += RL.getBaseClassOffset(BaseDecl);
13157 }
13158 DerivedType = Base->getType();
13159 }
13160
13161 return std::make_pair(BaseAlignment, Offset);
13162}
13163
13164/// Compute the alignment and offset of a binary additive operator.
13165static std::optional<std::pair<CharUnits, CharUnits>>
13167 bool IsSub, ASTContext &Ctx) {
13168 QualType PointeeType = PtrE->getType()->getPointeeType();
13169
13170 if (!PointeeType->isConstantSizeType())
13171 return std::nullopt;
13172
13173 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
13174
13175 if (!P)
13176 return std::nullopt;
13177
13178 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
13179 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
13180 CharUnits Offset = EltSize * IdxRes->getExtValue();
13181 if (IsSub)
13182 Offset = -Offset;
13183 return std::make_pair(P->first, P->second + Offset);
13184 }
13185
13186 // If the integer expression isn't a constant expression, compute the lower
13187 // bound of the alignment using the alignment and offset of the pointer
13188 // expression and the element size.
13189 return std::make_pair(
13190 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
13191 CharUnits::Zero());
13192}
13193
13194/// This helper function takes an lvalue expression and returns the alignment of
13195/// a VarDecl and a constant offset from the VarDecl.
13196std::optional<std::pair<
13197 CharUnits,
13199 ASTContext &Ctx) {
13200 E = E->IgnoreParens();
13201 switch (E->getStmtClass()) {
13202 default:
13203 break;
13204 case Stmt::CStyleCastExprClass:
13205 case Stmt::CXXStaticCastExprClass:
13206 case Stmt::ImplicitCastExprClass: {
13207 auto *CE = cast<CastExpr>(E);
13208 const Expr *From = CE->getSubExpr();
13209 switch (CE->getCastKind()) {
13210 default:
13211 break;
13212 case CK_NoOp:
13213 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13214 case CK_UncheckedDerivedToBase:
13215 case CK_DerivedToBase: {
13216 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13217 if (!P)
13218 break;
13219 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
13220 P->second, Ctx);
13221 }
13222 }
13223 break;
13224 }
13225 case Stmt::ArraySubscriptExprClass: {
13226 auto *ASE = cast<ArraySubscriptExpr>(E);
13228 false, Ctx);
13229 }
13230 case Stmt::DeclRefExprClass: {
13231 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
13232 // FIXME: If VD is captured by copy or is an escaping __block variable,
13233 // use the alignment of VD's type.
13234 if (!VD->getType()->isReferenceType()) {
13235 // Dependent alignment cannot be resolved -> bail out.
13236 if (VD->hasDependentAlignment())
13237 break;
13238 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
13239 }
13240 if (VD->hasInit())
13241 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
13242 }
13243 break;
13244 }
13245 case Stmt::MemberExprClass: {
13246 auto *ME = cast<MemberExpr>(E);
13247 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
13248 if (!FD || FD->getType()->isReferenceType() ||
13249 FD->getParent()->isInvalidDecl())
13250 break;
13251 std::optional<std::pair<CharUnits, CharUnits>> P;
13252 if (ME->isArrow())
13253 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
13254 else
13255 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
13256 if (!P)
13257 break;
13258 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
13259 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
13260 return std::make_pair(P->first,
13261 P->second + CharUnits::fromQuantity(Offset));
13262 }
13263 case Stmt::UnaryOperatorClass: {
13264 auto *UO = cast<UnaryOperator>(E);
13265 switch (UO->getOpcode()) {
13266 default:
13267 break;
13268 case UO_Deref:
13270 }
13271 break;
13272 }
13273 case Stmt::BinaryOperatorClass: {
13274 auto *BO = cast<BinaryOperator>(E);
13275 auto Opcode = BO->getOpcode();
13276 switch (Opcode) {
13277 default:
13278 break;
13279 case BO_Comma:
13281 }
13282 break;
13283 }
13284 }
13285 return std::nullopt;
13286}
13287
13288/// This helper function takes a pointer expression and returns the alignment of
13289/// a VarDecl and a constant offset from the VarDecl.
13290std::optional<std::pair<
13292 *E,
13294 &Ctx) {
13295 E = E->IgnoreParens();
13296 switch (E->getStmtClass()) {
13297 default:
13298 break;
13299 case Stmt::CStyleCastExprClass:
13300 case Stmt::CXXStaticCastExprClass:
13301 case Stmt::ImplicitCastExprClass: {
13302 auto *CE = cast<CastExpr>(E);
13303 const Expr *From = CE->getSubExpr();
13304 switch (CE->getCastKind()) {
13305 default:
13306 break;
13307 case CK_NoOp:
13308 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13309 case CK_ArrayToPointerDecay:
13310 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13311 case CK_UncheckedDerivedToBase:
13312 case CK_DerivedToBase: {
13313 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13314 if (!P)
13315 break;
13317 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
13318 }
13319 }
13320 break;
13321 }
13322 case Stmt::CXXThisExprClass: {
13323 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
13325 return std::make_pair(Alignment, CharUnits::Zero());
13326 }
13327 case Stmt::UnaryOperatorClass: {
13328 auto *UO = cast<UnaryOperator>(E);
13329 if (UO->getOpcode() == UO_AddrOf)
13331 break;
13332 }
13333 case Stmt::BinaryOperatorClass: {
13334 auto *BO = cast<BinaryOperator>(E);
13335 auto Opcode = BO->getOpcode();
13336 switch (Opcode) {
13337 default:
13338 break;
13339 case BO_Add:
13340 case BO_Sub: {
13341 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
13342 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
13343 std::swap(LHS, RHS);
13344 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
13345 Ctx);
13346 }
13347 case BO_Comma:
13348 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
13349 }
13350 break;
13351 }
13352 }
13353 return std::nullopt;
13354}
13355
13357 // See if we can compute the alignment of a VarDecl and an offset from it.
13358 std::optional<std::pair<CharUnits, CharUnits>> P =
13360
13361 if (P)
13362 return P->first.alignmentAtOffset(P->second);
13363
13364 // If that failed, return the type's alignment.
13366}
13367
13369 // This is actually a lot of work to potentially be doing on every
13370 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
13371 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
13372 return;
13373
13374 // Ignore dependent types.
13375 if (T->isDependentType() || Op->getType()->isDependentType())
13376 return;
13377
13378 // Require that the destination be a pointer type.
13379 const PointerType *DestPtr = T->getAs<PointerType>();
13380 if (!DestPtr) return;
13381
13382 // If the destination has alignment 1, we're done.
13383 QualType DestPointee = DestPtr->getPointeeType();
13384 if (DestPointee->isIncompleteType()) return;
13385 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
13386 if (DestAlign.isOne()) return;
13387
13388 // Require that the source be a pointer type.
13389 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
13390 if (!SrcPtr) return;
13391 QualType SrcPointee = SrcPtr->getPointeeType();
13392
13393 // Explicitly allow casts from cv void*. We already implicitly
13394 // allowed casts to cv void*, since they have alignment 1.
13395 // Also allow casts involving incomplete types, which implicitly
13396 // includes 'void'.
13397 if (SrcPointee->isIncompleteType()) return;
13398
13399 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
13400
13401 if (SrcAlign >= DestAlign) return;
13402
13403 Diag(TRange.getBegin(), diag::warn_cast_align)
13404 << Op->getType() << T
13405 << static_cast<unsigned>(SrcAlign.getQuantity())
13406 << static_cast<unsigned>(DestAlign.getQuantity())
13407 << TRange << Op->getSourceRange();
13408}
13409
13410void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13411 const ArraySubscriptExpr *ASE,
13412 bool AllowOnePastEnd, bool IndexNegated) {
13413 // Already diagnosed by the constant evaluator.
13415 return;
13416
13417 IndexExpr = IndexExpr->IgnoreParenImpCasts();
13418 if (IndexExpr->isValueDependent())
13419 return;
13420
13421 const Type *EffectiveType =
13423 BaseExpr = BaseExpr->IgnoreParenCasts();
13424 const ConstantArrayType *ArrayTy =
13426
13428 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
13429
13430 const Type *BaseType =
13431 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
13432 bool IsUnboundedArray =
13433 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
13434 Context, StrictFlexArraysLevel,
13435 /*IgnoreTemplateOrMacroSubstitution=*/true);
13436 if (EffectiveType->isDependentType() ||
13437 (!IsUnboundedArray && BaseType->isDependentType()))
13438 return;
13439
13442 return;
13443
13444 llvm::APSInt index = Result.Val.getInt();
13445 if (IndexNegated) {
13446 index.setIsUnsigned(false);
13447 index = -index;
13448 }
13449
13450 if (IsUnboundedArray) {
13451 if (EffectiveType->isFunctionType())
13452 return;
13453 if (index.isUnsigned() || !index.isNegative()) {
13454 const auto &ASTC = getASTContext();
13455 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
13456 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
13457 if (index.getBitWidth() < AddrBits)
13458 index = index.zext(AddrBits);
13459 std::optional<CharUnits> ElemCharUnits =
13460 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
13461 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
13462 // pointer) bounds-checking isn't meaningful.
13463 if (!ElemCharUnits || ElemCharUnits->isZero())
13464 return;
13465 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
13466 // If index has more active bits than address space, we already know
13467 // we have a bounds violation to warn about. Otherwise, compute
13468 // address of (index + 1)th element, and warn about bounds violation
13469 // only if that address exceeds address space.
13470 if (index.getActiveBits() <= AddrBits) {
13471 bool Overflow;
13472 llvm::APInt Product(index);
13473 Product += 1;
13474 Product = Product.umul_ov(ElemBytes, Overflow);
13475 if (!Overflow && Product.getActiveBits() <= AddrBits)
13476 return;
13477 }
13478
13479 // Need to compute max possible elements in address space, since that
13480 // is included in diag message.
13481 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
13482 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
13483 MaxElems += 1;
13484 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
13485 MaxElems = MaxElems.udiv(ElemBytes);
13486
13487 unsigned DiagID =
13488 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
13489 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
13490
13491 // Diag message shows element size in bits and in "bytes" (platform-
13492 // dependent CharUnits)
13493 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13494 PDiag(DiagID)
13495 << toString(index, 10, true) << AddrBits
13496 << (unsigned)ASTC.toBits(*ElemCharUnits)
13497 << toString(ElemBytes, 10, false)
13498 << toString(MaxElems, 10, false)
13499 << (unsigned)MaxElems.getLimitedValue(~0U)
13500 << IndexExpr->getSourceRange());
13501
13502 const NamedDecl *ND = nullptr;
13503 // Try harder to find a NamedDecl to point at in the note.
13504 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
13505 BaseExpr = ASE->getBase()->IgnoreParenCasts();
13506 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13507 ND = DRE->getDecl();
13508 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
13509 ND = ME->getMemberDecl();
13510
13511 if (ND)
13512 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13513 PDiag(diag::note_array_declared_here) << ND);
13514 }
13515 return;
13516 }
13517
13518 if (index.isUnsigned() || !index.isNegative()) {
13519 // It is possible that the type of the base expression after
13520 // IgnoreParenCasts is incomplete, even though the type of the base
13521 // expression before IgnoreParenCasts is complete (see PR39746 for an
13522 // example). In this case we have no information about whether the array
13523 // access exceeds the array bounds. However we can still diagnose an array
13524 // access which precedes the array bounds.
13525 if (BaseType->isIncompleteType())
13526 return;
13527
13528 llvm::APInt size = ArrayTy->getSize();
13529
13530 if (BaseType != EffectiveType) {
13531 // Make sure we're comparing apples to apples when comparing index to
13532 // size.
13533 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13534 uint64_t array_typesize = Context.getTypeSize(BaseType);
13535
13536 // Handle ptrarith_typesize being zero, such as when casting to void*.
13537 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
13538 if (!ptrarith_typesize)
13539 ptrarith_typesize = Context.getCharWidth();
13540
13541 if (ptrarith_typesize != array_typesize) {
13542 // There's a cast to a different size type involved.
13543 uint64_t ratio = array_typesize / ptrarith_typesize;
13544
13545 // TODO: Be smarter about handling cases where array_typesize is not a
13546 // multiple of ptrarith_typesize.
13547 if (ptrarith_typesize * ratio == array_typesize)
13548 size *= llvm::APInt(size.getBitWidth(), ratio);
13549 }
13550 }
13551
13552 if (size.getBitWidth() > index.getBitWidth())
13553 index = index.zext(size.getBitWidth());
13554 else if (size.getBitWidth() < index.getBitWidth())
13555 size = size.zext(index.getBitWidth());
13556
13557 // For array subscripting the index must be less than size, but for pointer
13558 // arithmetic also allow the index (offset) to be equal to size since
13559 // computing the next address after the end of the array is legal and
13560 // commonly done e.g. in C++ iterators and range-based for loops.
13561 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13562 return;
13563
13564 // Suppress the warning if the subscript expression (as identified by the
13565 // ']' location) and the index expression are both from macro expansions
13566 // within a system header.
13567 if (ASE) {
13569 ASE->getRBracketLoc());
13570 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13571 SourceLocation IndexLoc =
13572 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13573 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13574 return;
13575 }
13576 }
13577
13578 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
13579 : diag::warn_ptr_arith_exceeds_bounds;
13580 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
13581 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
13582
13584 BaseExpr->getBeginLoc(), BaseExpr,
13585 PDiag(DiagID) << toString(index, 10, true) << ArrayTy->desugar()
13586 << CastMsg << CastMsgTy << IndexExpr->getSourceRange());
13587 } else {
13588 unsigned DiagID = diag::warn_array_index_precedes_bounds;
13589 if (!ASE) {
13590 DiagID = diag::warn_ptr_arith_precedes_bounds;
13591 if (index.isNegative()) index = -index;
13592 }
13593
13594 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13595 PDiag(DiagID) << toString(index, 10, true)
13596 << IndexExpr->getSourceRange());
13597 }
13598
13599 const NamedDecl *ND = nullptr;
13600 // Try harder to find a NamedDecl to point at in the note.
13601 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
13602 BaseExpr = ASE->getBase()->IgnoreParenCasts();
13603 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13604 ND = DRE->getDecl();
13605 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
13606 ND = ME->getMemberDecl();
13607
13608 if (ND)
13609 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13610 PDiag(diag::note_array_declared_here) << ND);
13611}
13612
13613void Sema::CheckArrayAccess(const Expr *expr) {
13614 int AllowOnePastEnd = 0;
13615 while (expr) {
13616 expr = expr->IgnoreParenImpCasts();
13617 switch (expr->getStmtClass()) {
13618 case Stmt::ArraySubscriptExprClass: {
13619 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13620 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13621 AllowOnePastEnd > 0);
13622 expr = ASE->getBase();
13623 break;
13624 }
13625 case Stmt::MemberExprClass: {
13626 expr = cast<MemberExpr>(expr)->getBase();
13627 break;
13628 }
13629 case Stmt::ArraySectionExprClass: {
13630 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
13631 // FIXME: We should probably be checking all of the elements to the
13632 // 'length' here as well.
13633 if (ASE->getLowerBound())
13634 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13635 /*ASE=*/nullptr, AllowOnePastEnd > 0);
13636 return;
13637 }
13638 case Stmt::UnaryOperatorClass: {
13639 // Only unwrap the * and & unary operators
13640 const UnaryOperator *UO = cast<UnaryOperator>(expr);
13641 expr = UO->getSubExpr();
13642 switch (UO->getOpcode()) {
13643 case UO_AddrOf:
13644 AllowOnePastEnd++;
13645 break;
13646 case UO_Deref:
13647 AllowOnePastEnd--;
13648 break;
13649 default:
13650 return;
13651 }
13652 break;
13653 }
13654 case Stmt::ConditionalOperatorClass: {
13655 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13656 if (const Expr *lhs = cond->getLHS())
13657 CheckArrayAccess(lhs);
13658 if (const Expr *rhs = cond->getRHS())
13659 CheckArrayAccess(rhs);
13660 return;
13661 }
13662 case Stmt::CXXOperatorCallExprClass: {
13663 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13664 for (const auto *Arg : OCE->arguments())
13665 CheckArrayAccess(Arg);
13666 return;
13667 }
13668 default:
13669 return;
13670 }
13671 }
13672}
13673
13675 Expr *RHS, bool isProperty) {
13676 // Check if RHS is an Objective-C object literal, which also can get
13677 // immediately zapped in a weak reference. Note that we explicitly
13678 // allow ObjCStringLiterals, since those are designed to never really die.
13679 RHS = RHS->IgnoreParenImpCasts();
13680
13681 // This enum needs to match with the 'select' in
13682 // warn_objc_arc_literal_assign (off-by-1).
13684 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
13685 return false;
13686
13687 S.Diag(Loc, diag::warn_arc_literal_assign)
13688 << (unsigned) Kind
13689 << (isProperty ? 0 : 1)
13690 << RHS->getSourceRange();
13691
13692 return true;
13693}
13694
13697 Expr *RHS, bool isProperty) {
13698 // Strip off any implicit cast added to get to the one ARC-specific.
13699 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13700 if (cast->getCastKind() == CK_ARCConsumeObject) {
13701 S.Diag(Loc, diag::warn_arc_retained_assign)
13703 << (isProperty ? 0 : 1)
13704 << RHS->getSourceRange();
13705 return true;
13706 }
13707 RHS = cast->getSubExpr();
13708 }
13709
13710 if (LT == Qualifiers::OCL_Weak &&
13711 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13712 return true;
13713
13714 return false;
13715}
13716
13718 QualType LHS, Expr *RHS) {
13720
13722 return false;
13723
13724 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13725 return true;
13726
13727 return false;
13728}
13729
13731 Expr *LHS, Expr *RHS) {
13732 QualType LHSType;
13733 // PropertyRef on LHS type need be directly obtained from
13734 // its declaration as it has a PseudoType.
13736 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13737 if (PRE && !PRE->isImplicitProperty()) {
13738 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13739 if (PD)
13740 LHSType = PD->getType();
13741 }
13742
13743 if (LHSType.isNull())
13744 LHSType = LHS->getType();
13745
13747
13748 if (LT == Qualifiers::OCL_Weak) {
13749 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13751 }
13752
13753 if (checkUnsafeAssigns(Loc, LHSType, RHS))
13754 return;
13755
13756 // FIXME. Check for other life times.
13757 if (LT != Qualifiers::OCL_None)
13758 return;
13759
13760 if (PRE) {
13761 if (PRE->isImplicitProperty())
13762 return;
13763 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13764 if (!PD)
13765 return;
13766
13767 unsigned Attributes = PD->getPropertyAttributes();
13768 if (Attributes & ObjCPropertyAttribute::kind_assign) {
13769 // when 'assign' attribute was not explicitly specified
13770 // by user, ignore it and rely on property type itself
13771 // for lifetime info.
13772 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13773 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
13774 LHSType->isObjCRetainableType())
13775 return;
13776
13777 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13778 if (cast->getCastKind() == CK_ARCConsumeObject) {
13779 Diag(Loc, diag::warn_arc_retained_property_assign)
13780 << RHS->getSourceRange();
13781 return;
13782 }
13783 RHS = cast->getSubExpr();
13784 }
13785 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
13786 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13787 return;
13788 }
13789 }
13790}
13791
13792//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13793
13794static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13795 SourceLocation StmtLoc,
13796 const NullStmt *Body) {
13797 // Do not warn if the body is a macro that expands to nothing, e.g:
13798 //
13799 // #define CALL(x)
13800 // if (condition)
13801 // CALL(0);
13802 if (Body->hasLeadingEmptyMacro())
13803 return false;
13804
13805 // Get line numbers of statement and body.
13806 bool StmtLineInvalid;
13807 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
13808 &StmtLineInvalid);
13809 if (StmtLineInvalid)
13810 return false;
13811
13812 bool BodyLineInvalid;
13813 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13814 &BodyLineInvalid);
13815 if (BodyLineInvalid)
13816 return false;
13817
13818 // Warn if null statement and body are on the same line.
13819 if (StmtLine != BodyLine)
13820 return false;
13821
13822 return true;
13823}
13824
13826 const Stmt *Body,
13827 unsigned DiagID) {
13828 // Since this is a syntactic check, don't emit diagnostic for template
13829 // instantiations, this just adds noise.
13831 return;
13832
13833 // The body should be a null statement.
13834 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13835 if (!NBody)
13836 return;
13837
13838 // Do the usual checks.
13839 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13840 return;
13841
13842 Diag(NBody->getSemiLoc(), DiagID);
13843 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13844}
13845
13847 const Stmt *PossibleBody) {
13848 assert(!CurrentInstantiationScope); // Ensured by caller
13849
13850 SourceLocation StmtLoc;
13851 const Stmt *Body;
13852 unsigned DiagID;
13853 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13854 StmtLoc = FS->getRParenLoc();
13855 Body = FS->getBody();
13856 DiagID = diag::warn_empty_for_body;
13857 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13858 StmtLoc = WS->getRParenLoc();
13859 Body = WS->getBody();
13860 DiagID = diag::warn_empty_while_body;
13861 } else
13862 return; // Neither `for' nor `while'.
13863
13864 // The body should be a null statement.
13865 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13866 if (!NBody)
13867 return;
13868
13869 // Skip expensive checks if diagnostic is disabled.
13870 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
13871 return;
13872
13873 // Do the usual checks.
13874 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13875 return;
13876
13877 // `for(...);' and `while(...);' are popular idioms, so in order to keep
13878 // noise level low, emit diagnostics only if for/while is followed by a
13879 // CompoundStmt, e.g.:
13880 // for (int i = 0; i < n; i++);
13881 // {
13882 // a(i);
13883 // }
13884 // or if for/while is followed by a statement with more indentation
13885 // than for/while itself:
13886 // for (int i = 0; i < n; i++);
13887 // a(i);
13888 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13889 if (!ProbableTypo) {
13890 bool BodyColInvalid;
13891 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
13892 PossibleBody->getBeginLoc(), &BodyColInvalid);
13893 if (BodyColInvalid)
13894 return;
13895
13896 bool StmtColInvalid;
13897 unsigned StmtCol =
13898 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
13899 if (StmtColInvalid)
13900 return;
13901
13902 if (BodyCol > StmtCol)
13903 ProbableTypo = true;
13904 }
13905
13906 if (ProbableTypo) {
13907 Diag(NBody->getSemiLoc(), DiagID);
13908 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13909 }
13910}
13911
13912//===--- CHECK: Warn on self move with std::move. -------------------------===//
13913
13914void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13915 SourceLocation OpLoc) {
13916 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13917 return;
13918
13920 return;
13921
13922 // Strip parens and casts away.
13923 LHSExpr = LHSExpr->IgnoreParenImpCasts();
13924 RHSExpr = RHSExpr->IgnoreParenImpCasts();
13925
13926 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
13927 // which we can treat as an inlined std::move
13928 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
13929 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
13930 RHSExpr = CE->getArg(0);
13931 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
13932 CXXSCE && CXXSCE->isXValue())
13933 RHSExpr = CXXSCE->getSubExpr();
13934 else
13935 return;
13936
13937 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13938 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13939
13940 // Two DeclRefExpr's, check that the decls are the same.
13941 if (LHSDeclRef && RHSDeclRef) {
13942 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13943 return;
13944 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13945 RHSDeclRef->getDecl()->getCanonicalDecl())
13946 return;
13947
13948 auto D = Diag(OpLoc, diag::warn_self_move)
13949 << LHSExpr->getType() << LHSExpr->getSourceRange()
13950 << RHSExpr->getSourceRange();
13951 if (const FieldDecl *F =
13953 D << 1 << F
13954 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
13955 else
13956 D << 0;
13957 return;
13958 }
13959
13960 // Member variables require a different approach to check for self moves.
13961 // MemberExpr's are the same if every nested MemberExpr refers to the same
13962 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
13963 // the base Expr's are CXXThisExpr's.
13964 const Expr *LHSBase = LHSExpr;
13965 const Expr *RHSBase = RHSExpr;
13966 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
13967 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
13968 if (!LHSME || !RHSME)
13969 return;
13970
13971 while (LHSME && RHSME) {
13972 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
13973 RHSME->getMemberDecl()->getCanonicalDecl())
13974 return;
13975
13976 LHSBase = LHSME->getBase();
13977 RHSBase = RHSME->getBase();
13978 LHSME = dyn_cast<MemberExpr>(LHSBase);
13979 RHSME = dyn_cast<MemberExpr>(RHSBase);
13980 }
13981
13982 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
13983 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
13984 if (LHSDeclRef && RHSDeclRef) {
13985 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13986 return;
13987 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13988 RHSDeclRef->getDecl()->getCanonicalDecl())
13989 return;
13990
13991 Diag(OpLoc, diag::warn_self_move)
13992 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
13993 << RHSExpr->getSourceRange();
13994 return;
13995 }
13996
13997 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
13998 Diag(OpLoc, diag::warn_self_move)
13999 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
14000 << RHSExpr->getSourceRange();
14001}
14002
14003//===--- Layout compatibility ----------------------------------------------//
14004
14005static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
14006
14007/// Check if two enumeration types are layout-compatible.
14008static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
14009 const EnumDecl *ED2) {
14010 // C++11 [dcl.enum] p8:
14011 // Two enumeration types are layout-compatible if they have the same
14012 // underlying type.
14013 return ED1->isComplete() && ED2->isComplete() &&
14014 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14015}
14016
14017/// Check if two fields are layout-compatible.
14018/// Can be used on union members, which are exempt from alignment requirement
14019/// of common initial sequence.
14020static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
14021 const FieldDecl *Field2,
14022 bool AreUnionMembers = false) {
14023 [[maybe_unused]] const Type *Field1Parent =
14024 Field1->getParent()->getTypeForDecl();
14025 [[maybe_unused]] const Type *Field2Parent =
14026 Field2->getParent()->getTypeForDecl();
14027 assert(((Field1Parent->isStructureOrClassType() &&
14028 Field2Parent->isStructureOrClassType()) ||
14029 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
14030 "Can't evaluate layout compatibility between a struct field and a "
14031 "union field.");
14032 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
14033 (AreUnionMembers && Field1Parent->isUnionType())) &&
14034 "AreUnionMembers should be 'true' for union fields (only).");
14035
14036 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14037 return false;
14038
14039 if (Field1->isBitField() != Field2->isBitField())
14040 return false;
14041
14042 if (Field1->isBitField()) {
14043 // Make sure that the bit-fields are the same length.
14044 unsigned Bits1 = Field1->getBitWidthValue(C);
14045 unsigned Bits2 = Field2->getBitWidthValue(C);
14046
14047 if (Bits1 != Bits2)
14048 return false;
14049 }
14050
14051 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
14052 Field2->hasAttr<clang::NoUniqueAddressAttr>())
14053 return false;
14054
14055 if (!AreUnionMembers &&
14056 Field1->getMaxAlignment() != Field2->getMaxAlignment())
14057 return false;
14058
14059 return true;
14060}
14061
14062/// Check if two standard-layout structs are layout-compatible.
14063/// (C++11 [class.mem] p17)
14064static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
14065 const RecordDecl *RD2) {
14066 // Get to the class where the fields are declared
14067 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
14068 RD1 = D1CXX->getStandardLayoutBaseWithFields();
14069
14070 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
14071 RD2 = D2CXX->getStandardLayoutBaseWithFields();
14072
14073 // Check the fields.
14074 return llvm::equal(RD1->fields(), RD2->fields(),
14075 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
14076 return isLayoutCompatible(C, F1, F2);
14077 });
14078}
14079
14080/// Check if two standard-layout unions are layout-compatible.
14081/// (C++11 [class.mem] p18)
14082static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
14083 const RecordDecl *RD2) {
14085 for (auto *Field2 : RD2->fields())
14086 UnmatchedFields.insert(Field2);
14087
14088 for (auto *Field1 : RD1->fields()) {
14089 auto I = UnmatchedFields.begin();
14090 auto E = UnmatchedFields.end();
14091
14092 for ( ; I != E; ++I) {
14093 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
14094 bool Result = UnmatchedFields.erase(*I);
14095 (void) Result;
14096 assert(Result);
14097 break;
14098 }
14099 }
14100 if (I == E)
14101 return false;
14102 }
14103
14104 return UnmatchedFields.empty();
14105}
14106
14107static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
14108 const RecordDecl *RD2) {
14109 if (RD1->isUnion() != RD2->isUnion())
14110 return false;
14111
14112 if (RD1->isUnion())
14113 return isLayoutCompatibleUnion(C, RD1, RD2);
14114 else
14115 return isLayoutCompatibleStruct(C, RD1, RD2);
14116}
14117
14118/// Check if two types are layout-compatible in C++11 sense.
14119static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
14120 if (T1.isNull() || T2.isNull())
14121 return false;
14122
14123 // C++20 [basic.types] p11:
14124 // Two types cv1 T1 and cv2 T2 are layout-compatible types
14125 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
14126 // or layout-compatible standard-layout class types (11.4).
14129
14130 if (C.hasSameType(T1, T2))
14131 return true;
14132
14133 const Type::TypeClass TC1 = T1->getTypeClass();
14134 const Type::TypeClass TC2 = T2->getTypeClass();
14135
14136 if (TC1 != TC2)
14137 return false;
14138
14139 if (TC1 == Type::Enum) {
14140 return isLayoutCompatible(C,
14141 cast<EnumType>(T1)->getDecl(),
14142 cast<EnumType>(T2)->getDecl());
14143 } else if (TC1 == Type::Record) {
14144 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14145 return false;
14146
14147 return isLayoutCompatible(C,
14148 cast<RecordType>(T1)->getDecl(),
14149 cast<RecordType>(T2)->getDecl());
14150 }
14151
14152 return false;
14153}
14154
14156 return isLayoutCompatible(getASTContext(), T1, T2);
14157}
14158
14159//===-------------- Pointer interconvertibility ----------------------------//
14160
14162 const TypeSourceInfo *Derived) {
14163 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
14164 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
14165
14166 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
14167 getASTContext().hasSameType(BaseT, DerivedT))
14168 return true;
14169
14170 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
14171 return false;
14172
14173 // Per [basic.compound]/4.3, containing object has to be standard-layout.
14174 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
14175 return true;
14176
14177 return false;
14178}
14179
14180//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14181
14182/// Given a type tag expression find the type tag itself.
14183///
14184/// \param TypeExpr Type tag expression, as it appears in user's code.
14185///
14186/// \param VD Declaration of an identifier that appears in a type tag.
14187///
14188/// \param MagicValue Type tag magic value.
14189///
14190/// \param isConstantEvaluated whether the evalaution should be performed in
14191
14192/// constant context.
14193static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14194 const ValueDecl **VD, uint64_t *MagicValue,
14195 bool isConstantEvaluated) {
14196 while(true) {
14197 if (!TypeExpr)
14198 return false;
14199
14200 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14201
14202 switch (TypeExpr->getStmtClass()) {
14203 case Stmt::UnaryOperatorClass: {
14204 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14205 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14206 TypeExpr = UO->getSubExpr();
14207 continue;
14208 }
14209 return false;
14210 }
14211
14212 case Stmt::DeclRefExprClass: {
14213 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14214 *VD = DRE->getDecl();
14215 return true;
14216 }
14217
14218 case Stmt::IntegerLiteralClass: {
14219 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14220 llvm::APInt MagicValueAPInt = IL->getValue();
14221 if (MagicValueAPInt.getActiveBits() <= 64) {
14222 *MagicValue = MagicValueAPInt.getZExtValue();
14223 return true;
14224 } else
14225 return false;
14226 }
14227
14228 case Stmt::BinaryConditionalOperatorClass:
14229 case Stmt::ConditionalOperatorClass: {
14230 const AbstractConditionalOperator *ACO =
14231 cast<AbstractConditionalOperator>(TypeExpr);
14232 bool Result;
14233 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14234 isConstantEvaluated)) {
14235 if (Result)
14236 TypeExpr = ACO->getTrueExpr();
14237 else
14238 TypeExpr = ACO->getFalseExpr();
14239 continue;
14240 }
14241 return false;
14242 }
14243
14244 case Stmt::BinaryOperatorClass: {
14245 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14246 if (BO->getOpcode() == BO_Comma) {
14247 TypeExpr = BO->getRHS();
14248 continue;
14249 }
14250 return false;
14251 }
14252
14253 default:
14254 return false;
14255 }
14256 }
14257}
14258
14259/// Retrieve the C type corresponding to type tag TypeExpr.
14260///
14261/// \param TypeExpr Expression that specifies a type tag.
14262///
14263/// \param MagicValues Registered magic values.
14264///
14265/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14266/// kind.
14267///
14268/// \param TypeInfo Information about the corresponding C type.
14269///
14270/// \param isConstantEvaluated whether the evalaution should be performed in
14271/// constant context.
14272///
14273/// \returns true if the corresponding C type was found.
14275 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14276 const ASTContext &Ctx,
14277 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14278 *MagicValues,
14279 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14280 bool isConstantEvaluated) {
14281 FoundWrongKind = false;
14282
14283 // Variable declaration that has type_tag_for_datatype attribute.
14284 const ValueDecl *VD = nullptr;
14285
14286 uint64_t MagicValue;
14287
14288 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
14289 return false;
14290
14291 if (VD) {
14292 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
14293 if (I->getArgumentKind() != ArgumentKind) {
14294 FoundWrongKind = true;
14295 return false;
14296 }
14297 TypeInfo.Type = I->getMatchingCType();
14298 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14299 TypeInfo.MustBeNull = I->getMustBeNull();
14300 return true;
14301 }
14302 return false;
14303 }
14304
14305 if (!MagicValues)
14306 return false;
14307
14308 llvm::DenseMap<Sema::TypeTagMagicValue,
14309 Sema::TypeTagData>::const_iterator I =
14310 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14311 if (I == MagicValues->end())
14312 return false;
14313
14314 TypeInfo = I->second;
14315 return true;
14316}
14317
14319 uint64_t MagicValue, QualType Type,
14320 bool LayoutCompatible,
14321 bool MustBeNull) {
14322 if (!TypeTagForDatatypeMagicValues)
14323 TypeTagForDatatypeMagicValues.reset(
14324 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14325
14326 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14327 (*TypeTagForDatatypeMagicValues)[Magic] =
14328 TypeTagData(Type, LayoutCompatible, MustBeNull);
14329}
14330
14331static bool IsSameCharType(QualType T1, QualType T2) {
14332 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14333 if (!BT1)
14334 return false;
14335
14336 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14337 if (!BT2)
14338 return false;
14339
14340 BuiltinType::Kind T1Kind = BT1->getKind();
14341 BuiltinType::Kind T2Kind = BT2->getKind();
14342
14343 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
14344 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
14345 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14346 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14347}
14348
14349void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
14350 const ArrayRef<const Expr *> ExprArgs,
14351 SourceLocation CallSiteLoc) {
14352 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14353 bool IsPointerAttr = Attr->getIsPointer();
14354
14355 // Retrieve the argument representing the 'type_tag'.
14356 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14357 if (TypeTagIdxAST >= ExprArgs.size()) {
14358 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14359 << 0 << Attr->getTypeTagIdx().getSourceIndex();
14360 return;
14361 }
14362 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
14363 bool FoundWrongKind;
14364 TypeTagData TypeInfo;
14365 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
14366 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
14368 if (FoundWrongKind)
14369 Diag(TypeTagExpr->getExprLoc(),
14370 diag::warn_type_tag_for_datatype_wrong_kind)
14371 << TypeTagExpr->getSourceRange();
14372 return;
14373 }
14374
14375 // Retrieve the argument representing the 'arg_idx'.
14376 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14377 if (ArgumentIdxAST >= ExprArgs.size()) {
14378 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14379 << 1 << Attr->getArgumentIdx().getSourceIndex();
14380 return;
14381 }
14382 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
14383 if (IsPointerAttr) {
14384 // Skip implicit cast of pointer to `void *' (as a function argument).
14385 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
14386 if (ICE->getType()->isVoidPointerType() &&
14387 ICE->getCastKind() == CK_BitCast)
14388 ArgumentExpr = ICE->getSubExpr();
14389 }
14390 QualType ArgumentType = ArgumentExpr->getType();
14391
14392 // Passing a `void*' pointer shouldn't trigger a warning.
14393 if (IsPointerAttr && ArgumentType->isVoidPointerType())
14394 return;
14395
14396 if (TypeInfo.MustBeNull) {
14397 // Type tag with matching void type requires a null pointer.
14398 if (!ArgumentExpr->isNullPointerConstant(Context,
14400 Diag(ArgumentExpr->getExprLoc(),
14401 diag::warn_type_safety_null_pointer_required)
14402 << ArgumentKind->getName()
14403 << ArgumentExpr->getSourceRange()
14404 << TypeTagExpr->getSourceRange();
14405 }
14406 return;
14407 }
14408
14409 QualType RequiredType = TypeInfo.Type;
14410 if (IsPointerAttr)
14411 RequiredType = Context.getPointerType(RequiredType);
14412
14413 bool mismatch = false;
14414 if (!TypeInfo.LayoutCompatible) {
14415 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14416
14417 // C++11 [basic.fundamental] p1:
14418 // Plain char, signed char, and unsigned char are three distinct types.
14419 //
14420 // But we treat plain `char' as equivalent to `signed char' or `unsigned
14421 // char' depending on the current char signedness mode.
14422 if (mismatch)
14423 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14424 RequiredType->getPointeeType())) ||
14425 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14426 mismatch = false;
14427 } else
14428 if (IsPointerAttr)
14429 mismatch = !isLayoutCompatible(Context,
14430 ArgumentType->getPointeeType(),
14431 RequiredType->getPointeeType());
14432 else
14433 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14434
14435 if (mismatch)
14436 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
14437 << ArgumentType << ArgumentKind
14438 << TypeInfo.LayoutCompatible << RequiredType
14439 << ArgumentExpr->getSourceRange()
14440 << TypeTagExpr->getSourceRange();
14441}
14442
14443void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14444 CharUnits Alignment) {
14445 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14446}
14447
14449 for (MisalignedMember &m : MisalignedMembers) {
14450 const NamedDecl *ND = m.RD;
14451 if (ND->getName().empty()) {
14452 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14453 ND = TD;
14454 }
14455 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
14456 << m.MD << ND << m.E->getSourceRange();
14457 }
14458 MisalignedMembers.clear();
14459}
14460
14462 E = E->IgnoreParens();
14463 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
14464 return;
14465 if (isa<UnaryOperator>(E) &&
14466 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14467 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14468 if (isa<MemberExpr>(Op)) {
14469 auto *MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
14470 if (MA != MisalignedMembers.end() &&
14471 (T->isDependentType() || T->isIntegerType() ||
14474 T->getPointeeType()) <= MA->Alignment))))
14475 MisalignedMembers.erase(MA);
14476 }
14477 }
14478}
14479
14481 Expr *E,
14482 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14483 Action) {
14484 const auto *ME = dyn_cast<MemberExpr>(E);
14485 if (!ME)
14486 return;
14487
14488 // No need to check expressions with an __unaligned-qualified type.
14490 return;
14491
14492 // For a chain of MemberExpr like "a.b.c.d" this list
14493 // will keep FieldDecl's like [d, c, b].
14494 SmallVector<FieldDecl *, 4> ReverseMemberChain;
14495 const MemberExpr *TopME = nullptr;
14496 bool AnyIsPacked = false;
14497 do {
14498 QualType BaseType = ME->getBase()->getType();
14499 if (BaseType->isDependentType())
14500 return;
14501 if (ME->isArrow())
14502 BaseType = BaseType->getPointeeType();
14503 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
14504 if (RD->isInvalidDecl())
14505 return;
14506
14507 ValueDecl *MD = ME->getMemberDecl();
14508 auto *FD = dyn_cast<FieldDecl>(MD);
14509 // We do not care about non-data members.
14510 if (!FD || FD->isInvalidDecl())
14511 return;
14512
14513 AnyIsPacked =
14514 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14515 ReverseMemberChain.push_back(FD);
14516
14517 TopME = ME;
14518 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14519 } while (ME);
14520 assert(TopME && "We did not compute a topmost MemberExpr!");
14521
14522 // Not the scope of this diagnostic.
14523 if (!AnyIsPacked)
14524 return;
14525
14526 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14527 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14528 // TODO: The innermost base of the member expression may be too complicated.
14529 // For now, just disregard these cases. This is left for future
14530 // improvement.
14531 if (!DRE && !isa<CXXThisExpr>(TopBase))
14532 return;
14533
14534 // Alignment expected by the whole expression.
14535 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14536
14537 // No need to do anything else with this case.
14538 if (ExpectedAlignment.isOne())
14539 return;
14540
14541 // Synthesize offset of the whole access.
14542 CharUnits Offset;
14543 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
14545
14546 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14547 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14548 ReverseMemberChain.back()->getParent()->getTypeForDecl());
14549
14550 // The base expression of the innermost MemberExpr may give
14551 // stronger guarantees than the class containing the member.
14552 if (DRE && !TopME->isArrow()) {
14553 const ValueDecl *VD = DRE->getDecl();
14554 if (!VD->getType()->isReferenceType())
14555 CompleteObjectAlignment =
14556 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14557 }
14558
14559 // Check if the synthesized offset fulfills the alignment.
14560 if (Offset % ExpectedAlignment != 0 ||
14561 // It may fulfill the offset it but the effective alignment may still be
14562 // lower than the expected expression alignment.
14563 CompleteObjectAlignment < ExpectedAlignment) {
14564 // If this happens, we want to determine a sensible culprit of this.
14565 // Intuitively, watching the chain of member expressions from right to
14566 // left, we start with the required alignment (as required by the field
14567 // type) but some packed attribute in that chain has reduced the alignment.
14568 // It may happen that another packed structure increases it again. But if
14569 // we are here such increase has not been enough. So pointing the first
14570 // FieldDecl that either is packed or else its RecordDecl is,
14571 // seems reasonable.
14572 FieldDecl *FD = nullptr;
14573 CharUnits Alignment;
14574 for (FieldDecl *FDI : ReverseMemberChain) {
14575 if (FDI->hasAttr<PackedAttr>() ||
14576 FDI->getParent()->hasAttr<PackedAttr>()) {
14577 FD = FDI;
14578 Alignment = std::min(
14581 break;
14582 }
14583 }
14584 assert(FD && "We did not find a packed FieldDecl!");
14585 Action(E, FD->getParent(), FD, Alignment);
14586 }
14587}
14588
14589void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14590 using namespace std::placeholders;
14591
14593 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14594 _2, _3, _4));
14595}
14596
14598 if (checkArgCount(TheCall, 1))
14599 return true;
14600
14601 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
14602 if (A.isInvalid())
14603 return true;
14604
14605 TheCall->setArg(0, A.get());
14606 QualType TyA = A.get()->getType();
14607
14608 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA, 1))
14609 return true;
14610
14611 TheCall->setType(TyA);
14612 return false;
14613}
14614
14615bool Sema::BuiltinElementwiseMath(CallExpr *TheCall, bool FPOnly) {
14616 QualType Res;
14617 if (BuiltinVectorMath(TheCall, Res, FPOnly))
14618 return true;
14619 TheCall->setType(Res);
14620 return false;
14621}
14622
14624 QualType Res;
14625 if (BuiltinVectorMath(TheCall, Res))
14626 return true;
14627
14628 if (auto *VecTy0 = Res->getAs<VectorType>())
14629 TheCall->setType(VecTy0->getElementType());
14630 else
14631 TheCall->setType(Res);
14632
14633 return false;
14634}
14635
14636bool Sema::BuiltinVectorMath(CallExpr *TheCall, QualType &Res, bool FPOnly) {
14637 if (checkArgCount(TheCall, 2))
14638 return true;
14639
14640 ExprResult A = TheCall->getArg(0);
14641 ExprResult B = TheCall->getArg(1);
14642 // Do standard promotions between the two arguments, returning their common
14643 // type.
14644 Res = UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
14645 if (A.isInvalid() || B.isInvalid())
14646 return true;
14647
14648 QualType TyA = A.get()->getType();
14649 QualType TyB = B.get()->getType();
14650
14651 if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
14652 return Diag(A.get()->getBeginLoc(),
14653 diag::err_typecheck_call_different_arg_types)
14654 << TyA << TyB;
14655
14656 if (FPOnly) {
14657 if (checkFPMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA, 1))
14658 return true;
14659 } else {
14660 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA, 1))
14661 return true;
14662 }
14663
14664 TheCall->setArg(0, A.get());
14665 TheCall->setArg(1, B.get());
14666 return false;
14667}
14668
14670 bool CheckForFloatArgs) {
14671 if (checkArgCount(TheCall, 3))
14672 return true;
14673
14674 Expr *Args[3];
14675 for (int I = 0; I < 3; ++I) {
14676 ExprResult Converted = UsualUnaryConversions(TheCall->getArg(I));
14677 if (Converted.isInvalid())
14678 return true;
14679 Args[I] = Converted.get();
14680 }
14681
14682 if (CheckForFloatArgs) {
14683 int ArgOrdinal = 1;
14684 for (Expr *Arg : Args) {
14686 Arg->getType(), ArgOrdinal++))
14687 return true;
14688 }
14689 } else {
14690 int ArgOrdinal = 1;
14691 for (Expr *Arg : Args) {
14692 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
14693 ArgOrdinal++))
14694 return true;
14695 }
14696 }
14697
14698 for (int I = 1; I < 3; ++I) {
14699 if (Args[0]->getType().getCanonicalType() !=
14700 Args[I]->getType().getCanonicalType()) {
14701 return Diag(Args[0]->getBeginLoc(),
14702 diag::err_typecheck_call_different_arg_types)
14703 << Args[0]->getType() << Args[I]->getType();
14704 }
14705
14706 TheCall->setArg(I, Args[I]);
14707 }
14708
14709 TheCall->setType(Args[0]->getType());
14710 return false;
14711}
14712
14713bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
14714 if (checkArgCount(TheCall, 1))
14715 return true;
14716
14717 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
14718 if (A.isInvalid())
14719 return true;
14720
14721 TheCall->setArg(0, A.get());
14722 return false;
14723}
14724
14725bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
14726 if (checkArgCount(TheCall, 1))
14727 return true;
14728
14729 ExprResult Arg = TheCall->getArg(0);
14730 QualType TyArg = Arg.get()->getType();
14731
14732 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
14733 return Diag(TheCall->getArg(0)->getBeginLoc(), diag::err_builtin_invalid_arg_type)
14734 << 1 << /*vector, integer or floating point ty*/ 0 << TyArg;
14735
14736 TheCall->setType(TyArg);
14737 return false;
14738}
14739
14740ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
14741 ExprResult CallResult) {
14742 if (checkArgCount(TheCall, 1))
14743 return ExprError();
14744
14745 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
14746 if (MatrixArg.isInvalid())
14747 return MatrixArg;
14748 Expr *Matrix = MatrixArg.get();
14749
14750 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
14751 if (!MType) {
14752 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
14753 << 1 << /* matrix ty*/ 1 << Matrix->getType();
14754 return ExprError();
14755 }
14756
14757 // Create returned matrix type by swapping rows and columns of the argument
14758 // matrix type.
14760 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
14761
14762 // Change the return type to the type of the returned matrix.
14763 TheCall->setType(ResultType);
14764
14765 // Update call argument to use the possibly converted matrix argument.
14766 TheCall->setArg(0, Matrix);
14767 return CallResult;
14768}
14769
14770// Get and verify the matrix dimensions.
14771static std::optional<unsigned>
14773 SourceLocation ErrorPos;
14774 std::optional<llvm::APSInt> Value =
14775 Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
14776 if (!Value) {
14777 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
14778 << Name;
14779 return {};
14780 }
14781 uint64_t Dim = Value->getZExtValue();
14783 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
14785 return {};
14786 }
14787 return Dim;
14788}
14789
14790ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
14791 ExprResult CallResult) {
14792 if (!getLangOpts().MatrixTypes) {
14793 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
14794 return ExprError();
14795 }
14796
14797 if (checkArgCount(TheCall, 4))
14798 return ExprError();
14799
14800 unsigned PtrArgIdx = 0;
14801 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
14802 Expr *RowsExpr = TheCall->getArg(1);
14803 Expr *ColumnsExpr = TheCall->getArg(2);
14804 Expr *StrideExpr = TheCall->getArg(3);
14805
14806 bool ArgError = false;
14807
14808 // Check pointer argument.
14809 {
14811 if (PtrConv.isInvalid())
14812 return PtrConv;
14813 PtrExpr = PtrConv.get();
14814 TheCall->setArg(0, PtrExpr);
14815 if (PtrExpr->isTypeDependent()) {
14816 TheCall->setType(Context.DependentTy);
14817 return TheCall;
14818 }
14819 }
14820
14821 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
14822 QualType ElementTy;
14823 if (!PtrTy) {
14824 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
14825 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
14826 ArgError = true;
14827 } else {
14828 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
14829
14831 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
14832 << PtrArgIdx + 1 << /* pointer to element ty*/ 2
14833 << PtrExpr->getType();
14834 ArgError = true;
14835 }
14836 }
14837
14838 // Apply default Lvalue conversions and convert the expression to size_t.
14839 auto ApplyArgumentConversions = [this](Expr *E) {
14841 if (Conv.isInvalid())
14842 return Conv;
14843
14844 return tryConvertExprToType(Conv.get(), Context.getSizeType());
14845 };
14846
14847 // Apply conversion to row and column expressions.
14848 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
14849 if (!RowsConv.isInvalid()) {
14850 RowsExpr = RowsConv.get();
14851 TheCall->setArg(1, RowsExpr);
14852 } else
14853 RowsExpr = nullptr;
14854
14855 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
14856 if (!ColumnsConv.isInvalid()) {
14857 ColumnsExpr = ColumnsConv.get();
14858 TheCall->setArg(2, ColumnsExpr);
14859 } else
14860 ColumnsExpr = nullptr;
14861
14862 // If any part of the result matrix type is still pending, just use
14863 // Context.DependentTy, until all parts are resolved.
14864 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
14865 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
14866 TheCall->setType(Context.DependentTy);
14867 return CallResult;
14868 }
14869
14870 // Check row and column dimensions.
14871 std::optional<unsigned> MaybeRows;
14872 if (RowsExpr)
14873 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
14874
14875 std::optional<unsigned> MaybeColumns;
14876 if (ColumnsExpr)
14877 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
14878
14879 // Check stride argument.
14880 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
14881 if (StrideConv.isInvalid())
14882 return ExprError();
14883 StrideExpr = StrideConv.get();
14884 TheCall->setArg(3, StrideExpr);
14885
14886 if (MaybeRows) {
14887 if (std::optional<llvm::APSInt> Value =
14888 StrideExpr->getIntegerConstantExpr(Context)) {
14889 uint64_t Stride = Value->getZExtValue();
14890 if (Stride < *MaybeRows) {
14891 Diag(StrideExpr->getBeginLoc(),
14892 diag::err_builtin_matrix_stride_too_small);
14893 ArgError = true;
14894 }
14895 }
14896 }
14897
14898 if (ArgError || !MaybeRows || !MaybeColumns)
14899 return ExprError();
14900
14901 TheCall->setType(
14902 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
14903 return CallResult;
14904}
14905
14906ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
14907 ExprResult CallResult) {
14908 if (checkArgCount(TheCall, 3))
14909 return ExprError();
14910
14911 unsigned PtrArgIdx = 1;
14912 Expr *MatrixExpr = TheCall->getArg(0);
14913 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
14914 Expr *StrideExpr = TheCall->getArg(2);
14915
14916 bool ArgError = false;
14917
14918 {
14919 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
14920 if (MatrixConv.isInvalid())
14921 return MatrixConv;
14922 MatrixExpr = MatrixConv.get();
14923 TheCall->setArg(0, MatrixExpr);
14924 }
14925 if (MatrixExpr->isTypeDependent()) {
14926 TheCall->setType(Context.DependentTy);
14927 return TheCall;
14928 }
14929
14930 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
14931 if (!MatrixTy) {
14932 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
14933 << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
14934 ArgError = true;
14935 }
14936
14937 {
14939 if (PtrConv.isInvalid())
14940 return PtrConv;
14941 PtrExpr = PtrConv.get();
14942 TheCall->setArg(1, PtrExpr);
14943 if (PtrExpr->isTypeDependent()) {
14944 TheCall->setType(Context.DependentTy);
14945 return TheCall;
14946 }
14947 }
14948
14949 // Check pointer argument.
14950 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
14951 if (!PtrTy) {
14952 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
14953 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
14954 ArgError = true;
14955 } else {
14956 QualType ElementTy = PtrTy->getPointeeType();
14957 if (ElementTy.isConstQualified()) {
14958 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
14959 ArgError = true;
14960 }
14961 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
14962 if (MatrixTy &&
14963 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
14964 Diag(PtrExpr->getBeginLoc(),
14965 diag::err_builtin_matrix_pointer_arg_mismatch)
14966 << ElementTy << MatrixTy->getElementType();
14967 ArgError = true;
14968 }
14969 }
14970
14971 // Apply default Lvalue conversions and convert the stride expression to
14972 // size_t.
14973 {
14974 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
14975 if (StrideConv.isInvalid())
14976 return StrideConv;
14977
14978 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
14979 if (StrideConv.isInvalid())
14980 return StrideConv;
14981 StrideExpr = StrideConv.get();
14982 TheCall->setArg(2, StrideExpr);
14983 }
14984
14985 // Check stride argument.
14986 if (MatrixTy) {
14987 if (std::optional<llvm::APSInt> Value =
14988 StrideExpr->getIntegerConstantExpr(Context)) {
14989 uint64_t Stride = Value->getZExtValue();
14990 if (Stride < MatrixTy->getNumRows()) {
14991 Diag(StrideExpr->getBeginLoc(),
14992 diag::err_builtin_matrix_stride_too_small);
14993 ArgError = true;
14994 }
14995 }
14996 }
14997
14998 if (ArgError)
14999 return ExprError();
15000
15001 return CallResult;
15002}
15003
15005 const NamedDecl *Callee) {
15006 // This warning does not make sense in code that has no runtime behavior.
15008 return;
15009
15010 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
15011
15012 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
15013 return;
15014
15015 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
15016 // all TCBs the callee is a part of.
15017 llvm::StringSet<> CalleeTCBs;
15018 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
15019 CalleeTCBs.insert(A->getTCBName());
15020 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
15021 CalleeTCBs.insert(A->getTCBName());
15022
15023 // Go through the TCBs the caller is a part of and emit warnings if Caller
15024 // is in a TCB that the Callee is not.
15025 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
15026 StringRef CallerTCB = A->getTCBName();
15027 if (CalleeTCBs.count(CallerTCB) == 0) {
15028 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
15029 << Callee << CallerTCB;
15030 }
15031 }
15032}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3443
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:84
Defines the Diagnostic-related interfaces.
const Decl * D
Expr * E
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:1172
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.
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:51
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.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis functions specific to BPF.
static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout unions are layout-compatible.
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 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 checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind, bool RequireConstant=false)
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 builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall)
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 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 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 CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant, Expr *Other, const llvm::APSInt &Value, bool RhsConstant)
static AbsoluteValueKind getAbsoluteValueKind(QualType T)
static bool isKnownToHaveUnsignedValue(Expr *E)
static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall)
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 BuiltinPreserveAI(Sema &S, CallExpr *TheCall)
Check the number of arguments and set the result type to the argument type.
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 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
Check conversion of given expression to boolean.
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 bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, ASTContext &Context)
static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check)
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 IsSameCharType(QualType T1, QualType T2)
static bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Checks if a the given expression evaluates to null.
static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall)
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 bool CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall, ArrayRef< llvm::Triple::ArchType > SupportedArchs)
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 std::pair< const ValueDecl *, CharUnits > findConstantBaseAndOffset(Sema &S, Expr *E)
static void diagnoseArrayStarInParamType(Sema &S, QualType PType, SourceLocation Loc)
static std::optional< IntRange > TryGetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, bool InConstantContext, bool Approximate)
Attempts to estimate an approximate range for the given integer expression.
static unsigned changeAbsFunction(unsigned AbsKind, AbsoluteValueKind ValueKind)
static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool &ICContext)
static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, Expr *RHS, bool isProperty)
static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall)
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 isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2)
Check if two types are layout-compatible in C++11 sense.
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 llvm::SmallPtrSet< MemberKind *, 1 > CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty)
static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static void CheckNonNullArguments(Sema &S, const NamedDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< const Expr * > Args, SourceLocation CallSiteLoc)
static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction)
static analyze_format_string::ArgType::MatchKind handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match, DiagnosticsEngine &Diags, SourceLocation Loc)
static bool referToTheSameDecl(const Expr *E1, const Expr *E2)
Check if two expressions refer to the same declaration.
#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 std::optional< unsigned > getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S)
static bool convertArgumentToType(Sema &S, Expr *&Value, QualType Ty)
static ExprResult PointerAuthStringDiscriminator(Sema &S, CallExpr *Call)
static bool ProcessFormatStringLiteral(const Expr *FormatExpr, StringRef &FormatStrRef, size_t &StrLen, ASTContext &Context)
static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout structs are layout-compatible.
static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall)
Checks that __builtin_popcountg was called with a single argument, which is an unsigned integer.
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 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 ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call, PointerAuthOpKind OpKind, bool RequireConstant)
static bool IsEnumConstOrFromMacro(Sema &S, Expr *E)
static bool checkBuiltinVerboseTrap(CallExpr *Call, Sema &S)
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 QualType getAbsoluteValueArgumentType(ASTContext &Context, unsigned AbsType)
MathCheck
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 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE)
Return true if ICE is an implicit argument promotion of an arithmetic type.
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 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)
static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall)
static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, ParmVarDecl **LastParam=nullptr)
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis functions specific to Hexagon.
This file declares semantic analysis functions specific to LoongArch.
This file declares semantic analysis functions specific to MIPS.
This file declares semantic analysis functions specific to NVPTX.
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
This file declares semantic analysis for Objective-C.
This file declares semantic analysis routines for OpenCL.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis functions specific to SystemZ.
This file declares semantic analysis functions specific to Wasm.
This file declares semantic analysis functions specific to X86.
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.
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
#define bool
Definition: amdgpuintrin.h:20
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
APSInt & getInt()
Definition: APValue.h:465
bool isVector() const
Definition: APValue.h:449
APSInt & getComplexIntImag()
Definition: APValue.h:503
bool isComplexInt() const
Definition: APValue.h:446
bool isFloat() const
Definition: APValue.h:444
bool isComplexFloat() const
Definition: APValue.h:447
APValue & getVectorElt(unsigned I)
Definition: APValue.h:539
unsigned getVectorLength() const
Definition: APValue.h:547
bool isLValue() const
Definition: APValue.h:448
bool isInt() const
Definition: APValue.h:443
APSInt & getComplexIntReal()
Definition: APValue.h:495
APFloat & getComplexFloatImag()
Definition: APValue.h:519
APFloat & getComplexFloatReal()
Definition: APValue.h:511
APFloat & getFloat()
Definition: APValue.h:479
bool isAddrLabelDiff() const
Definition: APValue.h:454
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2915
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.
unsigned getIntWidth(QualType T) 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
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:2716
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2732
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
Definition: ASTContext.h:1187
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:1188
IdentifierTable & Idents
Definition: ASTContext.h:680
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:682
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:1161
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:800
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:1162
CanQualType IntTy
Definition: ASTContext.h:1169
TypeInfoChars getTypeInfoInChars(const Type *T) const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:733
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:2763
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:2482
CanQualType BuiltinFnTy
Definition: ASTContext.h:1190
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1160
CanQualType UnsignedIntTy
Definition: ASTContext.h:1170
QualType getExceptionObjectType(QualType T) const
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1170
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:1681
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
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:799
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 ...
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.
@ GE_None
No error.
Definition: ASTContext.h:2384
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:2486
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:4224
Expr * getCond() const
getCond - Return the expression representing the condition for the ?: operator.
Definition: Expr.h:4402
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition: Expr.h:4408
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition: Expr.h:4414
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
This class represents BOTH the OpenMP Array Section and OpenACC 'subarray', with a boolean differenti...
Definition: Expr.h:6986
Expr * getBase()
Get base of the array section.
Definition: Expr.h:7052
Expr * getLowerBound()
Get lower bound of array section.
Definition: Expr.h:7056
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2718
SourceLocation getRBracketLoc() const
Definition: Expr.h:2766
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition: Expr.h:2747
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3577
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3591
QualType getElementType() const
Definition: Type.h:3589
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition: Expr.h:6678
std::unique_ptr< AtomicScopeModel > getScopeModel() const
Get atomic scope model.
Definition: Expr.h:6830
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:6796
Attr - This represents one attribute.
Definition: Attr.h:43
const char * getSpelling() const
Type source information for an attributed type.
Definition: TypeLoc.h:875
const T * getAttrAs()
Definition: TypeLoc.h:905
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition: TypeLoc.h:889
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6556
ConceptDecl * getTypeConstraintConcept() const
Definition: Type.h:6571
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3909
static bool isLogicalOp(Opcode Opc)
Definition: Expr.h:4042
Expr * getLHS() const
Definition: Expr.h:3959
SourceLocation getExprLoc() const
Definition: Expr.h:3950
Expr * getRHS() const
Definition: Expr.h:3961
bool isEqualityOp() const
Definition: Expr.h:4007
static bool isAdditiveOp(Opcode Opc)
Definition: Expr.h:3995
Opcode getOpcode() const
Definition: Expr.h:3954
A fixed int type of a specified bitwidth.
Definition: Type.h:7814
Pointer to a block type.
Definition: Type.h:3408
This class is used for builtin types like 'int'.
Definition: Type.h:3034
bool isInteger() const
Definition: Type.h:3095
bool isFloatingPoint() const
Definition: Type.h:3107
bool isSignedInteger() const
Definition: Type.h:3099
bool isUnsignedInteger() const
Definition: Type.h:3103
Kind getKind() const
Definition: Type.h:3082
bool isAuxBuiltinID(unsigned ID) const
Return true if builtin ID belongs to AuxTarget.
Definition: Builtins.h:260
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:220
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:266
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:109
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition: Expr.h:3840
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition: ExprCXX.h:1628
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition: ExprCXX.h:1686
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2817
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
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:4960
ArrayRef< Expr * > getInitExprs()
Definition: ExprCXX.h:5000
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:1237
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:565
bool isDynamicClass() const
Definition: DeclCXX.h:586
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2874
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3068
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:3081
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1638
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition: Expr.cpp:1577
arg_iterator arg_begin()
Definition: Expr.h:3121
arg_iterator arg_end()
Definition: Expr.h:3124
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3047
bool isCallToStdMove() const
Definition: Expr.cpp:3541
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:1655
Expr * getCallee()
Definition: Expr.h:3024
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:3055
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition: Expr.h:3158
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:3058
arg_range arguments()
Definition: Expr.h:3116
SourceLocation getRParenLoc() const
Definition: Expr.h:3194
Decl * getCalleeDecl()
Definition: Expr.h:3041
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:1582
void setCallee(Expr *F)
Definition: Expr.h:3026
QualType withConst() const
Retrieves a version of this type with const applied.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:84
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3547
path_iterator path_begin()
Definition: Expr.h:3617
CastKind getCastKind() const
Definition: Expr.h:3591
path_iterator path_end()
Definition: Expr.h:3618
Expr * getSubExpr()
Definition: Expr.h:3597
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
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
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:3145
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:4171
Declaration of a C++20 concept.
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4262
Expr * getLHS() const
Definition: Expr.h:4296
Expr * getRHS() const
Definition: Expr.h:4297
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3615
QualType desugar() const
Definition: Type.h:3716
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3671
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4232
static constexpr unsigned getMaxElementsPerDimension()
Returns the maximum number of elements per dimension.
Definition: Type.h:4266
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition: Type.h:4261
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition: Expr.h:4582
Represents an expression that might suspend coroutine execution; either a co_await or co_yield expres...
Definition: ExprCXX.h:5077
Expr * getOperand() const
Definition: ExprCXX.h:5146
child_range children()
Definition: ExprCXX.h:5176
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition: Type.h:3306
DynamicCountPointerKind getKind() const
Definition: Type.h:3336
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
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:2089
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1334
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2349
bool isFunctionOrMethod() const
Definition: DeclBase.h:2141
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
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:1352
ValueDecl * getDecl()
Definition: Expr.h:1333
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition: Expr.h:1457
SourceLocation getLocation() const
Definition: Expr.h:1341
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isInStdNamespace() const
Definition: DeclBase.cpp:422
T * getAttr() const
Definition: DeclBase.h:576
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition: DeclBase.cpp:534
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
Definition: DeclBase.cpp:1179
bool isInvalidDecl() const
Definition: DeclBase.h:591
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:562
SourceLocation getLocation() const
Definition: DeclBase.h:442
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:434
bool hasAttr() const
Definition: DeclBase.h:580
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:430
The name of a declaration.
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1977
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:764
RAII class that determines when any errors have occurred between the time the instance was created an...
Definition: Diagnostic.h:1064
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Definition: Diagnostic.h:1075
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:231
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:939
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3277
Represents an enum.
Definition: Decl.h:3847
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition: Decl.h:4044
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4066
TypeSourceInfo * getIntegerTypeSourceInfo() const
Return the type source info for the underlying integer type, if no type source info exists,...
Definition: Decl.h:4023
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4007
unsigned getNumPositiveBits() const
Returns the width in bits required to store all the non-negative enumerators of this enum.
Definition: Decl.h:4033
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6098
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:3095
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:3090
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3078
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:3086
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:4124
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:826
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:830
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:3082
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:3587
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
std::optional< std::string > tryEvaluateString(ASTContext &Ctx) const
If the current Expr can be evaluated to a pointer to a null-terminated constant string,...
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3070
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition: Expr.h:797
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition: Expr.h:806
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:809
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition: Expr.h:799
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:3963
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:4126
Represents a member of a struct/union/class.
Definition: Decl.h:3033
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3124
unsigned getBitWidthValue(const ASTContext &Ctx) const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4602
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3250
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition: Decl.h:3137
const FieldDecl * findCountedByField() const
Find the FieldDecl specified in a FAM's "counted_by" attribute.
Definition: Decl.cpp:4705
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:75
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:138
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:127
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:101
llvm::APFloat getValue() const
Definition: Expr.h:1652
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition: Stmt.h:2808
Represents a function declaration or definition.
Definition: Decl.h:1935
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition: Decl.cpp:4409
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2672
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3723
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3638
param_iterator param_end()
Definition: Decl.h:2662
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3741
QualType getReturnType() const
Definition: Decl.h:2720
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2649
param_iterator param_begin()
Definition: Decl.h:2661
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3096
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4188
bool isStatic() const
Definition: Decl.h:2804
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:4003
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3989
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3702
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5102
unsigned getNumParams() const
Definition: Type.h:5355
QualType getParamType(unsigned i) const
Definition: Type.h:5357
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5479
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5366
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.h:5474
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5362
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition: Type.h:4613
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition: Type.h:4609
QualType getReturnType() const
Definition: Type.h:4643
@ SME_PStateSMEnabledMask
Definition: Type.h:4587
@ SME_PStateSMCompatibleMask
Definition: Type.h:4588
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:3724
Describes an C or C++ initializer list.
Definition: Expr.h:5088
ArrayRef< Expr * > inits()
Definition: Expr.h:5128
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:973
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:499
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:1023
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:1059
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:498
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:1106
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:849
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:568
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:634
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:4217
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3236
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3319
Expr * getBase() const
Definition: Expr.h:3313
bool isArrow() const
Definition: Expr.h:3420
This represents a decl that may have a name.
Definition: Decl.h:253
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:280
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
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:1919
Represent a C++ namespace.
Definition: Decl.h:551
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:1591
bool hasLeadingEmptyMacro() const
Definition: Stmt.h:1605
SourceLocation getSemiLoc() const
Definition: Stmt.h:1602
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
QualType getType() const
Definition: DeclObjC.h:803
ObjCPropertyAttribute::Kind getPropertyAttributesAsWritten() const
Definition: DeclObjC.h:826
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition: DeclObjC.h:814
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition: ExprObjC.h:617
ObjCPropertyDecl * getExplicitProperty() const
Definition: ExprObjC.h:706
bool isImplicitProperty() const
Definition: ExprObjC.h:703
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:1173
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:255
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2170
Represents a parameter to a function.
Definition: Decl.h:1725
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
QualType getPointeeType() const
Definition: Type.h:3208
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6546
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition: Expr.cpp:4989
A (possibly-)qualified type.
Definition: Type.h:929
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2796
PrimitiveDefaultInitializeKind
Definition: Type.h:1452
QualType withoutLocalFastQualifiers() const
Definition: Type.h:1209
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7931
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8057
bool isConstant(const ASTContext &Ctx) const
Definition: Type.h:1089
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7971
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1433
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
Definition: Type.h:7983
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8025
void removeLocalVolatile()
Definition: Type.h:8047
void removeLocalConst()
Definition: Type.h:8039
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8004
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:8052
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1437
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:354
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:347
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:343
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:357
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:360
bool hasUnaligned() const
Definition: Type.h:504
Represents a struct/union/class.
Definition: Decl.h:4148
field_range fields() const
Definition: Decl.h:4354
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6072
RecordDecl * getDecl() const
Definition: Type.h:6082
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
bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaAMDGPU.cpp:25
bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaARM.cpp:976
@ ArmStreaming
Intrinsic is only available in normal mode.
Definition: SemaARM.h:37
@ ArmStreamingCompatible
Intrinsic is only available in Streaming-SVE mode.
Definition: SemaARM.h:38
bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaARM.cpp:1054
bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaBPF.cpp:111
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:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckLoongArchBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaMIPS.cpp:25
bool CheckNVPTXBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaNVPTX.cpp:21
void checkArrayLiteral(QualType TargetType, ObjCArrayLiteral *ArrayLiteral)
Check an Objective-C array literal being converted to the given target type.
Definition: SemaObjC.cpp:2357
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
bool isSignedCharBool(QualType Ty)
Definition: SemaObjC.cpp:2308
void adornBoolConversionDiagWithTernaryFixit(Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder)
Definition: SemaObjC.cpp:2313
void DiagnoseCStringFormatDirectiveInCFAPI(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...
Definition: SemaObjC.cpp:2271
void checkDictionaryLiteral(QualType TargetType, ObjCDictionaryLiteral *DictionaryLiteral)
Check an Objective-C dictionary literal being converted to the given target type.
Definition: SemaObjC.cpp:2382
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: SemaObjC.h:591
bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaPPC.cpp:96
void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg)
Definition: SemaPPC.cpp:30
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc)
Definition: SemaPPC.cpp:259
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaRISCV.cpp:552
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaSystemZ.cpp:24
bool CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaWasm.cpp:219
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaX86.cpp:687
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:463
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:14555
SemaAMDGPU & AMDGPU()
Definition: Sema.h:1045
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:12636
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:731
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
Definition: Sema.cpp:2486
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8983
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:8991
@ LookupAnyName
Look up any declaration with any name.
Definition: Sema.h:9028
VariadicCallType
Definition: Sema.h:2308
@ VariadicDoesNotApply
Definition: Sema.h:2313
@ VariadicFunction
Definition: Sema.h:2309
@ VariadicConstructor
Definition: Sema.h:2312
@ VariadicBlock
Definition: Sema.h:2310
bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount)
Checks that a call expression's argument count is at most the desired number.
bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum)
Returns true if the argument consists of one contiguous run of 1s with any number of 0s on either sid...
bool BuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum)
BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a constant expression representing ...
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.
bool BuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, unsigned Multiple)
BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr TheCall is a constant expr...
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
bool FormatStringHasSArg(const StringLiteral *FExpr)
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:1557
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...
bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, unsigned ArgBits)
BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is a constant expression represen...
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...
SemaHexagon & Hexagon()
Definition: Sema.h:1080
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:1568
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition: SemaExpr.cpp:784
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
SemaX86 & X86()
Definition: Sema.h:1165
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
Definition: SemaExpr.cpp:1042
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
Definition: SemaExpr.cpp:4998
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:14159
ASTContext & Context
Definition: Sema.h:908
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:528
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...
void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC, bool *ICContext=nullptr, bool IsListInit=false)
SemaObjC & ObjC()
Definition: Sema.h:1110
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:752
ASTContext & getASTContext() const
Definition: Sema.h:531
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:15777
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:690
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition: Sema.h:2142
bool BuiltinVectorToScalarMath(CallExpr *TheCall)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:816
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
AtomicArgumentOrder
Definition: Sema.h:2250
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:81
bool IsLayoutCompatible(QualType T1, QualType T2) const
const LangOptions & getLangOpts() const
Definition: Sema.h:524
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
Definition: SemaType.cpp:9057
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange)
CheckCastAlign - Implements -Wcast-align, which warns when a pointer cast increases the alignment req...
SemaBPF & BPF()
Definition: Sema.h:1060
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
Definition: SemaExpr.cpp:5710
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:6475
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:906
static const uint64_t MaximumAlignment
Definition: Sema.h:839
bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall)
SemaHLSL & HLSL()
Definition: Sema.h:1075
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
SemaMIPS & MIPS()
Definition: Sema.h:1095
SemaRISCV & RISCV()
Definition: Sema.h:1140
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.
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:6473
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition: Sema.cpp:1580
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:936
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op)
Definition: SemaCast.cpp:3351
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:939
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:2228
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:2142
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:640
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
void CheckTCBEnforcement(const SourceLocation CallExprLoc, const NamedDecl *Callee)
Enforce the bounds of a TCB CheckTCBEnforcement - Enforces that every function in a named TCB only di...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1043
bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount)
Checks that a call expression's argument count is at least the desired number.
@ VAK_Invalid
Definition: Sema.h:7533
@ VAK_Valid
Definition: Sema.h:7529
@ VAK_ValidInCXX11
Definition: Sema.h:7530
@ VAK_MSVCUndefined
Definition: Sema.h:7532
@ VAK_Undefined
Definition: Sema.h:7531
SemaOpenCL & OpenCL()
Definition: Sema.h:1120
FormatArgumentPassingKind
Definition: Sema.h:2152
@ FAPK_Fixed
Definition: Sema.h:2153
@ FAPK_Variadic
Definition: Sema.h:2154
@ FAPK_VAList
Definition: Sema.h:2155
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:7770
@ ACK_Comparison
A comparison.
Definition: Sema.h:7398
bool BuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result)
BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr TheCall is a constant expression.
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20964
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:13483
SourceManager & getSourceManager() const
Definition: Sema.h:529
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
bool BuiltinElementwiseTernaryMath(CallExpr *TheCall, bool CheckForFloatArgs=true)
bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount, unsigned MaxArgCount)
Checks that a call expression's argument count is in the desired range.
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:20245
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 BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum, unsigned ArgBits)
BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of TheCall is a constant expression re...
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:216
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:2144
bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount)
Checks that a call expression's argument count is the desired number.
ExprResult BuiltinShuffleVector(CallExpr *TheCall)
BuiltinShuffleVector - Handle __builtin_shufflevector.
QualType GetSignedVectorType(QualType V)
Return a signed ext_vector_type that is of identical size and number of elements.
Definition: SemaExpr.cpp:12683
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
SemaPPC & PPC()
Definition: Sema.h:1130
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9068
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:871
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
SemaSystemZ & SystemZ()
Definition: Sema.h:1155
SourceManager & SourceMgr
Definition: Sema.h:911
DiagnosticsEngine & Diags
Definition: Sema.h:910
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9718
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:997
FormatStringType
Definition: Sema.h:2181
@ FST_NSString
Definition: Sema.h:2184
@ FST_Syslog
Definition: Sema.h:2191
@ FST_Unknown
Definition: Sema.h:2192
@ FST_Strftime
Definition: Sema.h:2185
@ FST_Printf
Definition: Sema.h:2183
@ FST_FreeBSDKPrintf
Definition: Sema.h:2188
@ FST_Scanf
Definition: Sema.h:2182
@ FST_Strfmon
Definition: Sema.h:2186
@ FST_OSLog
Definition: Sema.h:2190
@ FST_Kprintf
Definition: Sema.h:2187
@ FST_OSTrace
Definition: Sema.h:2189
SemaNVPTX & NVPTX()
Definition: Sema.h:1105
bool BuiltinVectorMath(CallExpr *TheCall, QualType &Res, bool FPOnly=false)
void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction, const Expr *ThisArg, ArrayRef< const Expr * > Args)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:562
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:18078
@ AbstractParamType
Definition: Sema.h:5751
bool BuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High, bool RangeIsError=true)
BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr TheCall is a constant express...
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.
SemaLoongArch & LoongArch()
Definition: Sema.h:1085
@ 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.
SemaWasm & Wasm()
Definition: Sema.h:1160
SemaARM & ARM()
Definition: Sema.h:1050
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...
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef< const Expr * > Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType)
Handles the checks for format strings, non-POD arguments to vararg functions, NULL arguments passed t...
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition: Expr.h:4514
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:357
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:294
StmtClass getStmtClass() const
Definition: Stmt.h:1380
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:333
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:345
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1959
bool isUTF8() const
Definition: Expr.h:1904
bool isWide() const
Definition: Expr.h:1903
bool isPascal() const
Definition: Expr.h:1908
unsigned getLength() const
Definition: Expr.h:1895
StringLiteralKind getKind() const
Definition: Expr.h:1898
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:1325
bool isUTF32() const
Definition: Expr.h:1906
unsigned getByteLength() const
Definition: Expr.h:1894
StringRef getString() const
Definition: Expr.h:1855
bool isUTF16() const
Definition: Expr.h:1905
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.h:1960
bool isOrdinary() const
Definition: Expr.h:1902
unsigned getCharByteWidth() const
Definition: Expr.h:1896
bool isUnion() const
Definition: Decl.h:3770
Exposes information about the current target.
Definition: TargetInfo.h:220
virtual bool validatePointerAuthKey(const llvm::APSInt &value) const
Determine whether the given pointer-authentication key is valid.
Definition: TargetInfo.cpp:956
virtual bool supportsCpuSupports() const
Definition: TargetInfo.h:1524
virtual bool validateCpuIs(StringRef Name) const
Definition: TargetInfo.h:1540
virtual bool supportsCpuInit() const
Definition: TargetInfo.h:1526
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1262
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:1002
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
Definition: TargetInfo.cpp:286
IntType getSizeType() const
Definition: TargetInfo.h:377
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1530
virtual bool supportsCpuIs() const
Definition: TargetInfo.h:1525
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:795
virtual bool checkArithmeticFenceSupported() const
Controls if __arithmetic_fence is supported in the targeted backend.
Definition: TargetInfo.h:1679
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1493
virtual bool hasSjLjLowering() const
Controls if __builtin_longjmp / __builtin_setjmp can be lowered to llvm.eh.sjlj.longjmp / llvm....
Definition: TargetInfo.h:1728
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
Definition: DeclTemplate.h:271
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
const Type * getTypeForDecl() const
Definition: Decl.h:3395
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
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2715
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:5797
A container of type source information.
Definition: Type.h:7902
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:7913
The base class of the type hierarchy.
Definition: Type.h:1828
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isBlockPointerType() const
Definition: Type.h:8200
bool isVoidType() const
Definition: Type.h:8510
bool isBooleanType() const
Definition: Type.h:8638
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8688
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:773
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2180
bool isFloat16Type() const
Definition: Type.h:8519
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2251
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2105
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8668
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:2055
bool isVoidPointerType() const
Definition: Type.cpp:698
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2386
bool isArrayType() const
Definition: Type.h:8258
bool isCharType() const
Definition: Type.cpp:2123
bool isFunctionPointerType() const
Definition: Type.h:8226
bool isPointerType() const
Definition: Type.h:8186
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8550
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8800
bool isReferenceType() const
Definition: Type.h:8204
bool isEnumeralType() const
Definition: Type.h:8290
bool isScalarType() const
Definition: Type.h:8609
bool isVariableArrayType() const
Definition: Type.h:8270
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2554
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2092
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8625
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2270
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2593
bool isBitIntType() const
Definition: Type.h:8424
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8479
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8282
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool isAnyComplexType() const
Definition: Type.h:8294
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8563
bool isHalfType() const
Definition: Type.h:8514
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2220
QualType getCanonicalTypeInternal() const
Definition: Type.h:2989
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2501
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8681
bool isMemberPointerType() const
Definition: Type.h:8240
bool isAtomicType() const
Definition: Type.h:8341
bool isFunctionProtoType() const
Definition: Type.h:2535
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition: Type.cpp:3018
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2724
bool isObjCObjectType() const
Definition: Type.h:8332
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8786
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8644
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2446
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
bool isFunctionType() const
Definition: Type.h:8182
bool isObjCObjectPointerType() const
Definition: Type.h:8328
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition: Type.cpp:2292
bool isStructureOrClassType() const
Definition: Type.cpp:690
bool isVectorType() const
Definition: Type.h:8298
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2300
bool isFloatingType() const
Definition: Type.cpp:2283
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:2230
bool isAnyPointerType() const
Definition: Type.h:8194
TypeClass getTypeClass() const
Definition: Type.h:2341
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:2367
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
bool isNullPtrType() const
Definition: Type.h:8543
bool isRecordType() const
Definition: Type.h:8286
bool isObjCRetainableType() const
Definition: Type.cpp:5028
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4763
bool isUnionType() const
Definition: Type.cpp:704
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2513
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition: Type.cpp:2581
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1920
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3413
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2622
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2232
Expr * getSubExpr() const
Definition: Expr.h:2277
Opcode getOpcode() const
Definition: Expr.h:2272
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:2354
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:3338
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
QualType getType() const
Definition: Decl.h:682
Represents a variable declaration or definition.
Definition: Decl.h:882
Represents a GCC generic vector type.
Definition: Type.h:4034
unsigned getNumElements() const
Definition: Type.h:4049
WhileStmt - This represents a 'while' stmt.
Definition: Stmt.h:2611
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 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.
Definition: CNFFormula.h:35
@ 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:1179
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1157
bool LE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1171
bool InRange(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1198
bool Cast(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2181
bool EQ(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1126
bool GE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1186
void checkCaptureByLifetime(Sema &SemaRef, const CapturingEntity &Entity, Expr *Init)
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.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ 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:149
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:151
BinaryOperatorKind
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ SC_Register
Definition: Specifiers.h:257
SemaARM::ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD)
Definition: SemaARM.cpp:543
@ 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.
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:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
for(const auto &A :T->param_types())
const FunctionProtoType * T
Expr * IgnoreImplicitAsWrittenSingleStep(Expr *E)
Definition: IgnoreExpr.h:137
StringLiteralKind
Definition: Expr.h:1749
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:278
@ CC_Win64
Definition: Specifiers.h:285
@ CC_C
Definition: Specifiers.h:279
@ CC_X86_64SysV
Definition: Specifiers.h:286
@ Generic
not a target-specific vector type
U cast(CodeGen::Address addr)
Definition: Address.h:325
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Other
Other implicit parameter.
@ AS_public
Definition: Specifiers.h:124
unsigned long uint64_t
long int64_t
#define false
Definition: stdbool.h:26
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:5187
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:95
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:12653
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:12770
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition: Sema.h:12796
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition: Sema.h:12786
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition: Sema.h:12751
FormatArgumentPassingKind ArgPassingKind
Definition: Sema.h:2163
#define log2(__x)
Definition: tgmath.h:970