clang 22.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"
18#include "clang/AST/Attr.h"
20#include "clang/AST/CharUnits.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclObjC.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
29#include "clang/AST/ExprObjC.h"
32#include "clang/AST/NSAPI.h"
36#include "clang/AST/Stmt.h"
39#include "clang/AST/Type.h"
40#include "clang/AST/TypeLoc.h"
46#include "clang/Basic/LLVM.h"
57#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
59#include "clang/Sema/Lookup.h"
61#include "clang/Sema/Scope.h"
63#include "clang/Sema/Sema.h"
65#include "clang/Sema/SemaARM.h"
66#include "clang/Sema/SemaBPF.h"
68#include "clang/Sema/SemaHLSL.h"
71#include "clang/Sema/SemaMIPS.h"
73#include "clang/Sema/SemaObjC.h"
75#include "clang/Sema/SemaPPC.h"
79#include "clang/Sema/SemaWasm.h"
80#include "clang/Sema/SemaX86.h"
81#include "llvm/ADT/APFloat.h"
82#include "llvm/ADT/APInt.h"
83#include "llvm/ADT/APSInt.h"
84#include "llvm/ADT/ArrayRef.h"
85#include "llvm/ADT/DenseMap.h"
86#include "llvm/ADT/FoldingSet.h"
87#include "llvm/ADT/STLExtras.h"
88#include "llvm/ADT/STLForwardCompat.h"
89#include "llvm/ADT/SmallBitVector.h"
90#include "llvm/ADT/SmallPtrSet.h"
91#include "llvm/ADT/SmallString.h"
92#include "llvm/ADT/SmallVector.h"
93#include "llvm/ADT/StringExtras.h"
94#include "llvm/ADT/StringRef.h"
95#include "llvm/ADT/StringSet.h"
96#include "llvm/ADT/StringSwitch.h"
97#include "llvm/Support/AtomicOrdering.h"
98#include "llvm/Support/Compiler.h"
99#include "llvm/Support/ConvertUTF.h"
100#include "llvm/Support/ErrorHandling.h"
101#include "llvm/Support/Format.h"
102#include "llvm/Support/Locale.h"
103#include "llvm/Support/MathExtras.h"
104#include "llvm/Support/SaveAndRestore.h"
105#include "llvm/Support/raw_ostream.h"
106#include "llvm/TargetParser/RISCVTargetParser.h"
107#include "llvm/TargetParser/Triple.h"
108#include <algorithm>
109#include <cassert>
110#include <cctype>
111#include <cstddef>
112#include <cstdint>
113#include <functional>
114#include <limits>
115#include <optional>
116#include <string>
117#include <tuple>
118#include <utility>
119
120using namespace clang;
121using namespace sema;
122
124 unsigned ByteNo) const {
125 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
127}
128
129static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
131 return (A << 8) | B;
132}
133
134bool Sema::checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount) {
135 unsigned ArgCount = Call->getNumArgs();
136 if (ArgCount >= MinArgCount)
137 return false;
138
139 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
140 << 0 /*function call*/ << MinArgCount << ArgCount
141 << /*is non object*/ 0 << Call->getSourceRange();
142}
143
144bool Sema::checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount) {
145 unsigned ArgCount = Call->getNumArgs();
146 if (ArgCount <= MaxArgCount)
147 return false;
148 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_many_args_at_most)
149 << 0 /*function call*/ << MaxArgCount << ArgCount
150 << /*is non object*/ 0 << Call->getSourceRange();
151}
152
153bool Sema::checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
154 unsigned MaxArgCount) {
155 return checkArgCountAtLeast(Call, MinArgCount) ||
156 checkArgCountAtMost(Call, MaxArgCount);
157}
158
159bool Sema::checkArgCount(CallExpr *Call, unsigned DesiredArgCount) {
160 unsigned ArgCount = Call->getNumArgs();
161 if (ArgCount == DesiredArgCount)
162 return false;
163
164 if (checkArgCountAtLeast(Call, DesiredArgCount))
165 return true;
166 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
167
168 // Highlight all the excess arguments.
169 SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
170 Call->getArg(ArgCount - 1)->getEndLoc());
171
172 return Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
173 << 0 /*function call*/ << DesiredArgCount << ArgCount
174 << /*is non object*/ 0 << Range;
175}
176
178 bool HasError = false;
179
180 for (unsigned I = 0; I < Call->getNumArgs(); ++I) {
181 Expr *Arg = Call->getArg(I);
182
183 if (Arg->isValueDependent())
184 continue;
185
186 std::optional<std::string> ArgString = Arg->tryEvaluateString(S.Context);
187 int DiagMsgKind = -1;
188 // Arguments must be pointers to constant strings and cannot use '$'.
189 if (!ArgString.has_value())
190 DiagMsgKind = 0;
191 else if (ArgString->find('$') != std::string::npos)
192 DiagMsgKind = 1;
193
194 if (DiagMsgKind >= 0) {
195 S.Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg)
196 << DiagMsgKind << Arg->getSourceRange();
197 HasError = true;
198 }
199 }
200
201 return !HasError;
202}
203
205 if (Value->isTypeDependent())
206 return false;
207
208 InitializedEntity Entity =
212 if (Result.isInvalid())
213 return true;
214 Value = Result.get();
215 return false;
216}
217
218/// Check that the first argument to __builtin_annotation is an integer
219/// and the second argument is a non-wide string literal.
220static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
221 if (S.checkArgCount(TheCall, 2))
222 return true;
223
224 // First argument should be an integer.
225 Expr *ValArg = TheCall->getArg(0);
226 QualType Ty = ValArg->getType();
227 if (!Ty->isIntegerType()) {
228 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
229 << ValArg->getSourceRange();
230 return true;
231 }
232
233 // Second argument should be a constant string.
234 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
235 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
236 if (!Literal || !Literal->isOrdinary()) {
237 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
238 << StrArg->getSourceRange();
239 return true;
240 }
241
242 TheCall->setType(Ty);
243 return false;
244}
245
246static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
247 // We need at least one argument.
248 if (TheCall->getNumArgs() < 1) {
249 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
250 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
251 << TheCall->getCallee()->getSourceRange();
252 return true;
253 }
254
255 // All arguments should be wide string literals.
256 for (Expr *Arg : TheCall->arguments()) {
257 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
258 if (!Literal || !Literal->isWide()) {
259 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
260 << Arg->getSourceRange();
261 return true;
262 }
263 }
264
265 return false;
266}
267
268/// Check that the argument to __builtin_addressof is a glvalue, and set the
269/// result type to the corresponding pointer type.
270static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
271 if (S.checkArgCount(TheCall, 1))
272 return true;
273
274 ExprResult Arg(TheCall->getArg(0));
275 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
276 if (ResultType.isNull())
277 return true;
278
279 TheCall->setArg(0, Arg.get());
280 TheCall->setType(ResultType);
281 return false;
282}
283
284/// Check that the argument to __builtin_function_start is a function.
285static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
286 if (S.checkArgCount(TheCall, 1))
287 return true;
288
289 if (TheCall->getArg(0)->containsErrors())
290 return true;
291
293 if (Arg.isInvalid())
294 return true;
295
296 TheCall->setArg(0, Arg.get());
297 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
299
300 if (!FD) {
301 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
302 << TheCall->getSourceRange();
303 return true;
304 }
305
306 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
307 TheCall->getBeginLoc());
308}
309
310/// Check the number of arguments and set the result type to
311/// the argument type.
312static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
313 if (S.checkArgCount(TheCall, 1))
314 return true;
315
316 TheCall->setType(TheCall->getArg(0)->getType());
317 return false;
318}
319
320/// Check that the value argument for __builtin_is_aligned(value, alignment) and
321/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
322/// type (but not a function pointer) and that the alignment is a power-of-two.
323static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
324 if (S.checkArgCount(TheCall, 2))
325 return true;
326
327 clang::Expr *Source = TheCall->getArg(0);
328 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
329
330 auto IsValidIntegerType = [](QualType Ty) {
331 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
332 };
333 QualType SrcTy = Source->getType();
334 // We should also be able to use it with arrays (but not functions!).
335 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
336 SrcTy = S.Context.getDecayedType(SrcTy);
337 }
338 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
339 SrcTy->isFunctionPointerType()) {
340 // FIXME: this is not quite the right error message since we don't allow
341 // floating point types, or member pointers.
342 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
343 << SrcTy;
344 return true;
345 }
346
347 clang::Expr *AlignOp = TheCall->getArg(1);
348 if (!IsValidIntegerType(AlignOp->getType())) {
349 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
350 << AlignOp->getType();
351 return true;
352 }
353 Expr::EvalResult AlignResult;
354 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
355 // We can't check validity of alignment if it is value dependent.
356 if (!AlignOp->isValueDependent() &&
357 AlignOp->EvaluateAsInt(AlignResult, S.Context,
359 llvm::APSInt AlignValue = AlignResult.Val.getInt();
360 llvm::APSInt MaxValue(
361 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
362 if (AlignValue < 1) {
363 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
364 return true;
365 }
366 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
367 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
368 << toString(MaxValue, 10);
369 return true;
370 }
371 if (!AlignValue.isPowerOf2()) {
372 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
373 return true;
374 }
375 if (AlignValue == 1) {
376 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
377 << IsBooleanAlignBuiltin;
378 }
379 }
380
383 SourceLocation(), Source);
384 if (SrcArg.isInvalid())
385 return true;
386 TheCall->setArg(0, SrcArg.get());
387 ExprResult AlignArg =
389 S.Context, AlignOp->getType(), false),
390 SourceLocation(), AlignOp);
391 if (AlignArg.isInvalid())
392 return true;
393 TheCall->setArg(1, AlignArg.get());
394 // For align_up/align_down, the return type is the same as the (potentially
395 // decayed) argument type including qualifiers. For is_aligned(), the result
396 // is always bool.
397 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
398 return false;
399}
400
401static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
402 if (S.checkArgCount(TheCall, 3))
403 return true;
404
405 std::pair<unsigned, const char *> Builtins[] = {
406 { Builtin::BI__builtin_add_overflow, "ckd_add" },
407 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
408 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
409 };
410
411 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
412 const char *> &P) {
413 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
415 S.getSourceManager(), S.getLangOpts()) == P.second;
416 });
417
418 auto ValidCkdIntType = [](QualType QT) {
419 // A valid checked integer type is an integer type other than a plain char,
420 // bool, a bit-precise type, or an enumeration type.
421 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
422 return (BT->getKind() >= BuiltinType::Short &&
423 BT->getKind() <= BuiltinType::Int128) || (
424 BT->getKind() >= BuiltinType::UShort &&
425 BT->getKind() <= BuiltinType::UInt128) ||
426 BT->getKind() == BuiltinType::UChar ||
427 BT->getKind() == BuiltinType::SChar;
428 return false;
429 };
430
431 // First two arguments should be integers.
432 for (unsigned I = 0; I < 2; ++I) {
434 if (Arg.isInvalid()) return true;
435 TheCall->setArg(I, Arg.get());
436
437 QualType Ty = Arg.get()->getType();
438 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
439 if (!IsValid) {
440 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
441 << CkdOperation << Ty << Arg.get()->getSourceRange();
442 return true;
443 }
444 }
445
446 // Third argument should be a pointer to a non-const integer.
447 // IRGen correctly handles volatile, restrict, and address spaces, and
448 // the other qualifiers aren't possible.
449 {
451 if (Arg.isInvalid()) return true;
452 TheCall->setArg(2, Arg.get());
453
454 QualType Ty = Arg.get()->getType();
455 const auto *PtrTy = Ty->getAs<PointerType>();
456 if (!PtrTy ||
457 !PtrTy->getPointeeType()->isIntegerType() ||
458 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
459 PtrTy->getPointeeType().isConstQualified()) {
460 S.Diag(Arg.get()->getBeginLoc(),
461 diag::err_overflow_builtin_must_be_ptr_int)
462 << CkdOperation << Ty << Arg.get()->getSourceRange();
463 return true;
464 }
465 }
466
467 // Disallow signed bit-precise integer args larger than 128 bits to mul
468 // function until we improve backend support.
469 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
470 for (unsigned I = 0; I < 3; ++I) {
471 const auto Arg = TheCall->getArg(I);
472 // Third argument will be a pointer.
473 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
474 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
475 S.getASTContext().getIntWidth(Ty) > 128)
476 return S.Diag(Arg->getBeginLoc(),
477 diag::err_overflow_builtin_bit_int_max_size)
478 << 128;
479 }
480 }
481
482 return false;
483}
484
485namespace {
486struct BuiltinDumpStructGenerator {
487 Sema &S;
488 CallExpr *TheCall;
489 SourceLocation Loc = TheCall->getBeginLoc();
491 DiagnosticErrorTrap ErrorTracker;
492 PrintingPolicy Policy;
493
494 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
495 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
496 Policy(S.Context.getPrintingPolicy()) {
497 Policy.AnonymousTagLocations = false;
498 }
499
500 Expr *makeOpaqueValueExpr(Expr *Inner) {
501 auto *OVE = new (S.Context)
502 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
503 Inner->getObjectKind(), Inner);
504 Actions.push_back(OVE);
505 return OVE;
506 }
507
508 Expr *getStringLiteral(llvm::StringRef Str) {
510 // Wrap the literal in parentheses to attach a source location.
511 return new (S.Context) ParenExpr(Loc, Loc, Lit);
512 }
513
514 bool callPrintFunction(llvm::StringRef Format,
515 llvm::ArrayRef<Expr *> Exprs = {}) {
517 assert(TheCall->getNumArgs() >= 2);
518 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
519 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
520 Args.push_back(getStringLiteral(Format));
521 llvm::append_range(Args, Exprs);
522
523 // Register a note to explain why we're performing the call.
526 Ctx.PointOfInstantiation = Loc;
527 Ctx.CallArgs = Args.data();
528 Ctx.NumCallArgs = Args.size();
530
531 ExprResult RealCall =
532 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
533 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
534
536 if (!RealCall.isInvalid())
537 Actions.push_back(RealCall.get());
538 // Bail out if we've hit any errors, even if we managed to build the
539 // call. We don't want to produce more than one error.
540 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
541 }
542
543 Expr *getIndentString(unsigned Depth) {
544 if (!Depth)
545 return nullptr;
546
548 Indent.resize(Depth * Policy.Indentation, ' ');
549 return getStringLiteral(Indent);
550 }
551
553 return getStringLiteral(T.getAsString(Policy));
554 }
555
556 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
557 llvm::raw_svector_ostream OS(Str);
558
559 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
560 // than trying to print a single character.
561 if (auto *BT = T->getAs<BuiltinType>()) {
562 switch (BT->getKind()) {
563 case BuiltinType::Bool:
564 OS << "%d";
565 return true;
566 case BuiltinType::Char_U:
567 case BuiltinType::UChar:
568 OS << "%hhu";
569 return true;
570 case BuiltinType::Char_S:
571 case BuiltinType::SChar:
572 OS << "%hhd";
573 return true;
574 default:
575 break;
576 }
577 }
578
580 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
581 // We were able to guess how to format this.
582 if (Specifier.getConversionSpecifier().getKind() ==
583 analyze_printf::PrintfConversionSpecifier::sArg) {
584 // Wrap double-quotes around a '%s' specifier and limit its maximum
585 // length. Ideally we'd also somehow escape special characters in the
586 // contents but printf doesn't support that.
587 // FIXME: '%s' formatting is not safe in general.
588 OS << '"';
589 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
590 Specifier.toString(OS);
591 OS << '"';
592 // FIXME: It would be nice to include a '...' if the string doesn't fit
593 // in the length limit.
594 } else {
595 Specifier.toString(OS);
596 }
597 return true;
598 }
599
600 if (T->isPointerType()) {
601 // Format all pointers with '%p'.
602 OS << "%p";
603 return true;
604 }
605
606 return false;
607 }
608
609 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
610 Expr *IndentLit = getIndentString(Depth);
612 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
613 : callPrintFunction("%s", {TypeLit}))
614 return true;
615
616 return dumpRecordValue(RD, E, IndentLit, Depth);
617 }
618
619 // Dump a record value. E should be a pointer or lvalue referring to an RD.
620 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
621 unsigned Depth) {
622 // FIXME: Decide what to do if RD is a union. At least we should probably
623 // turn off printing `const char*` members with `%s`, because that is very
624 // likely to crash if that's not the active member. Whatever we decide, we
625 // should document it.
626
627 // Build an OpaqueValueExpr so we can refer to E more than once without
628 // triggering re-evaluation.
629 Expr *RecordArg = makeOpaqueValueExpr(E);
630 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
631
632 if (callPrintFunction(" {\n"))
633 return true;
634
635 // Dump each base class, regardless of whether they're aggregates.
636 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
637 for (const auto &Base : CXXRD->bases()) {
638 QualType BaseType =
639 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
640 : S.Context.getLValueReferenceType(Base.getType());
643 RecordArg);
644 if (BasePtr.isInvalid() ||
645 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
646 Depth + 1))
647 return true;
648 }
649 }
650
651 Expr *FieldIndentArg = getIndentString(Depth + 1);
652
653 // Dump each field.
654 for (auto *D : RD->decls()) {
655 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
656 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
657 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
658 continue;
659
660 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
661 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
662 getTypeString(FD->getType()),
663 getStringLiteral(FD->getName())};
664
665 if (FD->isBitField()) {
666 Format += ": %zu ";
668 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
669 FD->getBitWidthValue());
670 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
671 }
672
673 Format += "=";
674
677 CXXScopeSpec(), Loc, IFD,
678 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
680 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
682 DeclarationNameInfo(FD->getDeclName(), Loc));
683 if (Field.isInvalid())
684 return true;
685
686 auto *InnerRD = FD->getType()->getAsRecordDecl();
687 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
688 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
689 // Recursively print the values of members of aggregate record type.
690 if (callPrintFunction(Format, Args) ||
691 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
692 return true;
693 } else {
694 Format += " ";
695 if (appendFormatSpecifier(FD->getType(), Format)) {
696 // We know how to print this field.
697 Args.push_back(Field.get());
698 } else {
699 // We don't know how to print this field. Print out its address
700 // with a format specifier that a smart tool will be able to
701 // recognize and treat specially.
702 Format += "*%p";
703 ExprResult FieldAddr =
704 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
705 if (FieldAddr.isInvalid())
706 return true;
707 Args.push_back(FieldAddr.get());
708 }
709 Format += "\n";
710 if (callPrintFunction(Format, Args))
711 return true;
712 }
713 }
714
715 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
716 : callPrintFunction("}\n");
717 }
718
719 Expr *buildWrapper() {
720 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
722 TheCall->setType(Wrapper->getType());
723 TheCall->setValueKind(Wrapper->getValueKind());
724 return Wrapper;
725 }
726};
727} // namespace
728
730 if (S.checkArgCountAtLeast(TheCall, 2))
731 return ExprError();
732
733 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
734 if (PtrArgResult.isInvalid())
735 return ExprError();
736 TheCall->setArg(0, PtrArgResult.get());
737
738 // First argument should be a pointer to a struct.
739 QualType PtrArgType = PtrArgResult.get()->getType();
740 if (!PtrArgType->isPointerType() ||
741 !PtrArgType->getPointeeType()->isRecordType()) {
742 S.Diag(PtrArgResult.get()->getBeginLoc(),
743 diag::err_expected_struct_pointer_argument)
744 << 1 << TheCall->getDirectCallee() << PtrArgType;
745 return ExprError();
746 }
747 QualType Pointee = PtrArgType->getPointeeType();
748 const RecordDecl *RD = Pointee->getAsRecordDecl();
749 // Try to instantiate the class template as appropriate; otherwise, access to
750 // its data() may lead to a crash.
751 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
752 diag::err_incomplete_type))
753 return ExprError();
754 // Second argument is a callable, but we can't fully validate it until we try
755 // calling it.
756 QualType FnArgType = TheCall->getArg(1)->getType();
757 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
758 !FnArgType->isBlockPointerType() &&
759 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
760 auto *BT = FnArgType->getAs<BuiltinType>();
761 switch (BT ? BT->getKind() : BuiltinType::Void) {
762 case BuiltinType::Dependent:
763 case BuiltinType::Overload:
764 case BuiltinType::BoundMember:
765 case BuiltinType::PseudoObject:
766 case BuiltinType::UnknownAny:
767 case BuiltinType::BuiltinFn:
768 // This might be a callable.
769 break;
770
771 default:
772 S.Diag(TheCall->getArg(1)->getBeginLoc(),
773 diag::err_expected_callable_argument)
774 << 2 << TheCall->getDirectCallee() << FnArgType;
775 return ExprError();
776 }
777 }
778
779 BuiltinDumpStructGenerator Generator(S, TheCall);
780
781 // Wrap parentheses around the given pointer. This is not necessary for
782 // correct code generation, but it means that when we pretty-print the call
783 // arguments in our diagnostics we will produce '(&s)->n' instead of the
784 // incorrect '&s->n'.
785 Expr *PtrArg = PtrArgResult.get();
786 PtrArg = new (S.Context)
787 ParenExpr(PtrArg->getBeginLoc(),
788 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
789 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
790 return ExprError();
791
792 return Generator.buildWrapper();
793}
794
795static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
796 if (S.checkArgCount(BuiltinCall, 2))
797 return true;
798
799 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
800 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
801 Expr *Call = BuiltinCall->getArg(0);
802 Expr *Chain = BuiltinCall->getArg(1);
803
804 if (Call->getStmtClass() != Stmt::CallExprClass) {
805 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
806 << Call->getSourceRange();
807 return true;
808 }
809
810 auto CE = cast<CallExpr>(Call);
811 if (CE->getCallee()->getType()->isBlockPointerType()) {
812 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
813 << Call->getSourceRange();
814 return true;
815 }
816
817 const Decl *TargetDecl = CE->getCalleeDecl();
818 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
819 if (FD->getBuiltinID()) {
820 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
821 << Call->getSourceRange();
822 return true;
823 }
824
825 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
826 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
827 << Call->getSourceRange();
828 return true;
829 }
830
831 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
832 if (ChainResult.isInvalid())
833 return true;
834 if (!ChainResult.get()->getType()->isPointerType()) {
835 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
836 << Chain->getSourceRange();
837 return true;
838 }
839
840 QualType ReturnTy = CE->getCallReturnType(S.Context);
841 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
842 QualType BuiltinTy = S.Context.getFunctionType(
843 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
844 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
845
846 Builtin =
847 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
848
849 BuiltinCall->setType(CE->getType());
850 BuiltinCall->setValueKind(CE->getValueKind());
851 BuiltinCall->setObjectKind(CE->getObjectKind());
852 BuiltinCall->setCallee(Builtin);
853 BuiltinCall->setArg(1, ChainResult.get());
854
855 return false;
856}
857
858namespace {
859
860class ScanfDiagnosticFormatHandler
862 // Accepts the argument index (relative to the first destination index) of the
863 // argument whose size we want.
864 using ComputeSizeFunction =
865 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
866
867 // Accepts the argument index (relative to the first destination index), the
868 // destination size, and the source size).
869 using DiagnoseFunction =
870 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
871
872 ComputeSizeFunction ComputeSizeArgument;
873 DiagnoseFunction Diagnose;
874
875public:
876 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
877 DiagnoseFunction Diagnose)
878 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
879
880 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
881 const char *StartSpecifier,
882 unsigned specifierLen) override {
883 if (!FS.consumesDataArgument())
884 return true;
885
886 unsigned NulByte = 0;
887 switch ((FS.getConversionSpecifier().getKind())) {
888 default:
889 return true;
892 NulByte = 1;
893 break;
895 break;
896 }
897
898 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
899 if (FW.getHowSpecified() !=
900 analyze_format_string::OptionalAmount::HowSpecified::Constant)
901 return true;
902
903 unsigned SourceSize = FW.getConstantAmount() + NulByte;
904
905 std::optional<llvm::APSInt> DestSizeAPS =
906 ComputeSizeArgument(FS.getArgIndex());
907 if (!DestSizeAPS)
908 return true;
909
910 unsigned DestSize = DestSizeAPS->getZExtValue();
911
912 if (DestSize < SourceSize)
913 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
914
915 return true;
916 }
917};
918
919class EstimateSizeFormatHandler
921 size_t Size;
922 /// Whether the format string contains Linux kernel's format specifier
923 /// extension.
924 bool IsKernelCompatible = true;
925
926public:
927 EstimateSizeFormatHandler(StringRef Format)
928 : Size(std::min(Format.find(0), Format.size()) +
929 1 /* null byte always written by sprintf */) {}
930
931 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
932 const char *, unsigned SpecifierLen,
933 const TargetInfo &) override {
934
935 const size_t FieldWidth = computeFieldWidth(FS);
936 const size_t Precision = computePrecision(FS);
937
938 // The actual format.
939 switch (FS.getConversionSpecifier().getKind()) {
940 // Just a char.
943 Size += std::max(FieldWidth, (size_t)1);
944 break;
945 // Just an integer.
955 Size += std::max(FieldWidth, Precision);
956 break;
957
958 // %g style conversion switches between %f or %e style dynamically.
959 // %g removes trailing zeros, and does not print decimal point if there are
960 // no digits that follow it. Thus %g can print a single digit.
961 // FIXME: If it is alternative form:
962 // For g and G conversions, trailing zeros are not removed from the result.
965 Size += 1;
966 break;
967
968 // Floating point number in the form '[+]ddd.ddd'.
971 Size += std::max(FieldWidth, 1 /* integer part */ +
972 (Precision ? 1 + Precision
973 : 0) /* period + decimal */);
974 break;
975
976 // Floating point number in the form '[-]d.ddde[+-]dd'.
979 Size +=
980 std::max(FieldWidth,
981 1 /* integer part */ +
982 (Precision ? 1 + Precision : 0) /* period + decimal */ +
983 1 /* e or E letter */ + 2 /* exponent */);
984 break;
985
986 // Floating point number in the form '[-]0xh.hhhhp±dd'.
989 Size +=
990 std::max(FieldWidth,
991 2 /* 0x */ + 1 /* integer part */ +
992 (Precision ? 1 + Precision : 0) /* period + decimal */ +
993 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
994 break;
995
996 // Just a string.
999 Size += FieldWidth;
1000 break;
1001
1002 // Just a pointer in the form '0xddd'.
1004 // Linux kernel has its own extesion for `%p` specifier.
1005 // Kernel Document:
1006 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1007 IsKernelCompatible = false;
1008 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
1009 break;
1010
1011 // A plain percent.
1013 Size += 1;
1014 break;
1015
1016 default:
1017 break;
1018 }
1019
1020 // If field width is specified, the sign/space is already accounted for
1021 // within the field width, so no additional size is needed.
1022 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1023 Size += 1;
1024
1025 if (FS.hasAlternativeForm()) {
1026 switch (FS.getConversionSpecifier().getKind()) {
1027 // For o conversion, it increases the precision, if and only if necessary,
1028 // to force the first digit of the result to be a zero
1029 // (if the value and precision are both 0, a single 0 is printed)
1031 // For b conversion, a nonzero result has 0b prefixed to it.
1033 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1034 // it.
1037 // Note: even when the prefix is added, if
1038 // (prefix_width <= FieldWidth - formatted_length) holds,
1039 // the prefix does not increase the format
1040 // size. e.g.(("%#3x", 0xf) is "0xf")
1041
1042 // If the result is zero, o, b, x, X adds nothing.
1043 break;
1044 // For a, A, e, E, f, F, g, and G conversions,
1045 // the result of converting a floating-point number always contains a
1046 // decimal-point
1055 Size += (Precision ? 0 : 1);
1056 break;
1057 // For other conversions, the behavior is undefined.
1058 default:
1059 break;
1060 }
1061 }
1062 assert(SpecifierLen <= Size && "no underflow");
1063 Size -= SpecifierLen;
1064 return true;
1065 }
1066
1067 size_t getSizeLowerBound() const { return Size; }
1068 bool isKernelCompatible() const { return IsKernelCompatible; }
1069
1070private:
1071 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1072 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1073 size_t FieldWidth = 0;
1075 FieldWidth = FW.getConstantAmount();
1076 return FieldWidth;
1077 }
1078
1079 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1080 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1081 size_t Precision = 0;
1082
1083 // See man 3 printf for default precision value based on the specifier.
1084 switch (FW.getHowSpecified()) {
1086 switch (FS.getConversionSpecifier().getKind()) {
1087 default:
1088 break;
1092 Precision = 1;
1093 break;
1100 Precision = 1;
1101 break;
1108 Precision = 6;
1109 break;
1111 Precision = 1;
1112 break;
1113 }
1114 break;
1116 Precision = FW.getConstantAmount();
1117 break;
1118 default:
1119 break;
1120 }
1121 return Precision;
1122 }
1123};
1124
1125} // namespace
1126
1127static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1128 StringRef &FormatStrRef, size_t &StrLen,
1129 ASTContext &Context) {
1130 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1131 Format && (Format->isOrdinary() || Format->isUTF8())) {
1132 FormatStrRef = Format->getString();
1133 const ConstantArrayType *T =
1134 Context.getAsConstantArrayType(Format->getType());
1135 assert(T && "String literal not of constant array type!");
1136 size_t TypeSize = T->getZExtSize();
1137 // In case there's a null byte somewhere.
1138 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1139 return true;
1140 }
1141 return false;
1142}
1143
1144void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1145 CallExpr *TheCall) {
1146 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1148 return;
1149
1150 bool UseDABAttr = false;
1151 const FunctionDecl *UseDecl = FD;
1152
1153 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1154 if (DABAttr) {
1155 UseDecl = DABAttr->getFunction();
1156 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1157 UseDABAttr = true;
1158 }
1159
1160 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1161
1162 if (!BuiltinID)
1163 return;
1164
1165 const TargetInfo &TI = getASTContext().getTargetInfo();
1166 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1167
1168 auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1169 // If we refer to a diagnose_as_builtin attribute, we need to change the
1170 // argument index to refer to the arguments of the called function. Unless
1171 // the index is out of bounds, which presumably means it's a variadic
1172 // function.
1173 if (!UseDABAttr)
1174 return Index;
1175 unsigned DABIndices = DABAttr->argIndices_size();
1176 unsigned NewIndex = Index < DABIndices
1177 ? DABAttr->argIndices_begin()[Index]
1178 : Index - DABIndices + FD->getNumParams();
1179 if (NewIndex >= TheCall->getNumArgs())
1180 return std::nullopt;
1181 return NewIndex;
1182 };
1183
1184 auto ComputeExplicitObjectSizeArgument =
1185 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1186 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1187 if (!IndexOptional)
1188 return std::nullopt;
1189 unsigned NewIndex = *IndexOptional;
1191 Expr *SizeArg = TheCall->getArg(NewIndex);
1192 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
1193 return std::nullopt;
1194 llvm::APSInt Integer = Result.Val.getInt();
1195 Integer.setIsUnsigned(true);
1196 return Integer;
1197 };
1198
1199 auto ComputeSizeArgument =
1200 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1201 // If the parameter has a pass_object_size attribute, then we should use its
1202 // (potentially) more strict checking mode. Otherwise, conservatively assume
1203 // type 0.
1204 int BOSType = 0;
1205 // This check can fail for variadic functions.
1206 if (Index < FD->getNumParams()) {
1207 if (const auto *POS =
1208 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1209 BOSType = POS->getType();
1210 }
1211
1212 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1213 if (!IndexOptional)
1214 return std::nullopt;
1215 unsigned NewIndex = *IndexOptional;
1216
1217 if (NewIndex >= TheCall->getNumArgs())
1218 return std::nullopt;
1219
1220 const Expr *ObjArg = TheCall->getArg(NewIndex);
1222 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
1223 return std::nullopt;
1224
1225 // Get the object size in the target's size_t width.
1226 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
1227 };
1228
1229 auto ComputeStrLenArgument =
1230 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1231 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1232 if (!IndexOptional)
1233 return std::nullopt;
1234 unsigned NewIndex = *IndexOptional;
1235
1236 const Expr *ObjArg = TheCall->getArg(NewIndex);
1238 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
1239 return std::nullopt;
1240 // Add 1 for null byte.
1241 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
1242 };
1243
1244 std::optional<llvm::APSInt> SourceSize;
1245 std::optional<llvm::APSInt> DestinationSize;
1246 unsigned DiagID = 0;
1247 bool IsChkVariant = false;
1248
1249 auto GetFunctionName = [&]() {
1250 std::string FunctionNameStr =
1251 getASTContext().BuiltinInfo.getName(BuiltinID);
1252 llvm::StringRef FunctionName = FunctionNameStr;
1253 // Skim off the details of whichever builtin was called to produce a better
1254 // diagnostic, as it's unlikely that the user wrote the __builtin
1255 // explicitly.
1256 if (IsChkVariant) {
1257 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
1258 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
1259 } else {
1260 FunctionName.consume_front("__builtin_");
1261 }
1262 return FunctionName.str();
1263 };
1264
1265 switch (BuiltinID) {
1266 default:
1267 return;
1268 case Builtin::BI__builtin_stpcpy:
1269 case Builtin::BIstpcpy:
1270 case Builtin::BI__builtin_strcpy:
1271 case Builtin::BIstrcpy: {
1272 DiagID = diag::warn_fortify_strlen_overflow;
1273 SourceSize = ComputeStrLenArgument(1);
1274 DestinationSize = ComputeSizeArgument(0);
1275 break;
1276 }
1277
1278 case Builtin::BI__builtin___stpcpy_chk:
1279 case Builtin::BI__builtin___strcpy_chk: {
1280 DiagID = diag::warn_fortify_strlen_overflow;
1281 SourceSize = ComputeStrLenArgument(1);
1282 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1283 IsChkVariant = true;
1284 break;
1285 }
1286
1287 case Builtin::BIscanf:
1288 case Builtin::BIfscanf:
1289 case Builtin::BIsscanf: {
1290 unsigned FormatIndex = 1;
1291 unsigned DataIndex = 2;
1292 if (BuiltinID == Builtin::BIscanf) {
1293 FormatIndex = 0;
1294 DataIndex = 1;
1295 }
1296
1297 const auto *FormatExpr =
1298 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1299
1300 StringRef FormatStrRef;
1301 size_t StrLen;
1302 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1303 return;
1304
1305 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1306 unsigned SourceSize) {
1307 DiagID = diag::warn_fortify_scanf_overflow;
1308 unsigned Index = ArgIndex + DataIndex;
1309 std::string FunctionName = GetFunctionName();
1310 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1311 PDiag(DiagID) << FunctionName << (Index + 1)
1312 << DestSize << SourceSize);
1313 };
1314
1315 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1316 return ComputeSizeArgument(Index + DataIndex);
1317 };
1318 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1319 const char *FormatBytes = FormatStrRef.data();
1321 FormatBytes + StrLen, getLangOpts(),
1323
1324 // Unlike the other cases, in this one we have already issued the diagnostic
1325 // here, so no need to continue (because unlike the other cases, here the
1326 // diagnostic refers to the argument number).
1327 return;
1328 }
1329
1330 case Builtin::BIsprintf:
1331 case Builtin::BI__builtin___sprintf_chk: {
1332 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1333 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1334
1335 StringRef FormatStrRef;
1336 size_t StrLen;
1337 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1338 EstimateSizeFormatHandler H(FormatStrRef);
1339 const char *FormatBytes = FormatStrRef.data();
1341 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1342 Context.getTargetInfo(), false)) {
1343 DiagID = H.isKernelCompatible()
1344 ? diag::warn_format_overflow
1345 : diag::warn_format_overflow_non_kprintf;
1346 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1347 .extOrTrunc(SizeTypeWidth);
1348 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1349 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1350 IsChkVariant = true;
1351 } else {
1352 DestinationSize = ComputeSizeArgument(0);
1353 }
1354 break;
1355 }
1356 }
1357 return;
1358 }
1359 case Builtin::BI__builtin___memcpy_chk:
1360 case Builtin::BI__builtin___memmove_chk:
1361 case Builtin::BI__builtin___memset_chk:
1362 case Builtin::BI__builtin___strlcat_chk:
1363 case Builtin::BI__builtin___strlcpy_chk:
1364 case Builtin::BI__builtin___strncat_chk:
1365 case Builtin::BI__builtin___strncpy_chk:
1366 case Builtin::BI__builtin___stpncpy_chk:
1367 case Builtin::BI__builtin___memccpy_chk:
1368 case Builtin::BI__builtin___mempcpy_chk: {
1369 DiagID = diag::warn_builtin_chk_overflow;
1370 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1371 DestinationSize =
1372 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1373 IsChkVariant = true;
1374 break;
1375 }
1376
1377 case Builtin::BI__builtin___snprintf_chk:
1378 case Builtin::BI__builtin___vsnprintf_chk: {
1379 DiagID = diag::warn_builtin_chk_overflow;
1380 SourceSize = ComputeExplicitObjectSizeArgument(1);
1381 DestinationSize = ComputeExplicitObjectSizeArgument(3);
1382 IsChkVariant = true;
1383 break;
1384 }
1385
1386 case Builtin::BIstrncat:
1387 case Builtin::BI__builtin_strncat:
1388 case Builtin::BIstrncpy:
1389 case Builtin::BI__builtin_strncpy:
1390 case Builtin::BIstpncpy:
1391 case Builtin::BI__builtin_stpncpy: {
1392 // Whether these functions overflow depends on the runtime strlen of the
1393 // string, not just the buffer size, so emitting the "always overflow"
1394 // diagnostic isn't quite right. We should still diagnose passing a buffer
1395 // size larger than the destination buffer though; this is a runtime abort
1396 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1397 DiagID = diag::warn_fortify_source_size_mismatch;
1398 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1399 DestinationSize = ComputeSizeArgument(0);
1400 break;
1401 }
1402
1403 case Builtin::BImemcpy:
1404 case Builtin::BI__builtin_memcpy:
1405 case Builtin::BImemmove:
1406 case Builtin::BI__builtin_memmove:
1407 case Builtin::BImemset:
1408 case Builtin::BI__builtin_memset:
1409 case Builtin::BImempcpy:
1410 case Builtin::BI__builtin_mempcpy: {
1411 DiagID = diag::warn_fortify_source_overflow;
1412 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1413 DestinationSize = ComputeSizeArgument(0);
1414 break;
1415 }
1416 case Builtin::BIsnprintf:
1417 case Builtin::BI__builtin_snprintf:
1418 case Builtin::BIvsnprintf:
1419 case Builtin::BI__builtin_vsnprintf: {
1420 DiagID = diag::warn_fortify_source_size_mismatch;
1421 SourceSize = ComputeExplicitObjectSizeArgument(1);
1422 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1423 StringRef FormatStrRef;
1424 size_t StrLen;
1425 if (SourceSize &&
1426 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1427 EstimateSizeFormatHandler H(FormatStrRef);
1428 const char *FormatBytes = FormatStrRef.data();
1430 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1431 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1432 llvm::APSInt FormatSize =
1433 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1434 .extOrTrunc(SizeTypeWidth);
1435 if (FormatSize > *SourceSize && *SourceSize != 0) {
1436 unsigned TruncationDiagID =
1437 H.isKernelCompatible() ? diag::warn_format_truncation
1438 : diag::warn_format_truncation_non_kprintf;
1439 SmallString<16> SpecifiedSizeStr;
1440 SmallString<16> FormatSizeStr;
1441 SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1442 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1443 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1444 PDiag(TruncationDiagID)
1445 << GetFunctionName() << SpecifiedSizeStr
1446 << FormatSizeStr);
1447 }
1448 }
1449 }
1450 DestinationSize = ComputeSizeArgument(0);
1451 }
1452 }
1453
1454 if (!SourceSize || !DestinationSize ||
1455 llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1456 return;
1457
1458 std::string FunctionName = GetFunctionName();
1459
1460 SmallString<16> DestinationStr;
1461 SmallString<16> SourceStr;
1462 DestinationSize->toString(DestinationStr, /*Radix=*/10);
1463 SourceSize->toString(SourceStr, /*Radix=*/10);
1464 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1465 PDiag(DiagID)
1466 << FunctionName << DestinationStr << SourceStr);
1467}
1468
1469static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1470 Scope::ScopeFlags NeededScopeFlags,
1471 unsigned DiagID) {
1472 // Scopes aren't available during instantiation. Fortunately, builtin
1473 // functions cannot be template args so they cannot be formed through template
1474 // instantiation. Therefore checking once during the parse is sufficient.
1475 if (SemaRef.inTemplateInstantiation())
1476 return false;
1477
1478 Scope *S = SemaRef.getCurScope();
1479 while (S && !S->isSEHExceptScope())
1480 S = S->getParent();
1481 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1482 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1483 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1484 << DRE->getDecl()->getIdentifier();
1485 return true;
1486 }
1487
1488 return false;
1489}
1490
1491// In OpenCL, __builtin_alloca_* should return a pointer to address space
1492// that corresponds to the stack address space i.e private address space.
1493static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1494 QualType RT = TheCall->getType();
1495 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1496 "__builtin_alloca has invalid address space");
1497
1498 RT = RT->getPointeeType();
1500 TheCall->setType(S.Context.getPointerType(RT));
1501}
1502
1503namespace {
1504enum PointerAuthOpKind {
1505 PAO_Strip,
1506 PAO_Sign,
1507 PAO_Auth,
1508 PAO_SignGeneric,
1509 PAO_Discriminator,
1510 PAO_BlendPointer,
1511 PAO_BlendInteger
1512};
1513}
1514
1516 if (getLangOpts().PointerAuthIntrinsics)
1517 return false;
1518
1519 Diag(Loc, diag::err_ptrauth_disabled) << Range;
1520 return true;
1521}
1522
1525}
1526
1527static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1528 // Convert it to type 'int'.
1529 if (convertArgumentToType(S, Arg, S.Context.IntTy))
1530 return true;
1531
1532 // Value-dependent expressions are okay; wait for template instantiation.
1533 if (Arg->isValueDependent())
1534 return false;
1535
1536 unsigned KeyValue;
1537 return S.checkConstantPointerAuthKey(Arg, KeyValue);
1538}
1539
1541 // Attempt to constant-evaluate the expression.
1542 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
1543 if (!KeyValue) {
1544 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
1545 << 0 << Arg->getSourceRange();
1546 return true;
1547 }
1548
1549 // Ask the target to validate the key parameter.
1550 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
1552 {
1553 llvm::raw_svector_ostream Str(Value);
1554 Str << *KeyValue;
1555 }
1556
1557 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
1558 << Value << Arg->getSourceRange();
1559 return true;
1560 }
1561
1562 Result = KeyValue->getZExtValue();
1563 return false;
1564}
1565
1568 unsigned &IntVal) {
1569 if (!Arg) {
1570 IntVal = 0;
1571 return true;
1572 }
1573
1574 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
1575 if (!Result) {
1576 Diag(Arg->getExprLoc(), diag::err_ptrauth_arg_not_ice);
1577 return false;
1578 }
1579
1580 unsigned Max;
1581 bool IsAddrDiscArg = false;
1582
1583 switch (Kind) {
1585 Max = 1;
1586 IsAddrDiscArg = true;
1587 break;
1590 break;
1591 };
1592
1593 if (*Result < 0 || *Result > Max) {
1594 if (IsAddrDiscArg)
1595 Diag(Arg->getExprLoc(), diag::err_ptrauth_address_discrimination_invalid)
1596 << Result->getExtValue();
1597 else
1598 Diag(Arg->getExprLoc(), diag::err_ptrauth_extra_discriminator_invalid)
1599 << Result->getExtValue() << Max;
1600
1601 return false;
1602 };
1603
1604 IntVal = Result->getZExtValue();
1605 return true;
1606}
1607
1608static std::pair<const ValueDecl *, CharUnits>
1610 // Must evaluate as a pointer.
1612 if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())
1613 return {nullptr, CharUnits()};
1614
1615 const auto *BaseDecl =
1616 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1617 if (!BaseDecl)
1618 return {nullptr, CharUnits()};
1619
1620 return {BaseDecl, Result.Val.getLValueOffset()};
1621}
1622
1623static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1624 bool RequireConstant = false) {
1625 if (Arg->hasPlaceholderType()) {
1627 if (R.isInvalid())
1628 return true;
1629 Arg = R.get();
1630 }
1631
1632 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1633 return OpKind != PAO_BlendInteger;
1634 };
1635 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1636 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1637 OpKind == PAO_SignGeneric;
1638 };
1639
1640 // Require the value to have the right range of type.
1641 QualType ExpectedTy;
1642 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1643 ExpectedTy = Arg->getType().getUnqualifiedType();
1644 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1645 ExpectedTy = S.Context.VoidPtrTy;
1646 } else if (AllowsInteger(OpKind) &&
1648 ExpectedTy = S.Context.getUIntPtrType();
1649
1650 } else {
1651 // Diagnose the failures.
1652 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
1653 << unsigned(OpKind == PAO_Discriminator ? 1
1654 : OpKind == PAO_BlendPointer ? 2
1655 : OpKind == PAO_BlendInteger ? 3
1656 : 0)
1657 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1658 << Arg->getType() << Arg->getSourceRange();
1659 return true;
1660 }
1661
1662 // Convert to that type. This should just be an lvalue-to-rvalue
1663 // conversion.
1664 if (convertArgumentToType(S, Arg, ExpectedTy))
1665 return true;
1666
1667 if (!RequireConstant) {
1668 // Warn about null pointers for non-generic sign and auth operations.
1669 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1671 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
1672 ? diag::warn_ptrauth_sign_null_pointer
1673 : diag::warn_ptrauth_auth_null_pointer)
1674 << Arg->getSourceRange();
1675 }
1676
1677 return false;
1678 }
1679
1680 // Perform special checking on the arguments to ptrauth_sign_constant.
1681
1682 // The main argument.
1683 if (OpKind == PAO_Sign) {
1684 // Require the value we're signing to have a special form.
1685 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg);
1686 bool Invalid;
1687
1688 // Must be rooted in a declaration reference.
1689 if (!BaseDecl)
1690 Invalid = true;
1691
1692 // If it's a function declaration, we can't have an offset.
1693 else if (isa<FunctionDecl>(BaseDecl))
1694 Invalid = !Offset.isZero();
1695
1696 // Otherwise we're fine.
1697 else
1698 Invalid = false;
1699
1700 if (Invalid)
1701 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
1702 return Invalid;
1703 }
1704
1705 // The discriminator argument.
1706 assert(OpKind == PAO_Discriminator);
1707
1708 // Must be a pointer or integer or blend thereof.
1709 Expr *Pointer = nullptr;
1710 Expr *Integer = nullptr;
1711 if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {
1712 if (Call->getBuiltinCallee() ==
1713 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1714 Pointer = Call->getArg(0);
1715 Integer = Call->getArg(1);
1716 }
1717 }
1718 if (!Pointer && !Integer) {
1719 if (Arg->getType()->isPointerType())
1720 Pointer = Arg;
1721 else
1722 Integer = Arg;
1723 }
1724
1725 // Check the pointer.
1726 bool Invalid = false;
1727 if (Pointer) {
1728 assert(Pointer->getType()->isPointerType());
1729
1730 // TODO: if we're initializing a global, check that the address is
1731 // somehow related to what we're initializing. This probably will
1732 // never really be feasible and we'll have to catch it at link-time.
1733 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer);
1734 if (!BaseDecl || !isa<VarDecl>(BaseDecl))
1735 Invalid = true;
1736 }
1737
1738 // Check the integer.
1739 if (Integer) {
1740 assert(Integer->getType()->isIntegerType());
1741 if (!Integer->isEvaluatable(S.Context))
1742 Invalid = true;
1743 }
1744
1745 if (Invalid)
1746 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
1747 return Invalid;
1748}
1749
1751 if (S.checkArgCount(Call, 2))
1752 return ExprError();
1754 return ExprError();
1755 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
1756 checkPointerAuthKey(S, Call->getArgs()[1]))
1757 return ExprError();
1758
1759 Call->setType(Call->getArgs()[0]->getType());
1760 return Call;
1761}
1762
1764 if (S.checkArgCount(Call, 2))
1765 return ExprError();
1767 return ExprError();
1768 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
1769 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
1770 return ExprError();
1771
1772 Call->setType(S.Context.getUIntPtrType());
1773 return Call;
1774}
1775
1777 if (S.checkArgCount(Call, 2))
1778 return ExprError();
1780 return ExprError();
1781 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
1782 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
1783 return ExprError();
1784
1785 Call->setType(S.Context.getUIntPtrType());
1786 return Call;
1787}
1788
1790 PointerAuthOpKind OpKind,
1791 bool RequireConstant) {
1792 if (S.checkArgCount(Call, 3))
1793 return ExprError();
1795 return ExprError();
1796 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||
1797 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1798 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,
1799 RequireConstant))
1800 return ExprError();
1801
1802 Call->setType(Call->getArgs()[0]->getType());
1803 return Call;
1804}
1805
1807 if (S.checkArgCount(Call, 5))
1808 return ExprError();
1810 return ExprError();
1811 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1812 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1813 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1814 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1815 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
1816 return ExprError();
1817
1818 Call->setType(Call->getArgs()[0]->getType());
1819 return Call;
1820}
1821
1824 return ExprError();
1825
1826 // We've already performed normal call type-checking.
1827 const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();
1828
1829 // Operand must be an ordinary or UTF-8 string literal.
1830 const auto *Literal = dyn_cast<StringLiteral>(Arg);
1831 if (!Literal || Literal->getCharByteWidth() != 1) {
1832 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)
1833 << (Literal ? 1 : 0) << Arg->getSourceRange();
1834 return ExprError();
1835 }
1836
1837 return Call;
1838}
1839
1841 if (S.checkArgCount(Call, 1))
1842 return ExprError();
1843 Expr *FirstArg = Call->getArg(0);
1844 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(FirstArg);
1845 if (FirstValue.isInvalid())
1846 return ExprError();
1847 Call->setArg(0, FirstValue.get());
1848 QualType FirstArgType = FirstArg->getType();
1849 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
1850 FirstArgType = S.Context.getDecayedType(FirstArgType);
1851
1852 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
1853 if (!FirstArgRecord) {
1854 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1855 << /*isPolymorphic=*/0 << FirstArgType;
1856 return ExprError();
1857 }
1858 if (S.RequireCompleteType(
1859 FirstArg->getBeginLoc(), FirstArgType->getPointeeType(),
1860 diag::err_get_vtable_pointer_requires_complete_type)) {
1861 return ExprError();
1862 }
1863
1864 if (!FirstArgRecord->isPolymorphic()) {
1865 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1866 << /*isPolymorphic=*/1 << FirstArgRecord;
1867 return ExprError();
1868 }
1870 Call->setType(ReturnType);
1871 return Call;
1872}
1873
1875 if (S.checkArgCount(TheCall, 1))
1876 return ExprError();
1877
1878 // Compute __builtin_launder's parameter type from the argument.
1879 // The parameter type is:
1880 // * The type of the argument if it's not an array or function type,
1881 // Otherwise,
1882 // * The decayed argument type.
1883 QualType ParamTy = [&]() {
1884 QualType ArgTy = TheCall->getArg(0)->getType();
1885 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1886 return S.Context.getPointerType(Ty->getElementType());
1887 if (ArgTy->isFunctionType()) {
1888 return S.Context.getPointerType(ArgTy);
1889 }
1890 return ArgTy;
1891 }();
1892
1893 TheCall->setType(ParamTy);
1894
1895 auto DiagSelect = [&]() -> std::optional<unsigned> {
1896 if (!ParamTy->isPointerType())
1897 return 0;
1898 if (ParamTy->isFunctionPointerType())
1899 return 1;
1900 if (ParamTy->isVoidPointerType())
1901 return 2;
1902 return std::optional<unsigned>{};
1903 }();
1904 if (DiagSelect) {
1905 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1906 << *DiagSelect << TheCall->getSourceRange();
1907 return ExprError();
1908 }
1909
1910 // We either have an incomplete class type, or we have a class template
1911 // whose instantiation has not been forced. Example:
1912 //
1913 // template <class T> struct Foo { T value; };
1914 // Foo<int> *p = nullptr;
1915 // auto *d = __builtin_launder(p);
1916 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1917 diag::err_incomplete_type))
1918 return ExprError();
1919
1920 assert(ParamTy->getPointeeType()->isObjectType() &&
1921 "Unhandled non-object pointer case");
1922
1923 InitializedEntity Entity =
1925 ExprResult Arg =
1926 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1927 if (Arg.isInvalid())
1928 return ExprError();
1929 TheCall->setArg(0, Arg.get());
1930
1931 return TheCall;
1932}
1933
1935 if (S.checkArgCount(TheCall, 1))
1936 return ExprError();
1937
1939 if (Arg.isInvalid())
1940 return ExprError();
1941 QualType ParamTy = Arg.get()->getType();
1942 TheCall->setArg(0, Arg.get());
1943 TheCall->setType(S.Context.BoolTy);
1944
1945 // Only accept pointers to objects as arguments, which should have object
1946 // pointer or void pointer types.
1947 if (const auto *PT = ParamTy->getAs<PointerType>()) {
1948 // LWG4138: Function pointer types not allowed
1949 if (PT->getPointeeType()->isFunctionType()) {
1950 S.Diag(TheCall->getArg(0)->getExprLoc(),
1951 diag::err_builtin_is_within_lifetime_invalid_arg)
1952 << 1;
1953 return ExprError();
1954 }
1955 // Disallow VLAs too since those shouldn't be able to
1956 // be a template parameter for `std::is_within_lifetime`
1957 if (PT->getPointeeType()->isVariableArrayType()) {
1958 S.Diag(TheCall->getArg(0)->getExprLoc(), diag::err_vla_unsupported)
1959 << 1 << "__builtin_is_within_lifetime";
1960 return ExprError();
1961 }
1962 } else {
1963 S.Diag(TheCall->getArg(0)->getExprLoc(),
1964 diag::err_builtin_is_within_lifetime_invalid_arg)
1965 << 0;
1966 return ExprError();
1967 }
1968 return TheCall;
1969}
1970
1972 if (S.checkArgCount(TheCall, 3))
1973 return ExprError();
1974
1975 QualType Dest = TheCall->getArg(0)->getType();
1976 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
1977 S.Diag(TheCall->getArg(0)->getExprLoc(),
1978 diag::err_builtin_trivially_relocate_invalid_arg_type)
1979 << /*a pointer*/ 0;
1980 return ExprError();
1981 }
1982
1983 QualType T = Dest->getPointeeType();
1984 if (S.RequireCompleteType(TheCall->getBeginLoc(), T,
1985 diag::err_incomplete_type))
1986 return ExprError();
1987
1988 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
1990 S.Diag(TheCall->getArg(0)->getExprLoc(),
1991 diag::err_builtin_trivially_relocate_invalid_arg_type)
1992 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
1993 return ExprError();
1994 }
1995
1996 TheCall->setType(Dest);
1997
1998 QualType Src = TheCall->getArg(1)->getType();
1999 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2000 S.Diag(TheCall->getArg(1)->getExprLoc(),
2001 diag::err_builtin_trivially_relocate_invalid_arg_type)
2002 << /*the same*/ 3;
2003 return ExprError();
2004 }
2005
2006 Expr *SizeExpr = TheCall->getArg(2);
2007 ExprResult Size = S.DefaultLvalueConversion(SizeExpr);
2008 if (Size.isInvalid())
2009 return ExprError();
2010
2011 Size = S.tryConvertExprToType(Size.get(), S.getASTContext().getSizeType());
2012 if (Size.isInvalid())
2013 return ExprError();
2014 SizeExpr = Size.get();
2015 TheCall->setArg(2, SizeExpr);
2016
2017 return TheCall;
2018}
2019
2020// Emit an error and return true if the current object format type is in the
2021// list of unsupported types.
2023 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2024 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2025 llvm::Triple::ObjectFormatType CurObjFormat =
2026 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2027 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2028 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2029 << TheCall->getSourceRange();
2030 return true;
2031 }
2032 return false;
2033}
2034
2035// Emit an error and return true if the current architecture is not in the list
2036// of supported architectures.
2037static bool
2039 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2040 llvm::Triple::ArchType CurArch =
2041 S.getASTContext().getTargetInfo().getTriple().getArch();
2042 if (llvm::is_contained(SupportedArchs, CurArch))
2043 return false;
2044 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2045 << TheCall->getSourceRange();
2046 return true;
2047}
2048
2049static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2050 SourceLocation CallSiteLoc);
2051
2052bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2053 CallExpr *TheCall) {
2054 switch (TI.getTriple().getArch()) {
2055 default:
2056 // Some builtins don't require additional checking, so just consider these
2057 // acceptable.
2058 return false;
2059 case llvm::Triple::arm:
2060 case llvm::Triple::armeb:
2061 case llvm::Triple::thumb:
2062 case llvm::Triple::thumbeb:
2063 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2064 case llvm::Triple::aarch64:
2065 case llvm::Triple::aarch64_32:
2066 case llvm::Triple::aarch64_be:
2067 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2068 case llvm::Triple::bpfeb:
2069 case llvm::Triple::bpfel:
2070 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2071 case llvm::Triple::dxil:
2072 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2073 case llvm::Triple::hexagon:
2074 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2075 case llvm::Triple::mips:
2076 case llvm::Triple::mipsel:
2077 case llvm::Triple::mips64:
2078 case llvm::Triple::mips64el:
2079 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2080 case llvm::Triple::spirv:
2081 case llvm::Triple::spirv32:
2082 case llvm::Triple::spirv64:
2083 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2084 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2085 return false;
2086 case llvm::Triple::systemz:
2087 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2088 case llvm::Triple::x86:
2089 case llvm::Triple::x86_64:
2090 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2091 case llvm::Triple::ppc:
2092 case llvm::Triple::ppcle:
2093 case llvm::Triple::ppc64:
2094 case llvm::Triple::ppc64le:
2095 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2096 case llvm::Triple::amdgcn:
2097 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
2098 case llvm::Triple::riscv32:
2099 case llvm::Triple::riscv64:
2100 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2101 case llvm::Triple::loongarch32:
2102 case llvm::Triple::loongarch64:
2103 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2104 TheCall);
2105 case llvm::Triple::wasm32:
2106 case llvm::Triple::wasm64:
2107 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2108 case llvm::Triple::nvptx:
2109 case llvm::Triple::nvptx64:
2110 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2111 }
2112}
2113
2114// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2115// not a valid type, emit an error message and return true. Otherwise return
2116// false.
2117static bool
2120 int ArgOrdinal) {
2121 QualType EltTy = ArgTy;
2122 if (auto *VecTy = EltTy->getAs<VectorType>())
2123 EltTy = VecTy->getElementType();
2124
2125 switch (ArgTyRestr) {
2127 if (!ArgTy->getAs<VectorType>() &&
2129 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2130 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2131 << ArgTy;
2132 }
2133 break;
2135 if (!EltTy->isRealFloatingType()) {
2136 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2137 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2138 << /* floating-point */ 1 << ArgTy;
2139 }
2140 break;
2142 if (!EltTy->isIntegerType()) {
2143 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2144 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2145 << /* no fp */ 0 << ArgTy;
2146 }
2147 break;
2149 if (EltTy->isUnsignedIntegerType()) {
2150 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2151 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2152 << /* or fp */ 1 << ArgTy;
2153 }
2154 break;
2155 }
2156
2157 return false;
2158}
2159
2160/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2161/// This checks that the target supports the builtin and that the string
2162/// argument is constant and valid.
2163static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2164 const TargetInfo *AuxTI, unsigned BuiltinID) {
2165 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2166 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2167 "Expecting __builtin_cpu_...");
2168
2169 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2170 const TargetInfo *TheTI = &TI;
2171 auto SupportsBI = [=](const TargetInfo *TInfo) {
2172 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2173 (!IsCPUSupports && TInfo->supportsCpuIs()));
2174 };
2175 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2176 TheTI = AuxTI;
2177
2178 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2179 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2180 return S.Diag(TheCall->getBeginLoc(),
2181 TI.getTriple().isOSAIX()
2182 ? diag::err_builtin_aix_os_unsupported
2183 : diag::err_builtin_target_unsupported)
2184 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2185
2186 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2187 // Check if the argument is a string literal.
2188 if (!isa<StringLiteral>(Arg))
2189 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2190 << Arg->getSourceRange();
2191
2192 // Check the contents of the string.
2193 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2194 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2195 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2196 << Arg->getSourceRange();
2197 return false;
2198 }
2199 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2200 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2201 << Arg->getSourceRange();
2202 return false;
2203}
2204
2205/// Checks that __builtin_popcountg was called with a single argument, which is
2206/// an unsigned integer.
2207static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2208 if (S.checkArgCount(TheCall, 1))
2209 return true;
2210
2211 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2212 if (ArgRes.isInvalid())
2213 return true;
2214
2215 Expr *Arg = ArgRes.get();
2216 TheCall->setArg(0, Arg);
2217
2218 QualType ArgTy = Arg->getType();
2219
2220 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2221 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2222 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2223 << ArgTy;
2224 return true;
2225 }
2226 return false;
2227}
2228
2229/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2230/// an unsigned integer, and an optional second argument, which is promoted to
2231/// an 'int'.
2232static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2233 if (S.checkArgCountRange(TheCall, 1, 2))
2234 return true;
2235
2236 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2237 if (Arg0Res.isInvalid())
2238 return true;
2239
2240 Expr *Arg0 = Arg0Res.get();
2241 TheCall->setArg(0, Arg0);
2242
2243 QualType Arg0Ty = Arg0->getType();
2244
2245 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2246 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2247 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2248 << Arg0Ty;
2249 return true;
2250 }
2251
2252 if (TheCall->getNumArgs() > 1) {
2253 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2254 if (Arg1Res.isInvalid())
2255 return true;
2256
2257 Expr *Arg1 = Arg1Res.get();
2258 TheCall->setArg(1, Arg1);
2259
2260 QualType Arg1Ty = Arg1->getType();
2261
2262 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2263 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2264 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2265 return true;
2266 }
2267 }
2268
2269 return false;
2270}
2271
2272static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2273 unsigned Pos) {
2274 QualType MaskTy = MaskArg->getType();
2275 if (!MaskTy->isExtVectorBoolType())
2276 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2277 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2278 << MaskTy;
2279
2280 QualType PtrTy = PtrArg->getType();
2281 if (!PtrTy->isPointerType() || !PtrTy->getPointeeType()->isVectorType())
2282 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2283 << Pos << "pointer to vector";
2284 return false;
2285}
2286
2288 if (S.checkArgCountRange(TheCall, 2, 3))
2289 return ExprError();
2290
2291 Expr *MaskArg = TheCall->getArg(0);
2292 Expr *PtrArg = TheCall->getArg(1);
2293 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 2))
2294 return ExprError();
2295
2296 QualType MaskTy = MaskArg->getType();
2297 QualType PtrTy = PtrArg->getType();
2298 QualType PointeeTy = PtrTy->getPointeeType();
2299 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2300 const VectorType *DataVecTy = PointeeTy->getAs<VectorType>();
2301
2302 if (TheCall->getNumArgs() == 3) {
2303 Expr *PassThruArg = TheCall->getArg(2);
2304 QualType PassThruTy = PassThruArg->getType();
2305 if (!S.Context.hasSameType(PassThruTy, PointeeTy))
2306 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2307 << /* third argument */ 3 << PointeeTy;
2308 }
2309
2310 if (MaskVecTy->getNumElements() != DataVecTy->getNumElements())
2311 return ExprError(
2312 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2314 TheCall->getBuiltinCallee())
2315 << MaskTy << PointeeTy);
2316
2317 TheCall->setType(PointeeTy);
2318 return TheCall;
2319}
2320
2322 if (S.checkArgCount(TheCall, 3))
2323 return ExprError();
2324
2325 Expr *MaskArg = TheCall->getArg(0);
2326 Expr *ValArg = TheCall->getArg(1);
2327 Expr *PtrArg = TheCall->getArg(2);
2328
2329 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3))
2330 return ExprError();
2331
2332 QualType MaskTy = MaskArg->getType();
2333 QualType PtrTy = PtrArg->getType();
2334 QualType ValTy = ValArg->getType();
2335 if (!ValTy->isVectorType())
2336 return ExprError(
2337 S.Diag(ValArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2338 << 2 << "vector");
2339
2340 QualType PointeeTy = PtrTy->getPointeeType();
2341 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2342 const VectorType *ValVecTy = ValTy->getAs<VectorType>();
2343 const VectorType *PtrVecTy = PointeeTy->getAs<VectorType>();
2344
2345 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements() ||
2346 MaskVecTy->getNumElements() != PtrVecTy->getNumElements())
2347 return ExprError(
2348 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2350 TheCall->getBuiltinCallee())
2351 << MaskTy << PointeeTy);
2352
2353 if (!S.Context.hasSameType(ValTy, PointeeTy))
2354 return ExprError(S.Diag(TheCall->getBeginLoc(),
2355 diag::err_vec_builtin_incompatible_vector)
2356 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2357 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2358 TheCall->getArg(1)->getEndLoc()));
2359
2360 TheCall->setType(S.Context.VoidTy);
2361 return TheCall;
2362}
2363
2365 SourceLocation Loc = TheCall->getBeginLoc();
2366 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2367 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2368
2369 if (Args.size() == 0) {
2370 S.Diag(TheCall->getBeginLoc(),
2371 diag::err_typecheck_call_too_few_args_at_least)
2372 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2373 << /*is_non_object=*/0 << TheCall->getSourceRange();
2374 return ExprError();
2375 }
2376
2377 QualType FuncT = Args[0]->getType();
2378
2379 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2380 if (Args.size() < 2) {
2381 S.Diag(TheCall->getBeginLoc(),
2382 diag::err_typecheck_call_too_few_args_at_least)
2383 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2384 << /*is_non_object=*/0 << TheCall->getSourceRange();
2385 return ExprError();
2386 }
2387
2388 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2389 QualType ObjectT = Args[1]->getType();
2390
2391 if (MPT->isMemberDataPointer() && S.checkArgCount(TheCall, 2))
2392 return ExprError();
2393
2394 ExprResult ObjectArg = [&]() -> ExprResult {
2395 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2396 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2397 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2398 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2399 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2400 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2401 if (S.Context.hasSameType(QualType(MemPtrClass, 0),
2402 S.BuiltinRemoveCVRef(ObjectT, Loc)) ||
2403 S.BuiltinIsBaseOf(Args[1]->getBeginLoc(), QualType(MemPtrClass, 0),
2404 S.BuiltinRemoveCVRef(ObjectT, Loc))) {
2405 return Args[1];
2406 }
2407
2408 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2409 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2410 // reference_wrapper;
2411 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2412 if (RD->isInStdNamespace() &&
2413 RD->getDeclName().getAsString() == "reference_wrapper") {
2414 CXXScopeSpec SS;
2415 IdentifierInfo *GetName = &S.Context.Idents.get("get");
2416 UnqualifiedId GetID;
2417 GetID.setIdentifier(GetName, Loc);
2418
2420 S.getCurScope(), Args[1], Loc, tok::period, SS,
2421 /*TemplateKWLoc=*/SourceLocation(), GetID, nullptr);
2422
2423 if (MemExpr.isInvalid())
2424 return ExprError();
2425
2426 return S.ActOnCallExpr(S.getCurScope(), MemExpr.get(), Loc, {}, Loc);
2427 }
2428 }
2429
2430 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
2431 // class T and t1 does not satisfy the previous two items;
2432
2433 return S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, Args[1]);
2434 }();
2435
2436 if (ObjectArg.isInvalid())
2437 return ExprError();
2438
2439 ExprResult BinOp = S.ActOnBinOp(S.getCurScope(), TheCall->getBeginLoc(),
2440 tok::periodstar, ObjectArg.get(), Args[0]);
2441 if (BinOp.isInvalid())
2442 return ExprError();
2443
2444 if (MPT->isMemberDataPointer())
2445 return BinOp;
2446
2447 auto *MemCall = new (S.Context)
2449
2450 return S.ActOnCallExpr(S.getCurScope(), MemCall, TheCall->getBeginLoc(),
2451 Args.drop_front(2), TheCall->getRParenLoc());
2452 }
2453 return S.ActOnCallExpr(S.getCurScope(), Args.front(), TheCall->getBeginLoc(),
2454 Args.drop_front(), TheCall->getRParenLoc());
2455}
2456
2458Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2459 CallExpr *TheCall) {
2460 ExprResult TheCallResult(TheCall);
2461
2462 // Find out if any arguments are required to be integer constant expressions.
2463 unsigned ICEArguments = 0;
2465 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
2466 if (Error != ASTContext::GE_None)
2467 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2468
2469 // If any arguments are required to be ICE's, check and diagnose.
2470 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2471 // Skip arguments not required to be ICE's.
2472 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2473
2474 llvm::APSInt Result;
2475 // If we don't have enough arguments, continue so we can issue better
2476 // diagnostic in checkArgCount(...)
2477 if (ArgNo < TheCall->getNumArgs() &&
2478 BuiltinConstantArg(TheCall, ArgNo, Result))
2479 return true;
2480 ICEArguments &= ~(1 << ArgNo);
2481 }
2482
2483 FPOptions FPO;
2484 switch (BuiltinID) {
2485 case Builtin::BI__builtin_cpu_supports:
2486 case Builtin::BI__builtin_cpu_is:
2487 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
2488 Context.getAuxTargetInfo(), BuiltinID))
2489 return ExprError();
2490 break;
2491 case Builtin::BI__builtin_cpu_init:
2493 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2494 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2495 return ExprError();
2496 }
2497 break;
2498 case Builtin::BI__builtin___CFStringMakeConstantString:
2499 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2500 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2502 *this, BuiltinID, TheCall,
2503 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2504 return ExprError();
2505 assert(TheCall->getNumArgs() == 1 &&
2506 "Wrong # arguments to builtin CFStringMakeConstantString");
2507 if (ObjC().CheckObjCString(TheCall->getArg(0)))
2508 return ExprError();
2509 break;
2510 case Builtin::BI__builtin_ms_va_start:
2511 case Builtin::BI__builtin_stdarg_start:
2512 case Builtin::BI__builtin_va_start:
2513 case Builtin::BI__builtin_c23_va_start:
2514 if (BuiltinVAStart(BuiltinID, TheCall))
2515 return ExprError();
2516 break;
2517 case Builtin::BI__va_start: {
2518 switch (Context.getTargetInfo().getTriple().getArch()) {
2519 case llvm::Triple::aarch64:
2520 case llvm::Triple::arm:
2521 case llvm::Triple::thumb:
2522 if (BuiltinVAStartARMMicrosoft(TheCall))
2523 return ExprError();
2524 break;
2525 default:
2526 if (BuiltinVAStart(BuiltinID, TheCall))
2527 return ExprError();
2528 break;
2529 }
2530 break;
2531 }
2532
2533 // The acquire, release, and no fence variants are ARM and AArch64 only.
2534 case Builtin::BI_interlockedbittestandset_acq:
2535 case Builtin::BI_interlockedbittestandset_rel:
2536 case Builtin::BI_interlockedbittestandset_nf:
2537 case Builtin::BI_interlockedbittestandreset_acq:
2538 case Builtin::BI_interlockedbittestandreset_rel:
2539 case Builtin::BI_interlockedbittestandreset_nf:
2541 *this, TheCall,
2542 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2543 return ExprError();
2544 break;
2545
2546 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2547 case Builtin::BI_bittest64:
2548 case Builtin::BI_bittestandcomplement64:
2549 case Builtin::BI_bittestandreset64:
2550 case Builtin::BI_bittestandset64:
2551 case Builtin::BI_interlockedbittestandreset64:
2552 case Builtin::BI_interlockedbittestandset64:
2554 *this, TheCall,
2555 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
2556 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2557 return ExprError();
2558 break;
2559
2560 // The 64-bit acquire, release, and no fence variants are AArch64 only.
2561 case Builtin::BI_interlockedbittestandreset64_acq:
2562 case Builtin::BI_interlockedbittestandreset64_rel:
2563 case Builtin::BI_interlockedbittestandreset64_nf:
2564 case Builtin::BI_interlockedbittestandset64_acq:
2565 case Builtin::BI_interlockedbittestandset64_rel:
2566 case Builtin::BI_interlockedbittestandset64_nf:
2567 if (CheckBuiltinTargetInSupported(*this, TheCall, {llvm::Triple::aarch64}))
2568 return ExprError();
2569 break;
2570
2571 case Builtin::BI__builtin_set_flt_rounds:
2573 *this, TheCall,
2574 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
2575 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn,
2576 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
2577 llvm::Triple::ppc64le}))
2578 return ExprError();
2579 break;
2580
2581 case Builtin::BI__builtin_isgreater:
2582 case Builtin::BI__builtin_isgreaterequal:
2583 case Builtin::BI__builtin_isless:
2584 case Builtin::BI__builtin_islessequal:
2585 case Builtin::BI__builtin_islessgreater:
2586 case Builtin::BI__builtin_isunordered:
2587 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
2588 return ExprError();
2589 break;
2590 case Builtin::BI__builtin_fpclassify:
2591 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
2592 return ExprError();
2593 break;
2594 case Builtin::BI__builtin_isfpclass:
2595 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
2596 return ExprError();
2597 break;
2598 case Builtin::BI__builtin_isfinite:
2599 case Builtin::BI__builtin_isinf:
2600 case Builtin::BI__builtin_isinf_sign:
2601 case Builtin::BI__builtin_isnan:
2602 case Builtin::BI__builtin_issignaling:
2603 case Builtin::BI__builtin_isnormal:
2604 case Builtin::BI__builtin_issubnormal:
2605 case Builtin::BI__builtin_iszero:
2606 case Builtin::BI__builtin_signbit:
2607 case Builtin::BI__builtin_signbitf:
2608 case Builtin::BI__builtin_signbitl:
2609 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
2610 return ExprError();
2611 break;
2612 case Builtin::BI__builtin_shufflevector:
2613 return BuiltinShuffleVector(TheCall);
2614 // TheCall will be freed by the smart pointer here, but that's fine, since
2615 // BuiltinShuffleVector guts it, but then doesn't release it.
2616 case Builtin::BI__builtin_masked_load:
2617 case Builtin::BI__builtin_masked_expand_load:
2618 return BuiltinMaskedLoad(*this, TheCall);
2619 case Builtin::BI__builtin_masked_store:
2620 case Builtin::BI__builtin_masked_compress_store:
2621 return BuiltinMaskedStore(*this, TheCall);
2622 case Builtin::BI__builtin_invoke:
2623 return BuiltinInvoke(*this, TheCall);
2624 case Builtin::BI__builtin_prefetch:
2625 if (BuiltinPrefetch(TheCall))
2626 return ExprError();
2627 break;
2628 case Builtin::BI__builtin_alloca_with_align:
2629 case Builtin::BI__builtin_alloca_with_align_uninitialized:
2630 if (BuiltinAllocaWithAlign(TheCall))
2631 return ExprError();
2632 [[fallthrough]];
2633 case Builtin::BI__builtin_alloca:
2634 case Builtin::BI__builtin_alloca_uninitialized:
2635 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
2636 << TheCall->getDirectCallee();
2637 if (getLangOpts().OpenCL) {
2638 builtinAllocaAddrSpace(*this, TheCall);
2639 }
2640 break;
2641 case Builtin::BI__arithmetic_fence:
2642 if (BuiltinArithmeticFence(TheCall))
2643 return ExprError();
2644 break;
2645 case Builtin::BI__assume:
2646 case Builtin::BI__builtin_assume:
2647 if (BuiltinAssume(TheCall))
2648 return ExprError();
2649 break;
2650 case Builtin::BI__builtin_assume_aligned:
2651 if (BuiltinAssumeAligned(TheCall))
2652 return ExprError();
2653 break;
2654 case Builtin::BI__builtin_dynamic_object_size:
2655 case Builtin::BI__builtin_object_size:
2656 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
2657 return ExprError();
2658 break;
2659 case Builtin::BI__builtin_longjmp:
2660 if (BuiltinLongjmp(TheCall))
2661 return ExprError();
2662 break;
2663 case Builtin::BI__builtin_setjmp:
2664 if (BuiltinSetjmp(TheCall))
2665 return ExprError();
2666 break;
2667 case Builtin::BI__builtin_classify_type:
2668 if (checkArgCount(TheCall, 1))
2669 return true;
2670 TheCall->setType(Context.IntTy);
2671 break;
2672 case Builtin::BI__builtin_complex:
2673 if (BuiltinComplex(TheCall))
2674 return ExprError();
2675 break;
2676 case Builtin::BI__builtin_constant_p: {
2677 if (checkArgCount(TheCall, 1))
2678 return true;
2680 if (Arg.isInvalid()) return true;
2681 TheCall->setArg(0, Arg.get());
2682 TheCall->setType(Context.IntTy);
2683 break;
2684 }
2685 case Builtin::BI__builtin_launder:
2686 return BuiltinLaunder(*this, TheCall);
2687 case Builtin::BI__builtin_is_within_lifetime:
2688 return BuiltinIsWithinLifetime(*this, TheCall);
2689 case Builtin::BI__builtin_trivially_relocate:
2690 return BuiltinTriviallyRelocate(*this, TheCall);
2691
2692 case Builtin::BI__sync_fetch_and_add:
2693 case Builtin::BI__sync_fetch_and_add_1:
2694 case Builtin::BI__sync_fetch_and_add_2:
2695 case Builtin::BI__sync_fetch_and_add_4:
2696 case Builtin::BI__sync_fetch_and_add_8:
2697 case Builtin::BI__sync_fetch_and_add_16:
2698 case Builtin::BI__sync_fetch_and_sub:
2699 case Builtin::BI__sync_fetch_and_sub_1:
2700 case Builtin::BI__sync_fetch_and_sub_2:
2701 case Builtin::BI__sync_fetch_and_sub_4:
2702 case Builtin::BI__sync_fetch_and_sub_8:
2703 case Builtin::BI__sync_fetch_and_sub_16:
2704 case Builtin::BI__sync_fetch_and_or:
2705 case Builtin::BI__sync_fetch_and_or_1:
2706 case Builtin::BI__sync_fetch_and_or_2:
2707 case Builtin::BI__sync_fetch_and_or_4:
2708 case Builtin::BI__sync_fetch_and_or_8:
2709 case Builtin::BI__sync_fetch_and_or_16:
2710 case Builtin::BI__sync_fetch_and_and:
2711 case Builtin::BI__sync_fetch_and_and_1:
2712 case Builtin::BI__sync_fetch_and_and_2:
2713 case Builtin::BI__sync_fetch_and_and_4:
2714 case Builtin::BI__sync_fetch_and_and_8:
2715 case Builtin::BI__sync_fetch_and_and_16:
2716 case Builtin::BI__sync_fetch_and_xor:
2717 case Builtin::BI__sync_fetch_and_xor_1:
2718 case Builtin::BI__sync_fetch_and_xor_2:
2719 case Builtin::BI__sync_fetch_and_xor_4:
2720 case Builtin::BI__sync_fetch_and_xor_8:
2721 case Builtin::BI__sync_fetch_and_xor_16:
2722 case Builtin::BI__sync_fetch_and_nand:
2723 case Builtin::BI__sync_fetch_and_nand_1:
2724 case Builtin::BI__sync_fetch_and_nand_2:
2725 case Builtin::BI__sync_fetch_and_nand_4:
2726 case Builtin::BI__sync_fetch_and_nand_8:
2727 case Builtin::BI__sync_fetch_and_nand_16:
2728 case Builtin::BI__sync_add_and_fetch:
2729 case Builtin::BI__sync_add_and_fetch_1:
2730 case Builtin::BI__sync_add_and_fetch_2:
2731 case Builtin::BI__sync_add_and_fetch_4:
2732 case Builtin::BI__sync_add_and_fetch_8:
2733 case Builtin::BI__sync_add_and_fetch_16:
2734 case Builtin::BI__sync_sub_and_fetch:
2735 case Builtin::BI__sync_sub_and_fetch_1:
2736 case Builtin::BI__sync_sub_and_fetch_2:
2737 case Builtin::BI__sync_sub_and_fetch_4:
2738 case Builtin::BI__sync_sub_and_fetch_8:
2739 case Builtin::BI__sync_sub_and_fetch_16:
2740 case Builtin::BI__sync_and_and_fetch:
2741 case Builtin::BI__sync_and_and_fetch_1:
2742 case Builtin::BI__sync_and_and_fetch_2:
2743 case Builtin::BI__sync_and_and_fetch_4:
2744 case Builtin::BI__sync_and_and_fetch_8:
2745 case Builtin::BI__sync_and_and_fetch_16:
2746 case Builtin::BI__sync_or_and_fetch:
2747 case Builtin::BI__sync_or_and_fetch_1:
2748 case Builtin::BI__sync_or_and_fetch_2:
2749 case Builtin::BI__sync_or_and_fetch_4:
2750 case Builtin::BI__sync_or_and_fetch_8:
2751 case Builtin::BI__sync_or_and_fetch_16:
2752 case Builtin::BI__sync_xor_and_fetch:
2753 case Builtin::BI__sync_xor_and_fetch_1:
2754 case Builtin::BI__sync_xor_and_fetch_2:
2755 case Builtin::BI__sync_xor_and_fetch_4:
2756 case Builtin::BI__sync_xor_and_fetch_8:
2757 case Builtin::BI__sync_xor_and_fetch_16:
2758 case Builtin::BI__sync_nand_and_fetch:
2759 case Builtin::BI__sync_nand_and_fetch_1:
2760 case Builtin::BI__sync_nand_and_fetch_2:
2761 case Builtin::BI__sync_nand_and_fetch_4:
2762 case Builtin::BI__sync_nand_and_fetch_8:
2763 case Builtin::BI__sync_nand_and_fetch_16:
2764 case Builtin::BI__sync_val_compare_and_swap:
2765 case Builtin::BI__sync_val_compare_and_swap_1:
2766 case Builtin::BI__sync_val_compare_and_swap_2:
2767 case Builtin::BI__sync_val_compare_and_swap_4:
2768 case Builtin::BI__sync_val_compare_and_swap_8:
2769 case Builtin::BI__sync_val_compare_and_swap_16:
2770 case Builtin::BI__sync_bool_compare_and_swap:
2771 case Builtin::BI__sync_bool_compare_and_swap_1:
2772 case Builtin::BI__sync_bool_compare_and_swap_2:
2773 case Builtin::BI__sync_bool_compare_and_swap_4:
2774 case Builtin::BI__sync_bool_compare_and_swap_8:
2775 case Builtin::BI__sync_bool_compare_and_swap_16:
2776 case Builtin::BI__sync_lock_test_and_set:
2777 case Builtin::BI__sync_lock_test_and_set_1:
2778 case Builtin::BI__sync_lock_test_and_set_2:
2779 case Builtin::BI__sync_lock_test_and_set_4:
2780 case Builtin::BI__sync_lock_test_and_set_8:
2781 case Builtin::BI__sync_lock_test_and_set_16:
2782 case Builtin::BI__sync_lock_release:
2783 case Builtin::BI__sync_lock_release_1:
2784 case Builtin::BI__sync_lock_release_2:
2785 case Builtin::BI__sync_lock_release_4:
2786 case Builtin::BI__sync_lock_release_8:
2787 case Builtin::BI__sync_lock_release_16:
2788 case Builtin::BI__sync_swap:
2789 case Builtin::BI__sync_swap_1:
2790 case Builtin::BI__sync_swap_2:
2791 case Builtin::BI__sync_swap_4:
2792 case Builtin::BI__sync_swap_8:
2793 case Builtin::BI__sync_swap_16:
2794 return BuiltinAtomicOverloaded(TheCallResult);
2795 case Builtin::BI__sync_synchronize:
2796 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
2797 << TheCall->getCallee()->getSourceRange();
2798 break;
2799 case Builtin::BI__builtin_nontemporal_load:
2800 case Builtin::BI__builtin_nontemporal_store:
2801 return BuiltinNontemporalOverloaded(TheCallResult);
2802 case Builtin::BI__builtin_memcpy_inline: {
2803 clang::Expr *SizeOp = TheCall->getArg(2);
2804 // We warn about copying to or from `nullptr` pointers when `size` is
2805 // greater than 0. When `size` is value dependent we cannot evaluate its
2806 // value so we bail out.
2807 if (SizeOp->isValueDependent())
2808 break;
2809 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
2810 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2811 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
2812 }
2813 break;
2814 }
2815 case Builtin::BI__builtin_memset_inline: {
2816 clang::Expr *SizeOp = TheCall->getArg(2);
2817 // We warn about filling to `nullptr` pointers when `size` is greater than
2818 // 0. When `size` is value dependent we cannot evaluate its value so we bail
2819 // out.
2820 if (SizeOp->isValueDependent())
2821 break;
2822 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
2823 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2824 break;
2825 }
2826#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
2827 case Builtin::BI##ID: \
2828 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
2829#include "clang/Basic/Builtins.inc"
2830 case Builtin::BI__annotation:
2831 if (BuiltinMSVCAnnotation(*this, TheCall))
2832 return ExprError();
2833 break;
2834 case Builtin::BI__builtin_annotation:
2835 if (BuiltinAnnotation(*this, TheCall))
2836 return ExprError();
2837 break;
2838 case Builtin::BI__builtin_addressof:
2839 if (BuiltinAddressof(*this, TheCall))
2840 return ExprError();
2841 break;
2842 case Builtin::BI__builtin_function_start:
2843 if (BuiltinFunctionStart(*this, TheCall))
2844 return ExprError();
2845 break;
2846 case Builtin::BI__builtin_is_aligned:
2847 case Builtin::BI__builtin_align_up:
2848 case Builtin::BI__builtin_align_down:
2849 if (BuiltinAlignment(*this, TheCall, BuiltinID))
2850 return ExprError();
2851 break;
2852 case Builtin::BI__builtin_add_overflow:
2853 case Builtin::BI__builtin_sub_overflow:
2854 case Builtin::BI__builtin_mul_overflow:
2855 if (BuiltinOverflow(*this, TheCall, BuiltinID))
2856 return ExprError();
2857 break;
2858 case Builtin::BI__builtin_operator_new:
2859 case Builtin::BI__builtin_operator_delete: {
2860 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
2861 ExprResult Res =
2862 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
2863 return Res;
2864 }
2865 case Builtin::BI__builtin_dump_struct:
2866 return BuiltinDumpStruct(*this, TheCall);
2867 case Builtin::BI__builtin_expect_with_probability: {
2868 // We first want to ensure we are called with 3 arguments
2869 if (checkArgCount(TheCall, 3))
2870 return ExprError();
2871 // then check probability is constant float in range [0.0, 1.0]
2872 const Expr *ProbArg = TheCall->getArg(2);
2874 Expr::EvalResult Eval;
2875 Eval.Diag = &Notes;
2876 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2877 !Eval.Val.isFloat()) {
2878 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2879 << ProbArg->getSourceRange();
2880 for (const PartialDiagnosticAt &PDiag : Notes)
2881 Diag(PDiag.first, PDiag.second);
2882 return ExprError();
2883 }
2884 llvm::APFloat Probability = Eval.Val.getFloat();
2885 bool LoseInfo = false;
2886 Probability.convert(llvm::APFloat::IEEEdouble(),
2887 llvm::RoundingMode::Dynamic, &LoseInfo);
2888 if (!(Probability >= llvm::APFloat(0.0) &&
2889 Probability <= llvm::APFloat(1.0))) {
2890 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2891 << ProbArg->getSourceRange();
2892 return ExprError();
2893 }
2894 break;
2895 }
2896 case Builtin::BI__builtin_preserve_access_index:
2897 if (BuiltinPreserveAI(*this, TheCall))
2898 return ExprError();
2899 break;
2900 case Builtin::BI__builtin_call_with_static_chain:
2901 if (BuiltinCallWithStaticChain(*this, TheCall))
2902 return ExprError();
2903 break;
2904 case Builtin::BI__exception_code:
2905 case Builtin::BI_exception_code:
2906 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
2907 diag::err_seh___except_block))
2908 return ExprError();
2909 break;
2910 case Builtin::BI__exception_info:
2911 case Builtin::BI_exception_info:
2912 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2913 diag::err_seh___except_filter))
2914 return ExprError();
2915 break;
2916 case Builtin::BI__GetExceptionInfo:
2917 if (checkArgCount(TheCall, 1))
2918 return ExprError();
2919
2921 TheCall->getBeginLoc(),
2923 TheCall))
2924 return ExprError();
2925
2926 TheCall->setType(Context.VoidPtrTy);
2927 break;
2928 case Builtin::BIaddressof:
2929 case Builtin::BI__addressof:
2930 case Builtin::BIforward:
2931 case Builtin::BIforward_like:
2932 case Builtin::BImove:
2933 case Builtin::BImove_if_noexcept:
2934 case Builtin::BIas_const: {
2935 // These are all expected to be of the form
2936 // T &/&&/* f(U &/&&)
2937 // where T and U only differ in qualification.
2938 if (checkArgCount(TheCall, 1))
2939 return ExprError();
2940 QualType Param = FDecl->getParamDecl(0)->getType();
2941 QualType Result = FDecl->getReturnType();
2942 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
2943 BuiltinID == Builtin::BI__addressof;
2944 if (!(Param->isReferenceType() &&
2945 (ReturnsPointer ? Result->isAnyPointerType()
2946 : Result->isReferenceType()) &&
2948 Result->getPointeeType()))) {
2949 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
2950 << FDecl;
2951 return ExprError();
2952 }
2953 break;
2954 }
2955 case Builtin::BI__builtin_ptrauth_strip:
2956 return PointerAuthStrip(*this, TheCall);
2957 case Builtin::BI__builtin_ptrauth_blend_discriminator:
2958 return PointerAuthBlendDiscriminator(*this, TheCall);
2959 case Builtin::BI__builtin_ptrauth_sign_constant:
2960 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
2961 /*RequireConstant=*/true);
2962 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
2963 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
2964 /*RequireConstant=*/false);
2965 case Builtin::BI__builtin_ptrauth_auth:
2966 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
2967 /*RequireConstant=*/false);
2968 case Builtin::BI__builtin_ptrauth_sign_generic_data:
2969 return PointerAuthSignGenericData(*this, TheCall);
2970 case Builtin::BI__builtin_ptrauth_auth_and_resign:
2971 return PointerAuthAuthAndResign(*this, TheCall);
2972 case Builtin::BI__builtin_ptrauth_string_discriminator:
2973 return PointerAuthStringDiscriminator(*this, TheCall);
2974
2975 case Builtin::BI__builtin_get_vtable_pointer:
2976 return GetVTablePointer(*this, TheCall);
2977
2978 // OpenCL v2.0, s6.13.16 - Pipe functions
2979 case Builtin::BIread_pipe:
2980 case Builtin::BIwrite_pipe:
2981 // Since those two functions are declared with var args, we need a semantic
2982 // check for the argument.
2983 if (OpenCL().checkBuiltinRWPipe(TheCall))
2984 return ExprError();
2985 break;
2986 case Builtin::BIreserve_read_pipe:
2987 case Builtin::BIreserve_write_pipe:
2988 case Builtin::BIwork_group_reserve_read_pipe:
2989 case Builtin::BIwork_group_reserve_write_pipe:
2990 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
2991 return ExprError();
2992 break;
2993 case Builtin::BIsub_group_reserve_read_pipe:
2994 case Builtin::BIsub_group_reserve_write_pipe:
2995 if (OpenCL().checkSubgroupExt(TheCall) ||
2996 OpenCL().checkBuiltinReserveRWPipe(TheCall))
2997 return ExprError();
2998 break;
2999 case Builtin::BIcommit_read_pipe:
3000 case Builtin::BIcommit_write_pipe:
3001 case Builtin::BIwork_group_commit_read_pipe:
3002 case Builtin::BIwork_group_commit_write_pipe:
3003 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
3004 return ExprError();
3005 break;
3006 case Builtin::BIsub_group_commit_read_pipe:
3007 case Builtin::BIsub_group_commit_write_pipe:
3008 if (OpenCL().checkSubgroupExt(TheCall) ||
3009 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3010 return ExprError();
3011 break;
3012 case Builtin::BIget_pipe_num_packets:
3013 case Builtin::BIget_pipe_max_packets:
3014 if (OpenCL().checkBuiltinPipePackets(TheCall))
3015 return ExprError();
3016 break;
3017 case Builtin::BIto_global:
3018 case Builtin::BIto_local:
3019 case Builtin::BIto_private:
3020 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3021 return ExprError();
3022 break;
3023 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3024 case Builtin::BIenqueue_kernel:
3025 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3026 return ExprError();
3027 break;
3028 case Builtin::BIget_kernel_work_group_size:
3029 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3030 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3031 return ExprError();
3032 break;
3033 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3034 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3035 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3036 return ExprError();
3037 break;
3038 case Builtin::BI__builtin_os_log_format:
3040 [[fallthrough]];
3041 case Builtin::BI__builtin_os_log_format_buffer_size:
3042 if (BuiltinOSLogFormat(TheCall))
3043 return ExprError();
3044 break;
3045 case Builtin::BI__builtin_frame_address:
3046 case Builtin::BI__builtin_return_address: {
3047 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3048 return ExprError();
3049
3050 // -Wframe-address warning if non-zero passed to builtin
3051 // return/frame address.
3053 if (!TheCall->getArg(0)->isValueDependent() &&
3054 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3055 Result.Val.getInt() != 0)
3056 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3057 << ((BuiltinID == Builtin::BI__builtin_return_address)
3058 ? "__builtin_return_address"
3059 : "__builtin_frame_address")
3060 << TheCall->getSourceRange();
3061 break;
3062 }
3063
3064 case Builtin::BI__builtin_nondeterministic_value: {
3065 if (BuiltinNonDeterministicValue(TheCall))
3066 return ExprError();
3067 break;
3068 }
3069
3070 // __builtin_elementwise_abs restricts the element type to signed integers or
3071 // floating point types only.
3072 case Builtin::BI__builtin_elementwise_abs:
3075 return ExprError();
3076 break;
3077
3078 // These builtins restrict the element type to floating point
3079 // types only.
3080 case Builtin::BI__builtin_elementwise_acos:
3081 case Builtin::BI__builtin_elementwise_asin:
3082 case Builtin::BI__builtin_elementwise_atan:
3083 case Builtin::BI__builtin_elementwise_ceil:
3084 case Builtin::BI__builtin_elementwise_cos:
3085 case Builtin::BI__builtin_elementwise_cosh:
3086 case Builtin::BI__builtin_elementwise_exp:
3087 case Builtin::BI__builtin_elementwise_exp2:
3088 case Builtin::BI__builtin_elementwise_exp10:
3089 case Builtin::BI__builtin_elementwise_floor:
3090 case Builtin::BI__builtin_elementwise_log:
3091 case Builtin::BI__builtin_elementwise_log2:
3092 case Builtin::BI__builtin_elementwise_log10:
3093 case Builtin::BI__builtin_elementwise_roundeven:
3094 case Builtin::BI__builtin_elementwise_round:
3095 case Builtin::BI__builtin_elementwise_rint:
3096 case Builtin::BI__builtin_elementwise_nearbyint:
3097 case Builtin::BI__builtin_elementwise_sin:
3098 case Builtin::BI__builtin_elementwise_sinh:
3099 case Builtin::BI__builtin_elementwise_sqrt:
3100 case Builtin::BI__builtin_elementwise_tan:
3101 case Builtin::BI__builtin_elementwise_tanh:
3102 case Builtin::BI__builtin_elementwise_trunc:
3103 case Builtin::BI__builtin_elementwise_canonicalize:
3106 return ExprError();
3107 break;
3108 case Builtin::BI__builtin_elementwise_fma:
3109 if (BuiltinElementwiseTernaryMath(TheCall))
3110 return ExprError();
3111 break;
3112
3113 // These builtins restrict the element type to floating point
3114 // types only, and take in two arguments.
3115 case Builtin::BI__builtin_elementwise_minnum:
3116 case Builtin::BI__builtin_elementwise_maxnum:
3117 case Builtin::BI__builtin_elementwise_minimum:
3118 case Builtin::BI__builtin_elementwise_maximum:
3119 case Builtin::BI__builtin_elementwise_minimumnum:
3120 case Builtin::BI__builtin_elementwise_maximumnum:
3121 case Builtin::BI__builtin_elementwise_atan2:
3122 case Builtin::BI__builtin_elementwise_fmod:
3123 case Builtin::BI__builtin_elementwise_pow:
3124 if (BuiltinElementwiseMath(TheCall,
3126 return ExprError();
3127 break;
3128 // These builtins restrict the element type to integer
3129 // types only.
3130 case Builtin::BI__builtin_elementwise_add_sat:
3131 case Builtin::BI__builtin_elementwise_sub_sat:
3132 if (BuiltinElementwiseMath(TheCall,
3134 return ExprError();
3135 break;
3136 case Builtin::BI__builtin_elementwise_fshl:
3137 case Builtin::BI__builtin_elementwise_fshr:
3140 return ExprError();
3141 break;
3142 case Builtin::BI__builtin_elementwise_min:
3143 case Builtin::BI__builtin_elementwise_max:
3144 if (BuiltinElementwiseMath(TheCall))
3145 return ExprError();
3146 break;
3147 case Builtin::BI__builtin_elementwise_popcount:
3148 case Builtin::BI__builtin_elementwise_bitreverse:
3151 return ExprError();
3152 break;
3153 case Builtin::BI__builtin_elementwise_copysign: {
3154 if (checkArgCount(TheCall, 2))
3155 return ExprError();
3156
3157 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
3158 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
3159 if (Magnitude.isInvalid() || Sign.isInvalid())
3160 return ExprError();
3161
3162 QualType MagnitudeTy = Magnitude.get()->getType();
3163 QualType SignTy = Sign.get()->getType();
3165 *this, TheCall->getArg(0)->getBeginLoc(), MagnitudeTy,
3168 *this, TheCall->getArg(1)->getBeginLoc(), SignTy,
3170 return ExprError();
3171 }
3172
3173 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3174 return Diag(Sign.get()->getBeginLoc(),
3175 diag::err_typecheck_call_different_arg_types)
3176 << MagnitudeTy << SignTy;
3177 }
3178
3179 TheCall->setArg(0, Magnitude.get());
3180 TheCall->setArg(1, Sign.get());
3181 TheCall->setType(Magnitude.get()->getType());
3182 break;
3183 }
3184 case Builtin::BI__builtin_elementwise_ctlz:
3185 case Builtin::BI__builtin_elementwise_cttz:
3186 // These builtins can be unary or binary. Note for empty calls we call the
3187 // unary checker in order to not emit an error that says the function
3188 // expects 2 arguments, which would be misleading.
3189 if (TheCall->getNumArgs() <= 1) {
3192 return ExprError();
3193 } else if (BuiltinElementwiseMath(
3195 return ExprError();
3196 break;
3197 case Builtin::BI__builtin_reduce_max:
3198 case Builtin::BI__builtin_reduce_min: {
3199 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3200 return ExprError();
3201
3202 const Expr *Arg = TheCall->getArg(0);
3203 const auto *TyA = Arg->getType()->getAs<VectorType>();
3204
3205 QualType ElTy;
3206 if (TyA)
3207 ElTy = TyA->getElementType();
3208 else if (Arg->getType()->isSizelessVectorType())
3210
3211 if (ElTy.isNull()) {
3212 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3213 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3214 << Arg->getType();
3215 return ExprError();
3216 }
3217
3218 TheCall->setType(ElTy);
3219 break;
3220 }
3221 case Builtin::BI__builtin_reduce_maximum:
3222 case Builtin::BI__builtin_reduce_minimum: {
3223 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3224 return ExprError();
3225
3226 const Expr *Arg = TheCall->getArg(0);
3227 const auto *TyA = Arg->getType()->getAs<VectorType>();
3228
3229 QualType ElTy;
3230 if (TyA)
3231 ElTy = TyA->getElementType();
3232 else if (Arg->getType()->isSizelessVectorType())
3234
3235 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3236 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3237 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3238 << Arg->getType();
3239 return ExprError();
3240 }
3241
3242 TheCall->setType(ElTy);
3243 break;
3244 }
3245
3246 // These builtins support vectors of integers only.
3247 // TODO: ADD/MUL should support floating-point types.
3248 case Builtin::BI__builtin_reduce_add:
3249 case Builtin::BI__builtin_reduce_mul:
3250 case Builtin::BI__builtin_reduce_xor:
3251 case Builtin::BI__builtin_reduce_or:
3252 case Builtin::BI__builtin_reduce_and: {
3253 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3254 return ExprError();
3255
3256 const Expr *Arg = TheCall->getArg(0);
3257 const auto *TyA = Arg->getType()->getAs<VectorType>();
3258
3259 QualType ElTy;
3260 if (TyA)
3261 ElTy = TyA->getElementType();
3262 else if (Arg->getType()->isSizelessVectorType())
3264
3265 if (ElTy.isNull() || !ElTy->isIntegerType()) {
3266 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3267 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
3268 << Arg->getType();
3269 return ExprError();
3270 }
3271
3272 TheCall->setType(ElTy);
3273 break;
3274 }
3275
3276 case Builtin::BI__builtin_matrix_transpose:
3277 return BuiltinMatrixTranspose(TheCall, TheCallResult);
3278
3279 case Builtin::BI__builtin_matrix_column_major_load:
3280 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
3281
3282 case Builtin::BI__builtin_matrix_column_major_store:
3283 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
3284
3285 case Builtin::BI__builtin_verbose_trap:
3286 if (!checkBuiltinVerboseTrap(TheCall, *this))
3287 return ExprError();
3288 break;
3289
3290 case Builtin::BI__builtin_get_device_side_mangled_name: {
3291 auto Check = [](CallExpr *TheCall) {
3292 if (TheCall->getNumArgs() != 1)
3293 return false;
3294 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
3295 if (!DRE)
3296 return false;
3297 auto *D = DRE->getDecl();
3298 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
3299 return false;
3300 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3301 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
3302 };
3303 if (!Check(TheCall)) {
3304 Diag(TheCall->getBeginLoc(),
3305 diag::err_hip_invalid_args_builtin_mangled_name);
3306 return ExprError();
3307 }
3308 break;
3309 }
3310 case Builtin::BI__builtin_popcountg:
3311 if (BuiltinPopcountg(*this, TheCall))
3312 return ExprError();
3313 break;
3314 case Builtin::BI__builtin_clzg:
3315 case Builtin::BI__builtin_ctzg:
3316 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
3317 return ExprError();
3318 break;
3319
3320 case Builtin::BI__builtin_allow_runtime_check: {
3321 Expr *Arg = TheCall->getArg(0);
3322 // Check if the argument is a string literal.
3323 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) {
3324 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3325 << Arg->getSourceRange();
3326 return ExprError();
3327 }
3328 break;
3329 }
3330 case Builtin::BI__builtin_counted_by_ref:
3331 if (BuiltinCountedByRef(TheCall))
3332 return ExprError();
3333 break;
3334 }
3335
3336 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
3337 return ExprError();
3338
3339 // Since the target specific builtins for each arch overlap, only check those
3340 // of the arch we are compiling for.
3341 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
3342 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
3343 assert(Context.getAuxTargetInfo() &&
3344 "Aux Target Builtin, but not an aux target?");
3345
3346 if (CheckTSBuiltinFunctionCall(
3348 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
3349 return ExprError();
3350 } else {
3351 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
3352 TheCall))
3353 return ExprError();
3354 }
3355 }
3356
3357 return TheCallResult;
3358}
3359
3360bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3361 llvm::APSInt Result;
3362 // We can't check the value of a dependent argument.
3363 Expr *Arg = TheCall->getArg(ArgNum);
3364 if (Arg->isTypeDependent() || Arg->isValueDependent())
3365 return false;
3366
3367 // Check constant-ness first.
3368 if (BuiltinConstantArg(TheCall, ArgNum, Result))
3369 return true;
3370
3371 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3372 if (Result.isShiftedMask() || (~Result).isShiftedMask())
3373 return false;
3374
3375 return Diag(TheCall->getBeginLoc(),
3376 diag::err_argument_not_contiguous_bit_field)
3377 << ArgNum << Arg->getSourceRange();
3378}
3379
3380bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
3381 unsigned FirstArg, FormatStringInfo *FSI) {
3382 bool IsCXXMember = false;
3383 if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
3384 IsCXXMember = MD->isInstance();
3385 bool IsVariadic = false;
3386 if (const FunctionType *FnTy = D->getFunctionType())
3387 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
3388 else if (const auto *BD = dyn_cast<BlockDecl>(D))
3389 IsVariadic = BD->isVariadic();
3390 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
3391 IsVariadic = OMD->isVariadic();
3392
3393 return getFormatStringInfo(FormatIdx, FirstArg, IsCXXMember, IsVariadic, FSI);
3394}
3395
3396bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
3397 bool IsCXXMember, bool IsVariadic,
3398 FormatStringInfo *FSI) {
3399 if (FirstArg == 0)
3401 else if (IsVariadic)
3403 else
3405 FSI->FormatIdx = FormatIdx - 1;
3406 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
3407
3408 // The way the format attribute works in GCC, the implicit this argument
3409 // of member functions is counted. However, it doesn't appear in our own
3410 // lists, so decrement format_idx in that case.
3411 if (IsCXXMember) {
3412 if(FSI->FormatIdx == 0)
3413 return false;
3414 --FSI->FormatIdx;
3415 if (FSI->FirstDataArg != 0)
3416 --FSI->FirstDataArg;
3417 }
3418 return true;
3419}
3420
3421/// Checks if a the given expression evaluates to null.
3422///
3423/// Returns true if the value evaluates to null.
3424static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3425 // Treat (smart) pointers constructed from nullptr as null, whether we can
3426 // const-evaluate them or not.
3427 // This must happen first: the smart pointer expr might have _Nonnull type!
3428 if (isa<CXXNullPtrLiteralExpr>(
3431 return true;
3432
3433 // If the expression has non-null type, it doesn't evaluate to null.
3434 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
3435 if (*nullability == NullabilityKind::NonNull)
3436 return false;
3437 }
3438
3439 // As a special case, transparent unions initialized with zero are
3440 // considered null for the purposes of the nonnull attribute.
3441 if (const RecordType *UT = Expr->getType()->getAsUnionType();
3442 UT && UT->getOriginalDecl()
3444 ->hasAttr<TransparentUnionAttr>()) {
3445 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
3446 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
3447 Expr = ILE->getInit(0);
3448 }
3449
3450 bool Result;
3451 return (!Expr->isValueDependent() &&
3453 !Result);
3454}
3455
3457 const Expr *ArgExpr,
3458 SourceLocation CallSiteLoc) {
3459 if (CheckNonNullExpr(S, ArgExpr))
3460 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3461 S.PDiag(diag::warn_null_arg)
3462 << ArgExpr->getSourceRange());
3463}
3464
3465/// Determine whether the given type has a non-null nullability annotation.
3467 if (auto nullability = type->getNullability())
3468 return *nullability == NullabilityKind::NonNull;
3469
3470 return false;
3471}
3472
3474 const NamedDecl *FDecl,
3475 const FunctionProtoType *Proto,
3477 SourceLocation CallSiteLoc) {
3478 assert((FDecl || Proto) && "Need a function declaration or prototype");
3479
3480 // Already checked by constant evaluator.
3482 return;
3483 // Check the attributes attached to the method/function itself.
3484 llvm::SmallBitVector NonNullArgs;
3485 if (FDecl) {
3486 // Handle the nonnull attribute on the function/method declaration itself.
3487 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3488 if (!NonNull->args_size()) {
3489 // Easy case: all pointer arguments are nonnull.
3490 for (const auto *Arg : Args)
3491 if (S.isValidPointerAttrType(Arg->getType()))
3492 CheckNonNullArgument(S, Arg, CallSiteLoc);
3493 return;
3494 }
3495
3496 for (const ParamIdx &Idx : NonNull->args()) {
3497 unsigned IdxAST = Idx.getASTIndex();
3498 if (IdxAST >= Args.size())
3499 continue;
3500 if (NonNullArgs.empty())
3501 NonNullArgs.resize(Args.size());
3502 NonNullArgs.set(IdxAST);
3503 }
3504 }
3505 }
3506
3507 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3508 // Handle the nonnull attribute on the parameters of the
3509 // function/method.
3511 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3512 parms = FD->parameters();
3513 else
3514 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3515
3516 unsigned ParamIndex = 0;
3517 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3518 I != E; ++I, ++ParamIndex) {
3519 const ParmVarDecl *PVD = *I;
3520 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
3521 if (NonNullArgs.empty())
3522 NonNullArgs.resize(Args.size());
3523
3524 NonNullArgs.set(ParamIndex);
3525 }
3526 }
3527 } else {
3528 // If we have a non-function, non-method declaration but no
3529 // function prototype, try to dig out the function prototype.
3530 if (!Proto) {
3531 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3532 QualType type = VD->getType().getNonReferenceType();
3533 if (auto pointerType = type->getAs<PointerType>())
3534 type = pointerType->getPointeeType();
3535 else if (auto blockType = type->getAs<BlockPointerType>())
3536 type = blockType->getPointeeType();
3537 // FIXME: data member pointers?
3538
3539 // Dig out the function prototype, if there is one.
3540 Proto = type->getAs<FunctionProtoType>();
3541 }
3542 }
3543
3544 // Fill in non-null argument information from the nullability
3545 // information on the parameter types (if we have them).
3546 if (Proto) {
3547 unsigned Index = 0;
3548 for (auto paramType : Proto->getParamTypes()) {
3549 if (isNonNullType(paramType)) {
3550 if (NonNullArgs.empty())
3551 NonNullArgs.resize(Args.size());
3552
3553 NonNullArgs.set(Index);
3554 }
3555
3556 ++Index;
3557 }
3558 }
3559 }
3560
3561 // Check for non-null arguments.
3562 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3563 ArgIndex != ArgIndexEnd; ++ArgIndex) {
3564 if (NonNullArgs[ArgIndex])
3565 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
3566 }
3567}
3568
3569void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
3570 StringRef ParamName, QualType ArgTy,
3571 QualType ParamTy) {
3572
3573 // If a function accepts a pointer or reference type
3574 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
3575 return;
3576
3577 // If the parameter is a pointer type, get the pointee type for the
3578 // argument too. If the parameter is a reference type, don't try to get
3579 // the pointee type for the argument.
3580 if (ParamTy->isPointerType())
3581 ArgTy = ArgTy->getPointeeType();
3582
3583 // Remove reference or pointer
3584 ParamTy = ParamTy->getPointeeType();
3585
3586 // Find expected alignment, and the actual alignment of the passed object.
3587 // getTypeAlignInChars requires complete types
3588 if (ArgTy.isNull() || ParamTy->isDependentType() ||
3589 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
3590 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
3591 return;
3592
3593 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
3594 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
3595
3596 // If the argument is less aligned than the parameter, there is a
3597 // potential alignment issue.
3598 if (ArgAlign < ParamAlign)
3599 Diag(Loc, diag::warn_param_mismatched_alignment)
3600 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
3601 << ParamName << (FDecl != nullptr) << FDecl;
3602}
3603
3604void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
3605 const Expr *ThisArg,
3607 if (!FD || Args.empty())
3608 return;
3609 auto GetArgAt = [&](int Idx) -> const Expr * {
3610 if (Idx == LifetimeCaptureByAttr::Global ||
3611 Idx == LifetimeCaptureByAttr::Unknown)
3612 return nullptr;
3613 if (IsMemberFunction && Idx == 0)
3614 return ThisArg;
3615 return Args[Idx - IsMemberFunction];
3616 };
3617 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
3618 unsigned ArgIdx) {
3619 if (!Attr)
3620 return;
3621
3622 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
3623 for (int CapturingParamIdx : Attr->params()) {
3624 // lifetime_capture_by(this) case is handled in the lifetimebound expr
3625 // initialization codepath.
3626 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
3627 isa<CXXConstructorDecl>(FD))
3628 continue;
3629 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
3630 CapturingEntity CE{Capturing};
3631 // Ensure that 'Captured' outlives the 'Capturing' entity.
3632 checkCaptureByLifetime(*this, CE, Captured);
3633 }
3634 };
3635 for (unsigned I = 0; I < FD->getNumParams(); ++I)
3636 HandleCaptureByAttr(FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>(),
3637 I + IsMemberFunction);
3638 // Check when the implicit object param is captured.
3639 if (IsMemberFunction) {
3640 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
3641 if (!TSI)
3642 return;
3644 for (TypeLoc TL = TSI->getTypeLoc();
3645 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
3646 TL = ATL.getModifiedLoc())
3647 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
3648 }
3649}
3650
3652 const Expr *ThisArg, ArrayRef<const Expr *> Args,
3653 bool IsMemberFunction, SourceLocation Loc,
3655 // FIXME: We should check as much as we can in the template definition.
3657 return;
3658
3659 // Printf and scanf checking.
3660 llvm::SmallBitVector CheckedVarArgs;
3661 if (FDecl) {
3662 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
3663 // Only create vector if there are format attributes.
3664 CheckedVarArgs.resize(Args.size());
3665 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
3666 CheckedVarArgs);
3667 }
3668
3669 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3670 CheckedVarArgs.resize(Args.size());
3671 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
3672 CheckedVarArgs);
3673 }
3674 }
3675
3676 // Refuse POD arguments that weren't caught by the format string
3677 // checks above.
3678 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3679 if (CallType != VariadicCallType::DoesNotApply &&
3680 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
3681 unsigned NumParams = Proto ? Proto->getNumParams()
3682 : isa_and_nonnull<FunctionDecl>(FDecl)
3683 ? cast<FunctionDecl>(FDecl)->getNumParams()
3684 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
3685 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3686 : 0;
3687
3688 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
3689 // Args[ArgIdx] can be null in malformed code.
3690 if (const Expr *Arg = Args[ArgIdx]) {
3691 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3692 checkVariadicArgument(Arg, CallType);
3693 }
3694 }
3695 }
3696 if (FD)
3697 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
3698 if (FDecl || Proto) {
3699 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
3700
3701 // Type safety checking.
3702 if (FDecl) {
3703 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
3704 CheckArgumentWithTypeTag(I, Args, Loc);
3705 }
3706 }
3707
3708 // Check that passed arguments match the alignment of original arguments.
3709 // Try to get the missing prototype from the declaration.
3710 if (!Proto && FDecl) {
3711 const auto *FT = FDecl->getFunctionType();
3712 if (isa_and_nonnull<FunctionProtoType>(FT))
3713 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
3714 }
3715 if (Proto) {
3716 // For variadic functions, we may have more args than parameters.
3717 // For some K&R functions, we may have less args than parameters.
3718 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
3719 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
3720 bool IsScalableArg = false;
3721 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
3722 // Args[ArgIdx] can be null in malformed code.
3723 if (const Expr *Arg = Args[ArgIdx]) {
3724 if (Arg->containsErrors())
3725 continue;
3726
3727 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
3728 FDecl->hasLinkage() &&
3729 FDecl->getFormalLinkage() != Linkage::Internal &&
3731 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
3732
3733 QualType ParamTy = Proto->getParamType(ArgIdx);
3734 if (ParamTy->isSizelessVectorType())
3735 IsScalableArg = true;
3736 QualType ArgTy = Arg->getType();
3737 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
3738 ArgTy, ParamTy);
3739 }
3740 }
3741
3742 // If the callee has an AArch64 SME attribute to indicate that it is an
3743 // __arm_streaming function, then the caller requires SME to be available.
3746 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
3747 llvm::StringMap<bool> CallerFeatureMap;
3748 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
3749 if (!CallerFeatureMap.contains("sme"))
3750 Diag(Loc, diag::err_sme_call_in_non_sme_target);
3751 } else if (!Context.getTargetInfo().hasFeature("sme")) {
3752 Diag(Loc, diag::err_sme_call_in_non_sme_target);
3753 }
3754 }
3755
3756 // If the call requires a streaming-mode change and has scalable vector
3757 // arguments or return values, then warn the user that the streaming and
3758 // non-streaming vector lengths may be different.
3759 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
3760 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
3761 (IsScalableArg || IsScalableRet)) {
3762 bool IsCalleeStreaming =
3764 bool IsCalleeStreamingCompatible =
3765 ExtInfo.AArch64SMEAttributes &
3767 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
3768 if (!IsCalleeStreamingCompatible &&
3769 (CallerFnType == SemaARM::ArmStreamingCompatible ||
3770 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
3771 if (IsScalableArg)
3772 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
3773 << /*IsArg=*/true;
3774 if (IsScalableRet)
3775 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
3776 << /*IsArg=*/false;
3777 }
3778 }
3779
3780 FunctionType::ArmStateValue CalleeArmZAState =
3782 FunctionType::ArmStateValue CalleeArmZT0State =
3784 if (CalleeArmZAState != FunctionType::ARM_None ||
3785 CalleeArmZT0State != FunctionType::ARM_None) {
3786 bool CallerHasZAState = false;
3787 bool CallerHasZT0State = false;
3788 if (CallerFD) {
3789 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
3790 if (Attr && Attr->isNewZA())
3791 CallerHasZAState = true;
3792 if (Attr && Attr->isNewZT0())
3793 CallerHasZT0State = true;
3794 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
3795 CallerHasZAState |=
3797 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
3799 CallerHasZT0State |=
3801 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
3803 }
3804 }
3805
3806 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
3807 Diag(Loc, diag::err_sme_za_call_no_za_state);
3808
3809 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
3810 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
3811
3812 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
3813 CalleeArmZT0State != FunctionType::ARM_None) {
3814 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
3815 Diag(Loc, diag::note_sme_use_preserves_za);
3816 }
3817 }
3818 }
3819
3820 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
3821 auto *AA = FDecl->getAttr<AllocAlignAttr>();
3822 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
3823 if (!Arg->isValueDependent()) {
3824 Expr::EvalResult Align;
3825 if (Arg->EvaluateAsInt(Align, Context)) {
3826 const llvm::APSInt &I = Align.Val.getInt();
3827 if (!I.isPowerOf2())
3828 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
3829 << Arg->getSourceRange();
3830
3831 if (I > Sema::MaximumAlignment)
3832 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
3833 << Arg->getSourceRange() << Sema::MaximumAlignment;
3834 }
3835 }
3836 }
3837
3838 if (FD)
3839 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
3840}
3841
3843 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
3845 }
3846}
3847
3848void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
3850 const FunctionProtoType *Proto,
3852 VariadicCallType CallType = Proto->isVariadic()
3855
3856 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
3857 CheckArgAlignment(
3858 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
3859 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
3860
3861 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
3862 Loc, SourceRange(), CallType);
3863}
3864
3866 const FunctionProtoType *Proto) {
3867 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
3868 isa<CXXMethodDecl>(FDecl);
3869 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
3870 IsMemberOperatorCall;
3871 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
3872 TheCall->getCallee());
3873 Expr** Args = TheCall->getArgs();
3874 unsigned NumArgs = TheCall->getNumArgs();
3875
3876 Expr *ImplicitThis = nullptr;
3877 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
3878 // If this is a call to a member operator, hide the first
3879 // argument from checkCall.
3880 // FIXME: Our choice of AST representation here is less than ideal.
3881 ImplicitThis = Args[0];
3882 ++Args;
3883 --NumArgs;
3884 } else if (IsMemberFunction && !FDecl->isStatic() &&
3886 ImplicitThis =
3887 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3888
3889 if (ImplicitThis) {
3890 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
3891 // used.
3892 QualType ThisType = ImplicitThis->getType();
3893 if (!ThisType->isPointerType()) {
3894 assert(!ThisType->isReferenceType());
3895 ThisType = Context.getPointerType(ThisType);
3896 }
3897
3898 QualType ThisTypeFromDecl = Context.getPointerType(
3899 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
3900
3901 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
3902 ThisTypeFromDecl);
3903 }
3904
3905 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
3906 IsMemberFunction, TheCall->getRParenLoc(),
3907 TheCall->getCallee()->getSourceRange(), CallType);
3908
3909 IdentifierInfo *FnInfo = FDecl->getIdentifier();
3910 // None of the checks below are needed for functions that don't have
3911 // simple names (e.g., C++ conversion functions).
3912 if (!FnInfo)
3913 return false;
3914
3915 // Enforce TCB except for builtin calls, which are always allowed.
3916 if (FDecl->getBuiltinID() == 0)
3917 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
3918
3919 CheckAbsoluteValueFunction(TheCall, FDecl);
3920 CheckMaxUnsignedZero(TheCall, FDecl);
3921 CheckInfNaNFunction(TheCall, FDecl);
3922
3923 if (getLangOpts().ObjC)
3924 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
3925
3926 unsigned CMId = FDecl->getMemoryFunctionKind();
3927
3928 // Handle memory setting and copying functions.
3929 switch (CMId) {
3930 case 0:
3931 return false;
3932 case Builtin::BIstrlcpy: // fallthrough
3933 case Builtin::BIstrlcat:
3934 CheckStrlcpycatArguments(TheCall, FnInfo);
3935 break;
3936 case Builtin::BIstrncat:
3937 CheckStrncatArguments(TheCall, FnInfo);
3938 break;
3939 case Builtin::BIfree:
3940 CheckFreeArguments(TheCall);
3941 break;
3942 default:
3943 CheckMemaccessArguments(TheCall, CMId, FnInfo);
3944 }
3945
3946 return false;
3947}
3948
3949bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3950 const FunctionProtoType *Proto) {
3951 QualType Ty;
3952 if (const auto *V = dyn_cast<VarDecl>(NDecl))
3953 Ty = V->getType().getNonReferenceType();
3954 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
3955 Ty = F->getType().getNonReferenceType();
3956 else
3957 return false;
3958
3959 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
3960 !Ty->isFunctionProtoType())
3961 return false;
3962
3963 VariadicCallType CallType;
3964 if (!Proto || !Proto->isVariadic()) {
3966 } else if (Ty->isBlockPointerType()) {
3967 CallType = VariadicCallType::Block;
3968 } else { // Ty->isFunctionPointerType()
3969 CallType = VariadicCallType::Function;
3970 }
3971
3972 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
3973 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3974 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
3975 TheCall->getCallee()->getSourceRange(), CallType);
3976
3977 return false;
3978}
3979
3980bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
3981 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
3982 TheCall->getCallee());
3983 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
3984 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3985 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
3986 TheCall->getCallee()->getSourceRange(), CallType);
3987
3988 return false;
3989}
3990
3991static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
3992 if (!llvm::isValidAtomicOrderingCABI(Ordering))
3993 return false;
3994
3995 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
3996 switch (Op) {
3997 case AtomicExpr::AO__c11_atomic_init:
3998 case AtomicExpr::AO__opencl_atomic_init:
3999 llvm_unreachable("There is no ordering argument for an init");
4000
4001 case AtomicExpr::AO__c11_atomic_load:
4002 case AtomicExpr::AO__opencl_atomic_load:
4003 case AtomicExpr::AO__hip_atomic_load:
4004 case AtomicExpr::AO__atomic_load_n:
4005 case AtomicExpr::AO__atomic_load:
4006 case AtomicExpr::AO__scoped_atomic_load_n:
4007 case AtomicExpr::AO__scoped_atomic_load:
4008 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4009 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4010
4011 case AtomicExpr::AO__c11_atomic_store:
4012 case AtomicExpr::AO__opencl_atomic_store:
4013 case AtomicExpr::AO__hip_atomic_store:
4014 case AtomicExpr::AO__atomic_store:
4015 case AtomicExpr::AO__atomic_store_n:
4016 case AtomicExpr::AO__scoped_atomic_store:
4017 case AtomicExpr::AO__scoped_atomic_store_n:
4018 case AtomicExpr::AO__atomic_clear:
4019 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4020 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4021 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4022
4023 default:
4024 return true;
4025 }
4026}
4027
4028ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4030 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4031 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4032 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4033 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4034 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4035 Op);
4036}
4037
4039 SourceLocation RParenLoc, MultiExprArg Args,
4041 AtomicArgumentOrder ArgOrder) {
4042 // All the non-OpenCL operations take one of the following forms.
4043 // The OpenCL operations take the __c11 forms with one extra argument for
4044 // synchronization scope.
4045 enum {
4046 // C __c11_atomic_init(A *, C)
4047 Init,
4048
4049 // C __c11_atomic_load(A *, int)
4050 Load,
4051
4052 // void __atomic_load(A *, CP, int)
4053 LoadCopy,
4054
4055 // void __atomic_store(A *, CP, int)
4056 Copy,
4057
4058 // C __c11_atomic_add(A *, M, int)
4059 Arithmetic,
4060
4061 // C __atomic_exchange_n(A *, CP, int)
4062 Xchg,
4063
4064 // void __atomic_exchange(A *, C *, CP, int)
4065 GNUXchg,
4066
4067 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4068 C11CmpXchg,
4069
4070 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4071 GNUCmpXchg,
4072
4073 // bool __atomic_test_and_set(A *, int)
4074 TestAndSetByte,
4075
4076 // void __atomic_clear(A *, int)
4077 ClearByte,
4078 } Form = Init;
4079
4080 const unsigned NumForm = ClearByte + 1;
4081 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
4082 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
4083 // where:
4084 // C is an appropriate type,
4085 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4086 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4087 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4088 // the int parameters are for orderings.
4089
4090 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4091 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4092 "need to update code for modified forms");
4093 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
4094 AtomicExpr::AO__atomic_xor_fetch + 1 ==
4095 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
4096 "need to update code for modified C11 atomics");
4097 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
4098 Op <= AtomicExpr::AO__opencl_atomic_store;
4099 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
4100 Op <= AtomicExpr::AO__hip_atomic_store;
4101 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
4102 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
4103 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
4104 Op <= AtomicExpr::AO__c11_atomic_store) ||
4105 IsOpenCL;
4106 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4107 Op == AtomicExpr::AO__atomic_store_n ||
4108 Op == AtomicExpr::AO__atomic_exchange_n ||
4109 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
4110 Op == AtomicExpr::AO__scoped_atomic_load_n ||
4111 Op == AtomicExpr::AO__scoped_atomic_store_n ||
4112 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
4113 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
4114 // Bit mask for extra allowed value types other than integers for atomic
4115 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
4116 // allow floating point.
4117 enum ArithOpExtraValueType {
4118 AOEVT_None = 0,
4119 AOEVT_Pointer = 1,
4120 AOEVT_FP = 2,
4121 };
4122 unsigned ArithAllows = AOEVT_None;
4123
4124 switch (Op) {
4125 case AtomicExpr::AO__c11_atomic_init:
4126 case AtomicExpr::AO__opencl_atomic_init:
4127 Form = Init;
4128 break;
4129
4130 case AtomicExpr::AO__c11_atomic_load:
4131 case AtomicExpr::AO__opencl_atomic_load:
4132 case AtomicExpr::AO__hip_atomic_load:
4133 case AtomicExpr::AO__atomic_load_n:
4134 case AtomicExpr::AO__scoped_atomic_load_n:
4135 Form = Load;
4136 break;
4137
4138 case AtomicExpr::AO__atomic_load:
4139 case AtomicExpr::AO__scoped_atomic_load:
4140 Form = LoadCopy;
4141 break;
4142
4143 case AtomicExpr::AO__c11_atomic_store:
4144 case AtomicExpr::AO__opencl_atomic_store:
4145 case AtomicExpr::AO__hip_atomic_store:
4146 case AtomicExpr::AO__atomic_store:
4147 case AtomicExpr::AO__atomic_store_n:
4148 case AtomicExpr::AO__scoped_atomic_store:
4149 case AtomicExpr::AO__scoped_atomic_store_n:
4150 Form = Copy;
4151 break;
4152 case AtomicExpr::AO__atomic_fetch_add:
4153 case AtomicExpr::AO__atomic_fetch_sub:
4154 case AtomicExpr::AO__atomic_add_fetch:
4155 case AtomicExpr::AO__atomic_sub_fetch:
4156 case AtomicExpr::AO__scoped_atomic_fetch_add:
4157 case AtomicExpr::AO__scoped_atomic_fetch_sub:
4158 case AtomicExpr::AO__scoped_atomic_add_fetch:
4159 case AtomicExpr::AO__scoped_atomic_sub_fetch:
4160 case AtomicExpr::AO__c11_atomic_fetch_add:
4161 case AtomicExpr::AO__c11_atomic_fetch_sub:
4162 case AtomicExpr::AO__opencl_atomic_fetch_add:
4163 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4164 case AtomicExpr::AO__hip_atomic_fetch_add:
4165 case AtomicExpr::AO__hip_atomic_fetch_sub:
4166 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4167 Form = Arithmetic;
4168 break;
4169 case AtomicExpr::AO__atomic_fetch_max:
4170 case AtomicExpr::AO__atomic_fetch_min:
4171 case AtomicExpr::AO__atomic_max_fetch:
4172 case AtomicExpr::AO__atomic_min_fetch:
4173 case AtomicExpr::AO__scoped_atomic_fetch_max:
4174 case AtomicExpr::AO__scoped_atomic_fetch_min:
4175 case AtomicExpr::AO__scoped_atomic_max_fetch:
4176 case AtomicExpr::AO__scoped_atomic_min_fetch:
4177 case AtomicExpr::AO__c11_atomic_fetch_max:
4178 case AtomicExpr::AO__c11_atomic_fetch_min:
4179 case AtomicExpr::AO__opencl_atomic_fetch_max:
4180 case AtomicExpr::AO__opencl_atomic_fetch_min:
4181 case AtomicExpr::AO__hip_atomic_fetch_max:
4182 case AtomicExpr::AO__hip_atomic_fetch_min:
4183 ArithAllows = AOEVT_FP;
4184 Form = Arithmetic;
4185 break;
4186 case AtomicExpr::AO__c11_atomic_fetch_and:
4187 case AtomicExpr::AO__c11_atomic_fetch_or:
4188 case AtomicExpr::AO__c11_atomic_fetch_xor:
4189 case AtomicExpr::AO__hip_atomic_fetch_and:
4190 case AtomicExpr::AO__hip_atomic_fetch_or:
4191 case AtomicExpr::AO__hip_atomic_fetch_xor:
4192 case AtomicExpr::AO__c11_atomic_fetch_nand:
4193 case AtomicExpr::AO__opencl_atomic_fetch_and:
4194 case AtomicExpr::AO__opencl_atomic_fetch_or:
4195 case AtomicExpr::AO__opencl_atomic_fetch_xor:
4196 case AtomicExpr::AO__atomic_fetch_and:
4197 case AtomicExpr::AO__atomic_fetch_or:
4198 case AtomicExpr::AO__atomic_fetch_xor:
4199 case AtomicExpr::AO__atomic_fetch_nand:
4200 case AtomicExpr::AO__atomic_and_fetch:
4201 case AtomicExpr::AO__atomic_or_fetch:
4202 case AtomicExpr::AO__atomic_xor_fetch:
4203 case AtomicExpr::AO__atomic_nand_fetch:
4204 case AtomicExpr::AO__scoped_atomic_fetch_and:
4205 case AtomicExpr::AO__scoped_atomic_fetch_or:
4206 case AtomicExpr::AO__scoped_atomic_fetch_xor:
4207 case AtomicExpr::AO__scoped_atomic_fetch_nand:
4208 case AtomicExpr::AO__scoped_atomic_and_fetch:
4209 case AtomicExpr::AO__scoped_atomic_or_fetch:
4210 case AtomicExpr::AO__scoped_atomic_xor_fetch:
4211 case AtomicExpr::AO__scoped_atomic_nand_fetch:
4212 Form = Arithmetic;
4213 break;
4214
4215 case AtomicExpr::AO__c11_atomic_exchange:
4216 case AtomicExpr::AO__hip_atomic_exchange:
4217 case AtomicExpr::AO__opencl_atomic_exchange:
4218 case AtomicExpr::AO__atomic_exchange_n:
4219 case AtomicExpr::AO__scoped_atomic_exchange_n:
4220 Form = Xchg;
4221 break;
4222
4223 case AtomicExpr::AO__atomic_exchange:
4224 case AtomicExpr::AO__scoped_atomic_exchange:
4225 Form = GNUXchg;
4226 break;
4227
4228 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4229 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4230 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4231 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4232 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4233 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4234 Form = C11CmpXchg;
4235 break;
4236
4237 case AtomicExpr::AO__atomic_compare_exchange:
4238 case AtomicExpr::AO__atomic_compare_exchange_n:
4239 case AtomicExpr::AO__scoped_atomic_compare_exchange:
4240 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
4241 Form = GNUCmpXchg;
4242 break;
4243
4244 case AtomicExpr::AO__atomic_test_and_set:
4245 Form = TestAndSetByte;
4246 break;
4247
4248 case AtomicExpr::AO__atomic_clear:
4249 Form = ClearByte;
4250 break;
4251 }
4252
4253 unsigned AdjustedNumArgs = NumArgs[Form];
4254 if ((IsOpenCL || IsHIP || IsScoped) &&
4255 Op != AtomicExpr::AO__opencl_atomic_init)
4256 ++AdjustedNumArgs;
4257 // Check we have the right number of arguments.
4258 if (Args.size() < AdjustedNumArgs) {
4259 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4260 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4261 << /*is non object*/ 0 << ExprRange;
4262 return ExprError();
4263 } else if (Args.size() > AdjustedNumArgs) {
4264 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4265 diag::err_typecheck_call_too_many_args)
4266 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4267 << /*is non object*/ 0 << ExprRange;
4268 return ExprError();
4269 }
4270
4271 // Inspect the first argument of the atomic operation.
4272 Expr *Ptr = Args[0];
4274 if (ConvertedPtr.isInvalid())
4275 return ExprError();
4276
4277 Ptr = ConvertedPtr.get();
4278 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4279 if (!pointerType) {
4280 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4281 << Ptr->getType() << 0 << Ptr->getSourceRange();
4282 return ExprError();
4283 }
4284
4285 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4286 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4287 QualType ValType = AtomTy; // 'C'
4288 if (IsC11) {
4289 if (!AtomTy->isAtomicType()) {
4290 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4291 << Ptr->getType() << Ptr->getSourceRange();
4292 return ExprError();
4293 }
4294 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4296 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4297 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4298 << Ptr->getSourceRange();
4299 return ExprError();
4300 }
4301 ValType = AtomTy->castAs<AtomicType>()->getValueType();
4302 } else if (Form != Load && Form != LoadCopy) {
4303 if (ValType.isConstQualified()) {
4304 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4305 << Ptr->getType() << Ptr->getSourceRange();
4306 return ExprError();
4307 }
4308 }
4309
4310 if (Form != TestAndSetByte && Form != ClearByte) {
4311 // Pointer to object of size zero is not allowed.
4312 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
4313 diag::err_incomplete_type))
4314 return ExprError();
4315
4316 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
4317 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4318 << Ptr->getType() << 1 << Ptr->getSourceRange();
4319 return ExprError();
4320 }
4321 } else {
4322 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
4323 // non-const pointer type, including void* and pointers to incomplete
4324 // structs, but only access the first byte.
4325 AtomTy = Context.CharTy;
4326 AtomTy = AtomTy.withCVRQualifiers(
4327 pointerType->getPointeeType().getCVRQualifiers());
4328 QualType PointerQT = Context.getPointerType(AtomTy);
4329 pointerType = PointerQT->getAs<PointerType>();
4330 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
4331 ValType = AtomTy;
4332 }
4333
4334 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
4335 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4336 Diag(ExprRange.getBegin(),
4337 diag::err_atomic_op_needs_non_address_discriminated_pointer)
4338 << 0 << Ptr->getType() << Ptr->getSourceRange();
4339 return ExprError();
4340 }
4341
4342 // For an arithmetic operation, the implied arithmetic must be well-formed.
4343 if (Form == Arithmetic) {
4344 // GCC does not enforce these rules for GNU atomics, but we do to help catch
4345 // trivial type errors.
4346 auto IsAllowedValueType = [&](QualType ValType,
4347 unsigned AllowedType) -> bool {
4348 if (ValType->isIntegerType())
4349 return true;
4350 if (ValType->isPointerType())
4351 return AllowedType & AOEVT_Pointer;
4352 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
4353 return false;
4354 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
4355 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
4357 &llvm::APFloat::x87DoubleExtended())
4358 return false;
4359 return true;
4360 };
4361 if (!IsAllowedValueType(ValType, ArithAllows)) {
4362 auto DID = ArithAllows & AOEVT_FP
4363 ? (ArithAllows & AOEVT_Pointer
4364 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
4365 : diag::err_atomic_op_needs_atomic_int_or_fp)
4366 : diag::err_atomic_op_needs_atomic_int;
4367 Diag(ExprRange.getBegin(), DID)
4368 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4369 return ExprError();
4370 }
4371 if (IsC11 && ValType->isPointerType() &&
4373 diag::err_incomplete_type)) {
4374 return ExprError();
4375 }
4376 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4377 // For __atomic_*_n operations, the value type must be a scalar integral or
4378 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4379 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4380 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4381 return ExprError();
4382 }
4383
4384 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4385 !AtomTy->isScalarType()) {
4386 // For GNU atomics, require a trivially-copyable type. This is not part of
4387 // the GNU atomics specification but we enforce it for consistency with
4388 // other atomics which generally all require a trivially-copyable type. This
4389 // is because atomics just copy bits.
4390 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4391 << Ptr->getType() << Ptr->getSourceRange();
4392 return ExprError();
4393 }
4394
4395 switch (ValType.getObjCLifetime()) {
4398 // okay
4399 break;
4400
4404 // FIXME: Can this happen? By this point, ValType should be known
4405 // to be trivially copyable.
4406 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4407 << ValType << Ptr->getSourceRange();
4408 return ExprError();
4409 }
4410
4411 // All atomic operations have an overload which takes a pointer to a volatile
4412 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4413 // into the result or the other operands. Similarly atomic_load takes a
4414 // pointer to a const 'A'.
4415 ValType.removeLocalVolatile();
4416 ValType.removeLocalConst();
4417 QualType ResultType = ValType;
4418 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
4419 Form == ClearByte)
4420 ResultType = Context.VoidTy;
4421 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
4422 ResultType = Context.BoolTy;
4423
4424 // The type of a parameter passed 'by value'. In the GNU atomics, such
4425 // arguments are actually passed as pointers.
4426 QualType ByValType = ValType; // 'CP'
4427 bool IsPassedByAddress = false;
4428 if (!IsC11 && !IsHIP && !IsN) {
4429 ByValType = Ptr->getType();
4430 IsPassedByAddress = true;
4431 }
4432
4433 SmallVector<Expr *, 5> APIOrderedArgs;
4434 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4435 APIOrderedArgs.push_back(Args[0]);
4436 switch (Form) {
4437 case Init:
4438 case Load:
4439 APIOrderedArgs.push_back(Args[1]); // Val1/Order
4440 break;
4441 case LoadCopy:
4442 case Copy:
4443 case Arithmetic:
4444 case Xchg:
4445 APIOrderedArgs.push_back(Args[2]); // Val1
4446 APIOrderedArgs.push_back(Args[1]); // Order
4447 break;
4448 case GNUXchg:
4449 APIOrderedArgs.push_back(Args[2]); // Val1
4450 APIOrderedArgs.push_back(Args[3]); // Val2
4451 APIOrderedArgs.push_back(Args[1]); // Order
4452 break;
4453 case C11CmpXchg:
4454 APIOrderedArgs.push_back(Args[2]); // Val1
4455 APIOrderedArgs.push_back(Args[4]); // Val2
4456 APIOrderedArgs.push_back(Args[1]); // Order
4457 APIOrderedArgs.push_back(Args[3]); // OrderFail
4458 break;
4459 case GNUCmpXchg:
4460 APIOrderedArgs.push_back(Args[2]); // Val1
4461 APIOrderedArgs.push_back(Args[4]); // Val2
4462 APIOrderedArgs.push_back(Args[5]); // Weak
4463 APIOrderedArgs.push_back(Args[1]); // Order
4464 APIOrderedArgs.push_back(Args[3]); // OrderFail
4465 break;
4466 case TestAndSetByte:
4467 case ClearByte:
4468 APIOrderedArgs.push_back(Args[1]); // Order
4469 break;
4470 }
4471 } else
4472 APIOrderedArgs.append(Args.begin(), Args.end());
4473
4474 // The first argument's non-CV pointer type is used to deduce the type of
4475 // subsequent arguments, except for:
4476 // - weak flag (always converted to bool)
4477 // - memory order (always converted to int)
4478 // - scope (always converted to int)
4479 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4480 QualType Ty;
4481 if (i < NumVals[Form] + 1) {
4482 switch (i) {
4483 case 0:
4484 // The first argument is always a pointer. It has a fixed type.
4485 // It is always dereferenced, a nullptr is undefined.
4486 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4487 // Nothing else to do: we already know all we want about this pointer.
4488 continue;
4489 case 1:
4490 // The second argument is the non-atomic operand. For arithmetic, this
4491 // is always passed by value, and for a compare_exchange it is always
4492 // passed by address. For the rest, GNU uses by-address and C11 uses
4493 // by-value.
4494 assert(Form != Load);
4495 if (Form == Arithmetic && ValType->isPointerType())
4497 else if (Form == Init || Form == Arithmetic)
4498 Ty = ValType;
4499 else if (Form == Copy || Form == Xchg) {
4500 if (IsPassedByAddress) {
4501 // The value pointer is always dereferenced, a nullptr is undefined.
4502 CheckNonNullArgument(*this, APIOrderedArgs[i],
4503 ExprRange.getBegin());
4504 }
4505 Ty = ByValType;
4506 } else {
4507 Expr *ValArg = APIOrderedArgs[i];
4508 // The value pointer is always dereferenced, a nullptr is undefined.
4509 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4511 // Keep address space of non-atomic pointer type.
4512 if (const PointerType *PtrTy =
4513 ValArg->getType()->getAs<PointerType>()) {
4514 AS = PtrTy->getPointeeType().getAddressSpace();
4515 }
4518 }
4519 break;
4520 case 2:
4521 // The third argument to compare_exchange / GNU exchange is the desired
4522 // value, either by-value (for the C11 and *_n variant) or as a pointer.
4523 if (IsPassedByAddress)
4524 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4525 Ty = ByValType;
4526 break;
4527 case 3:
4528 // The fourth argument to GNU compare_exchange is a 'weak' flag.
4529 Ty = Context.BoolTy;
4530 break;
4531 }
4532 } else {
4533 // The order(s) and scope are always converted to int.
4534 Ty = Context.IntTy;
4535 }
4536
4537 InitializedEntity Entity =
4539 ExprResult Arg = APIOrderedArgs[i];
4540 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4541 if (Arg.isInvalid())
4542 return true;
4543 APIOrderedArgs[i] = Arg.get();
4544 }
4545
4546 // Permute the arguments into a 'consistent' order.
4547 SmallVector<Expr*, 5> SubExprs;
4548 SubExprs.push_back(Ptr);
4549 switch (Form) {
4550 case Init:
4551 // Note, AtomicExpr::getVal1() has a special case for this atomic.
4552 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4553 break;
4554 case Load:
4555 case TestAndSetByte:
4556 case ClearByte:
4557 SubExprs.push_back(APIOrderedArgs[1]); // Order
4558 break;
4559 case LoadCopy:
4560 case Copy:
4561 case Arithmetic:
4562 case Xchg:
4563 SubExprs.push_back(APIOrderedArgs[2]); // Order
4564 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4565 break;
4566 case GNUXchg:
4567 // Note, AtomicExpr::getVal2() has a special case for this atomic.
4568 SubExprs.push_back(APIOrderedArgs[3]); // Order
4569 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4570 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4571 break;
4572 case C11CmpXchg:
4573 SubExprs.push_back(APIOrderedArgs[3]); // Order
4574 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4575 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4576 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4577 break;
4578 case GNUCmpXchg:
4579 SubExprs.push_back(APIOrderedArgs[4]); // Order
4580 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4581 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4582 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4583 SubExprs.push_back(APIOrderedArgs[3]); // Weak
4584 break;
4585 }
4586
4587 // If the memory orders are constants, check they are valid.
4588 if (SubExprs.size() >= 2 && Form != Init) {
4589 std::optional<llvm::APSInt> Success =
4590 SubExprs[1]->getIntegerConstantExpr(Context);
4591 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
4592 Diag(SubExprs[1]->getBeginLoc(),
4593 diag::warn_atomic_op_has_invalid_memory_order)
4594 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
4595 << SubExprs[1]->getSourceRange();
4596 }
4597 if (SubExprs.size() >= 5) {
4598 if (std::optional<llvm::APSInt> Failure =
4599 SubExprs[3]->getIntegerConstantExpr(Context)) {
4600 if (!llvm::is_contained(
4601 {llvm::AtomicOrderingCABI::relaxed,
4602 llvm::AtomicOrderingCABI::consume,
4603 llvm::AtomicOrderingCABI::acquire,
4604 llvm::AtomicOrderingCABI::seq_cst},
4605 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
4606 Diag(SubExprs[3]->getBeginLoc(),
4607 diag::warn_atomic_op_has_invalid_memory_order)
4608 << /*failure=*/2 << SubExprs[3]->getSourceRange();
4609 }
4610 }
4611 }
4612 }
4613
4614 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4615 auto *Scope = Args[Args.size() - 1];
4616 if (std::optional<llvm::APSInt> Result =
4617 Scope->getIntegerConstantExpr(Context)) {
4618 if (!ScopeModel->isValid(Result->getZExtValue()))
4619 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
4620 << Scope->getSourceRange();
4621 }
4622 SubExprs.push_back(Scope);
4623 }
4624
4625 AtomicExpr *AE = new (Context)
4626 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4627
4628 if ((Op == AtomicExpr::AO__c11_atomic_load ||
4629 Op == AtomicExpr::AO__c11_atomic_store ||
4630 Op == AtomicExpr::AO__opencl_atomic_load ||
4631 Op == AtomicExpr::AO__hip_atomic_load ||
4632 Op == AtomicExpr::AO__opencl_atomic_store ||
4633 Op == AtomicExpr::AO__hip_atomic_store) &&
4635 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4636 << ((Op == AtomicExpr::AO__c11_atomic_load ||
4637 Op == AtomicExpr::AO__opencl_atomic_load ||
4638 Op == AtomicExpr::AO__hip_atomic_load)
4639 ? 0
4640 : 1);
4641
4642 if (ValType->isBitIntType()) {
4643 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
4644 return ExprError();
4645 }
4646
4647 return AE;
4648}
4649
4650/// checkBuiltinArgument - Given a call to a builtin function, perform
4651/// normal type-checking on the given argument, updating the call in
4652/// place. This is useful when a builtin function requires custom
4653/// type-checking for some of its arguments but not necessarily all of
4654/// them.
4655///
4656/// Returns true on error.
4657static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4658 FunctionDecl *Fn = E->getDirectCallee();
4659 assert(Fn && "builtin call without direct callee!");
4660
4661 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4662 InitializedEntity Entity =
4664
4665 ExprResult Arg = E->getArg(ArgIndex);
4666 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4667 if (Arg.isInvalid())
4668 return true;
4669
4670 E->setArg(ArgIndex, Arg.get());
4671 return false;
4672}
4673
4674ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
4675 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4676 Expr *Callee = TheCall->getCallee();
4677 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4678 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4679
4680 // Ensure that we have at least one argument to do type inference from.
4681 if (TheCall->getNumArgs() < 1) {
4682 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4683 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
4684 << Callee->getSourceRange();
4685 return ExprError();
4686 }
4687
4688 // Inspect the first argument of the atomic builtin. This should always be
4689 // a pointer type, whose element is an integral scalar or pointer type.
4690 // Because it is a pointer type, we don't have to worry about any implicit
4691 // casts here.
4692 // FIXME: We don't allow floating point scalars as input.
4693 Expr *FirstArg = TheCall->getArg(0);
4694 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4695 if (FirstArgResult.isInvalid())
4696 return ExprError();
4697 FirstArg = FirstArgResult.get();
4698 TheCall->setArg(0, FirstArg);
4699
4700 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4701 if (!pointerType) {
4702 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4703 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4704 return ExprError();
4705 }
4706
4707 QualType ValType = pointerType->getPointeeType();
4708 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4709 !ValType->isBlockPointerType()) {
4710 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4711 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4712 return ExprError();
4713 }
4714 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
4715 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4716 Diag(FirstArg->getBeginLoc(),
4717 diag::err_atomic_op_needs_non_address_discriminated_pointer)
4718 << 1 << ValType << FirstArg->getSourceRange();
4719 return ExprError();
4720 }
4721
4722 if (ValType.isConstQualified()) {
4723 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4724 << FirstArg->getType() << FirstArg->getSourceRange();
4725 return ExprError();
4726 }
4727
4728 switch (ValType.getObjCLifetime()) {
4731 // okay
4732 break;
4733
4737 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4738 << ValType << FirstArg->getSourceRange();
4739 return ExprError();
4740 }
4741
4742 // Strip any qualifiers off ValType.
4743 ValType = ValType.getUnqualifiedType();
4744
4745 // The majority of builtins return a value, but a few have special return
4746 // types, so allow them to override appropriately below.
4747 QualType ResultType = ValType;
4748
4749 // We need to figure out which concrete builtin this maps onto. For example,
4750 // __sync_fetch_and_add with a 2 byte object turns into
4751 // __sync_fetch_and_add_2.
4752#define BUILTIN_ROW(x) \
4753 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4754 Builtin::BI##x##_8, Builtin::BI##x##_16 }
4755
4756 static const unsigned BuiltinIndices[][5] = {
4757 BUILTIN_ROW(__sync_fetch_and_add),
4758 BUILTIN_ROW(__sync_fetch_and_sub),
4759 BUILTIN_ROW(__sync_fetch_and_or),
4760 BUILTIN_ROW(__sync_fetch_and_and),
4761 BUILTIN_ROW(__sync_fetch_and_xor),
4762 BUILTIN_ROW(__sync_fetch_and_nand),
4763
4764 BUILTIN_ROW(__sync_add_and_fetch),
4765 BUILTIN_ROW(__sync_sub_and_fetch),
4766 BUILTIN_ROW(__sync_and_and_fetch),
4767 BUILTIN_ROW(__sync_or_and_fetch),
4768 BUILTIN_ROW(__sync_xor_and_fetch),
4769 BUILTIN_ROW(__sync_nand_and_fetch),
4770
4771 BUILTIN_ROW(__sync_val_compare_and_swap),
4772 BUILTIN_ROW(__sync_bool_compare_and_swap),
4773 BUILTIN_ROW(__sync_lock_test_and_set),
4774 BUILTIN_ROW(__sync_lock_release),
4775 BUILTIN_ROW(__sync_swap)
4776 };
4777#undef BUILTIN_ROW
4778
4779 // Determine the index of the size.
4780 unsigned SizeIndex;
4781 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4782 case 1: SizeIndex = 0; break;
4783 case 2: SizeIndex = 1; break;
4784 case 4: SizeIndex = 2; break;
4785 case 8: SizeIndex = 3; break;
4786 case 16: SizeIndex = 4; break;
4787 default:
4788 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4789 << FirstArg->getType() << FirstArg->getSourceRange();
4790 return ExprError();
4791 }
4792
4793 // Each of these builtins has one pointer argument, followed by some number of
4794 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4795 // that we ignore. Find out which row of BuiltinIndices to read from as well
4796 // as the number of fixed args.
4797 unsigned BuiltinID = FDecl->getBuiltinID();
4798 unsigned BuiltinIndex, NumFixed = 1;
4799 bool WarnAboutSemanticsChange = false;
4800 switch (BuiltinID) {
4801 default: llvm_unreachable("Unknown overloaded atomic builtin!");
4802 case Builtin::BI__sync_fetch_and_add:
4803 case Builtin::BI__sync_fetch_and_add_1:
4804 case Builtin::BI__sync_fetch_and_add_2:
4805 case Builtin::BI__sync_fetch_and_add_4:
4806 case Builtin::BI__sync_fetch_and_add_8:
4807 case Builtin::BI__sync_fetch_and_add_16:
4808 BuiltinIndex = 0;
4809 break;
4810
4811 case Builtin::BI__sync_fetch_and_sub:
4812 case Builtin::BI__sync_fetch_and_sub_1:
4813 case Builtin::BI__sync_fetch_and_sub_2:
4814 case Builtin::BI__sync_fetch_and_sub_4:
4815 case Builtin::BI__sync_fetch_and_sub_8:
4816 case Builtin::BI__sync_fetch_and_sub_16:
4817 BuiltinIndex = 1;
4818 break;
4819
4820 case Builtin::BI__sync_fetch_and_or:
4821 case Builtin::BI__sync_fetch_and_or_1:
4822 case Builtin::BI__sync_fetch_and_or_2:
4823 case Builtin::BI__sync_fetch_and_or_4:
4824 case Builtin::BI__sync_fetch_and_or_8:
4825 case Builtin::BI__sync_fetch_and_or_16:
4826 BuiltinIndex = 2;
4827 break;
4828
4829 case Builtin::BI__sync_fetch_and_and:
4830 case Builtin::BI__sync_fetch_and_and_1:
4831 case Builtin::BI__sync_fetch_and_and_2:
4832 case Builtin::BI__sync_fetch_and_and_4:
4833 case Builtin::BI__sync_fetch_and_and_8:
4834 case Builtin::BI__sync_fetch_and_and_16:
4835 BuiltinIndex = 3;
4836 break;
4837
4838 case Builtin::BI__sync_fetch_and_xor:
4839 case Builtin::BI__sync_fetch_and_xor_1:
4840 case Builtin::BI__sync_fetch_and_xor_2:
4841 case Builtin::BI__sync_fetch_and_xor_4:
4842 case Builtin::BI__sync_fetch_and_xor_8:
4843 case Builtin::BI__sync_fetch_and_xor_16:
4844 BuiltinIndex = 4;
4845 break;
4846
4847 case Builtin::BI__sync_fetch_and_nand:
4848 case Builtin::BI__sync_fetch_and_nand_1:
4849 case Builtin::BI__sync_fetch_and_nand_2:
4850 case Builtin::BI__sync_fetch_and_nand_4:
4851 case Builtin::BI__sync_fetch_and_nand_8:
4852 case Builtin::BI__sync_fetch_and_nand_16:
4853 BuiltinIndex = 5;
4854 WarnAboutSemanticsChange = true;
4855 break;
4856
4857 case Builtin::BI__sync_add_and_fetch:
4858 case Builtin::BI__sync_add_and_fetch_1:
4859 case Builtin::BI__sync_add_and_fetch_2:
4860 case Builtin::BI__sync_add_and_fetch_4:
4861 case Builtin::BI__sync_add_and_fetch_8:
4862 case Builtin::BI__sync_add_and_fetch_16:
4863 BuiltinIndex = 6;
4864 break;
4865
4866 case Builtin::BI__sync_sub_and_fetch:
4867 case Builtin::BI__sync_sub_and_fetch_1:
4868 case Builtin::BI__sync_sub_and_fetch_2:
4869 case Builtin::BI__sync_sub_and_fetch_4:
4870 case Builtin::BI__sync_sub_and_fetch_8:
4871 case Builtin::BI__sync_sub_and_fetch_16:
4872 BuiltinIndex = 7;
4873 break;
4874
4875 case Builtin::BI__sync_and_and_fetch:
4876 case Builtin::BI__sync_and_and_fetch_1:
4877 case Builtin::BI__sync_and_and_fetch_2:
4878 case Builtin::BI__sync_and_and_fetch_4:
4879 case Builtin::BI__sync_and_and_fetch_8:
4880 case Builtin::BI__sync_and_and_fetch_16:
4881 BuiltinIndex = 8;
4882 break;
4883
4884 case Builtin::BI__sync_or_and_fetch:
4885 case Builtin::BI__sync_or_and_fetch_1:
4886 case Builtin::BI__sync_or_and_fetch_2:
4887 case Builtin::BI__sync_or_and_fetch_4:
4888 case Builtin::BI__sync_or_and_fetch_8:
4889 case Builtin::BI__sync_or_and_fetch_16:
4890 BuiltinIndex = 9;
4891 break;
4892
4893 case Builtin::BI__sync_xor_and_fetch:
4894 case Builtin::BI__sync_xor_and_fetch_1:
4895 case Builtin::BI__sync_xor_and_fetch_2:
4896 case Builtin::BI__sync_xor_and_fetch_4:
4897 case Builtin::BI__sync_xor_and_fetch_8:
4898 case Builtin::BI__sync_xor_and_fetch_16:
4899 BuiltinIndex = 10;
4900 break;
4901
4902 case Builtin::BI__sync_nand_and_fetch:
4903 case Builtin::BI__sync_nand_and_fetch_1:
4904 case Builtin::BI__sync_nand_and_fetch_2:
4905 case Builtin::BI__sync_nand_and_fetch_4:
4906 case Builtin::BI__sync_nand_and_fetch_8:
4907 case Builtin::BI__sync_nand_and_fetch_16:
4908 BuiltinIndex = 11;
4909 WarnAboutSemanticsChange = true;
4910 break;
4911
4912 case Builtin::BI__sync_val_compare_and_swap:
4913 case Builtin::BI__sync_val_compare_and_swap_1:
4914 case Builtin::BI__sync_val_compare_and_swap_2:
4915 case Builtin::BI__sync_val_compare_and_swap_4:
4916 case Builtin::BI__sync_val_compare_and_swap_8:
4917 case Builtin::BI__sync_val_compare_and_swap_16:
4918 BuiltinIndex = 12;
4919 NumFixed = 2;
4920 break;
4921
4922 case Builtin::BI__sync_bool_compare_and_swap:
4923 case Builtin::BI__sync_bool_compare_and_swap_1:
4924 case Builtin::BI__sync_bool_compare_and_swap_2:
4925 case Builtin::BI__sync_bool_compare_and_swap_4:
4926 case Builtin::BI__sync_bool_compare_and_swap_8:
4927 case Builtin::BI__sync_bool_compare_and_swap_16:
4928 BuiltinIndex = 13;
4929 NumFixed = 2;
4930 ResultType = Context.BoolTy;
4931 break;
4932
4933 case Builtin::BI__sync_lock_test_and_set:
4934 case Builtin::BI__sync_lock_test_and_set_1:
4935 case Builtin::BI__sync_lock_test_and_set_2:
4936 case Builtin::BI__sync_lock_test_and_set_4:
4937 case Builtin::BI__sync_lock_test_and_set_8:
4938 case Builtin::BI__sync_lock_test_and_set_16:
4939 BuiltinIndex = 14;
4940 break;
4941
4942 case Builtin::BI__sync_lock_release:
4943 case Builtin::BI__sync_lock_release_1:
4944 case Builtin::BI__sync_lock_release_2:
4945 case Builtin::BI__sync_lock_release_4:
4946 case Builtin::BI__sync_lock_release_8:
4947 case Builtin::BI__sync_lock_release_16:
4948 BuiltinIndex = 15;
4949 NumFixed = 0;
4950 ResultType = Context.VoidTy;
4951 break;
4952
4953 case Builtin::BI__sync_swap:
4954 case Builtin::BI__sync_swap_1:
4955 case Builtin::BI__sync_swap_2:
4956 case Builtin::BI__sync_swap_4:
4957 case Builtin::BI__sync_swap_8:
4958 case Builtin::BI__sync_swap_16:
4959 BuiltinIndex = 16;
4960 break;
4961 }
4962
4963 // Now that we know how many fixed arguments we expect, first check that we
4964 // have at least that many.
4965 if (TheCall->getNumArgs() < 1+NumFixed) {
4966 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4967 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
4968 << Callee->getSourceRange();
4969 return ExprError();
4970 }
4971
4972 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
4973 << Callee->getSourceRange();
4974
4975 if (WarnAboutSemanticsChange) {
4976 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
4977 << Callee->getSourceRange();
4978 }
4979
4980 // Get the decl for the concrete builtin from this, we can tell what the
4981 // concrete integer type we should convert to is.
4982 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
4983 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
4984 FunctionDecl *NewBuiltinDecl;
4985 if (NewBuiltinID == BuiltinID)
4986 NewBuiltinDecl = FDecl;
4987 else {
4988 // Perform builtin lookup to avoid redeclaring it.
4989 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
4990 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
4991 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
4992 assert(Res.getFoundDecl());
4993 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
4994 if (!NewBuiltinDecl)
4995 return ExprError();
4996 }
4997
4998 // The first argument --- the pointer --- has a fixed type; we
4999 // deduce the types of the rest of the arguments accordingly. Walk
5000 // the remaining arguments, converting them to the deduced value type.
5001 for (unsigned i = 0; i != NumFixed; ++i) {
5002 ExprResult Arg = TheCall->getArg(i+1);
5003
5004 // GCC does an implicit conversion to the pointer or integer ValType. This
5005 // can fail in some cases (1i -> int**), check for this error case now.
5006 // Initialize the argument.
5008 ValType, /*consume*/ false);
5009 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5010 if (Arg.isInvalid())
5011 return ExprError();
5012
5013 // Okay, we have something that *can* be converted to the right type. Check
5014 // to see if there is a potentially weird extension going on here. This can
5015 // happen when you do an atomic operation on something like an char* and
5016 // pass in 42. The 42 gets converted to char. This is even more strange
5017 // for things like 45.123 -> char, etc.
5018 // FIXME: Do this check.
5019 TheCall->setArg(i+1, Arg.get());
5020 }
5021
5022 // Create a new DeclRefExpr to refer to the new decl.
5024 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5025 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5026 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5027
5028 // Set the callee in the CallExpr.
5029 // FIXME: This loses syntactic information.
5030 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5031 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5032 CK_BuiltinFnToFnPtr);
5033 TheCall->setCallee(PromotedCall.get());
5034
5035 // Change the result type of the call to match the original value type. This
5036 // is arbitrary, but the codegen for these builtins ins design to handle it
5037 // gracefully.
5038 TheCall->setType(ResultType);
5039
5040 // Prohibit problematic uses of bit-precise integer types with atomic
5041 // builtins. The arguments would have already been converted to the first
5042 // argument's type, so only need to check the first argument.
5043 const auto *BitIntValType = ValType->getAs<BitIntType>();
5044 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
5045 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5046 return ExprError();
5047 }
5048
5049 return TheCallResult;
5050}
5051
5052ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5053 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5054 DeclRefExpr *DRE =
5055 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5056 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5057 unsigned BuiltinID = FDecl->getBuiltinID();
5058 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5059 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5060 "Unexpected nontemporal load/store builtin!");
5061 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5062 unsigned numArgs = isStore ? 2 : 1;
5063
5064 // Ensure that we have the proper number of arguments.
5065 if (checkArgCount(TheCall, numArgs))
5066 return ExprError();
5067
5068 // Inspect the last argument of the nontemporal builtin. This should always
5069 // be a pointer type, from which we imply the type of the memory access.
5070 // Because it is a pointer type, we don't have to worry about any implicit
5071 // casts here.
5072 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5073 ExprResult PointerArgResult =
5075
5076 if (PointerArgResult.isInvalid())
5077 return ExprError();
5078 PointerArg = PointerArgResult.get();
5079 TheCall->setArg(numArgs - 1, PointerArg);
5080
5081 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5082 if (!pointerType) {
5083 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5084 << PointerArg->getType() << PointerArg->getSourceRange();
5085 return ExprError();
5086 }
5087
5088 QualType ValType = pointerType->getPointeeType();
5089
5090 // Strip any qualifiers off ValType.
5091 ValType = ValType.getUnqualifiedType();
5092 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5093 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5094 !ValType->isVectorType()) {
5095 Diag(DRE->getBeginLoc(),
5096 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5097 << PointerArg->getType() << PointerArg->getSourceRange();
5098 return ExprError();
5099 }
5100
5101 if (!isStore) {
5102 TheCall->setType(ValType);
5103 return TheCallResult;
5104 }
5105
5106 ExprResult ValArg = TheCall->getArg(0);
5108 Context, ValType, /*consume*/ false);
5109 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5110 if (ValArg.isInvalid())
5111 return ExprError();
5112
5113 TheCall->setArg(0, ValArg.get());
5114 TheCall->setType(Context.VoidTy);
5115 return TheCallResult;
5116}
5117
5118/// CheckObjCString - Checks that the format string argument to the os_log()
5119/// and os_trace() functions is correct, and converts it to const char *.
5120ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5121 Arg = Arg->IgnoreParenCasts();
5122 auto *Literal = dyn_cast<StringLiteral>(Arg);
5123 if (!Literal) {
5124 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5125 Literal = ObjcLiteral->getString();
5126 }
5127 }
5128
5129 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
5130 return ExprError(
5131 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5132 << Arg->getSourceRange());
5133 }
5134
5135 ExprResult Result(Literal);
5137 InitializedEntity Entity =
5140 return Result;
5141}
5142
5143/// Check that the user is calling the appropriate va_start builtin for the
5144/// target and calling convention.
5145static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5146 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5147 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5148 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5149 TT.getArch() == llvm::Triple::aarch64_32);
5150 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
5151 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5152 if (IsX64 || IsAArch64) {
5153 CallingConv CC = CC_C;
5154 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5155 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5156 if (IsMSVAStart) {
5157 // Don't allow this in System V ABI functions.
5158 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
5159 return S.Diag(Fn->getBeginLoc(),
5160 diag::err_ms_va_start_used_in_sysv_function);
5161 } else {
5162 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5163 // On x64 Windows, don't allow this in System V ABI functions.
5164 // (Yes, that means there's no corresponding way to support variadic
5165 // System V ABI functions on Windows.)
5166 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
5167 (!IsWindowsOrUEFI && CC == CC_Win64))
5168 return S.Diag(Fn->getBeginLoc(),
5169 diag::err_va_start_used_in_wrong_abi_function)
5170 << !IsWindowsOrUEFI;
5171 }
5172 return false;
5173 }
5174
5175 if (IsMSVAStart)
5176 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5177 return false;
5178}
5179
5181 ParmVarDecl **LastParam = nullptr) {
5182 // Determine whether the current function, block, or obj-c method is variadic
5183 // and get its parameter list.
5184 bool IsVariadic = false;
5186 DeclContext *Caller = S.CurContext;
5187 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5188 IsVariadic = Block->isVariadic();
5189 Params = Block->parameters();
5190 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5191 IsVariadic = FD->isVariadic();
5192 Params = FD->parameters();
5193 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5194 IsVariadic = MD->isVariadic();
5195 // FIXME: This isn't correct for methods (results in bogus warning).
5196 Params = MD->parameters();
5197 } else if (isa<CapturedDecl>(Caller)) {
5198 // We don't support va_start in a CapturedDecl.
5199 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5200 return true;
5201 } else {
5202 // This must be some other declcontext that parses exprs.
5203 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5204 return true;
5205 }
5206
5207 if (!IsVariadic) {
5208 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5209 return true;
5210 }
5211
5212 if (LastParam)
5213 *LastParam = Params.empty() ? nullptr : Params.back();
5214
5215 return false;
5216}
5217
5218bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5219 Expr *Fn = TheCall->getCallee();
5220 if (checkVAStartABI(*this, BuiltinID, Fn))
5221 return true;
5222
5223 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
5224 // This builtin requires one argument (the va_list), allows two arguments,
5225 // but diagnoses more than two arguments. e.g.,
5226 // __builtin_c23_va_start(); // error
5227 // __builtin_c23_va_start(list); // ok
5228 // __builtin_c23_va_start(list, param); // ok
5229 // __builtin_c23_va_start(list, anything, anything); // error
5230 // This differs from the GCC behavior in that they accept the last case
5231 // with a warning, but it doesn't seem like a useful behavior to allow.
5232 if (checkArgCountRange(TheCall, 1, 2))
5233 return true;
5234 } else {
5235 // In C23 mode, va_start only needs one argument. However, the builtin still
5236 // requires two arguments (which matches the behavior of the GCC builtin),
5237 // <stdarg.h> passes `0` as the second argument in C23 mode.
5238 if (checkArgCount(TheCall, 2))
5239 return true;
5240 }
5241
5242 // Type-check the first argument normally.
5243 if (checkBuiltinArgument(*this, TheCall, 0))
5244 return true;
5245
5246 // Check that the current function is variadic, and get its last parameter.
5247 ParmVarDecl *LastParam;
5248 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5249 return true;
5250
5251 // Verify that the second argument to the builtin is the last non-variadic
5252 // argument of the current function or method. In C23 mode, if the call is
5253 // not to __builtin_c23_va_start, and the second argument is an integer
5254 // constant expression with value 0, then we don't bother with this check.
5255 // For __builtin_c23_va_start, we only perform the check for the second
5256 // argument being the last argument to the current function if there is a
5257 // second argument present.
5258 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
5259 TheCall->getNumArgs() < 2) {
5260 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5261 return false;
5262 }
5263
5264 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5265 if (std::optional<llvm::APSInt> Val =
5267 Val && LangOpts.C23 && *Val == 0 &&
5268 BuiltinID != Builtin::BI__builtin_c23_va_start) {
5269 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5270 return false;
5271 }
5272
5273 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
5274 // next block.
5275 QualType Type;
5276 SourceLocation ParamLoc;
5277 bool IsCRegister = false;
5278 bool SecondArgIsLastNonVariadicArgument = false;
5279 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5280 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5281 SecondArgIsLastNonVariadicArgument = PV == LastParam;
5282
5283 Type = PV->getType();
5284 ParamLoc = PV->getLocation();
5285 IsCRegister =
5286 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5287 }
5288 }
5289
5290 if (!SecondArgIsLastNonVariadicArgument)
5291 Diag(TheCall->getArg(1)->getBeginLoc(),
5292 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
5293 else if (IsCRegister || Type->isReferenceType() ||
5294 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5295 // Promotable integers are UB, but enumerations need a bit of
5296 // extra checking to see what their promotable type actually is.
5297 if (!Context.isPromotableIntegerType(Type))
5298 return false;
5299 const auto *ED = Type->getAsEnumDecl();
5300 if (!ED)
5301 return true;
5302 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
5303 }()) {
5304 unsigned Reason = 0;
5305 if (Type->isReferenceType()) Reason = 1;
5306 else if (IsCRegister) Reason = 2;
5307 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5308 Diag(ParamLoc, diag::note_parameter_type) << Type;
5309 }
5310
5311 return false;
5312}
5313
5314bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
5315 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
5316 const LangOptions &LO = getLangOpts();
5317
5318 if (LO.CPlusPlus)
5319 return Arg->getType()
5321 .getTypePtr()
5322 ->getPointeeType()
5324
5325 // In C, allow aliasing through `char *`, this is required for AArch64 at
5326 // least.
5327 return true;
5328 };
5329
5330 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5331 // const char *named_addr);
5332
5333 Expr *Func = Call->getCallee();
5334
5335 if (Call->getNumArgs() < 3)
5336 return Diag(Call->getEndLoc(),
5337 diag::err_typecheck_call_too_few_args_at_least)
5338 << 0 /*function call*/ << 3 << Call->getNumArgs()
5339 << /*is non object*/ 0;
5340
5341 // Type-check the first argument normally.
5342 if (checkBuiltinArgument(*this, Call, 0))
5343 return true;
5344
5345 // Check that the current function is variadic.
5347 return true;
5348
5349 // __va_start on Windows does not validate the parameter qualifiers
5350
5351 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5352 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5353
5354 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5355 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5356
5357 const QualType &ConstCharPtrTy =
5359 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
5360 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5361 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5362 << 0 /* qualifier difference */
5363 << 3 /* parameter mismatch */
5364 << 2 << Arg1->getType() << ConstCharPtrTy;
5365
5366 const QualType SizeTy = Context.getSizeType();
5367 if (!Context.hasSameType(
5369 SizeTy))
5370 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5371 << Arg2->getType() << SizeTy << 1 /* different class */
5372 << 0 /* qualifier difference */
5373 << 3 /* parameter mismatch */
5374 << 3 << Arg2->getType() << SizeTy;
5375
5376 return false;
5377}
5378
5379bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
5380 if (checkArgCount(TheCall, 2))
5381 return true;
5382
5383 if (BuiltinID == Builtin::BI__builtin_isunordered &&
5384 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
5385 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5386 << 1 << 0 << TheCall->getSourceRange();
5387
5388 ExprResult OrigArg0 = TheCall->getArg(0);
5389 ExprResult OrigArg1 = TheCall->getArg(1);
5390
5391 // Do standard promotions between the two arguments, returning their common
5392 // type.
5394 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
5395 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5396 return true;
5397
5398 // Make sure any conversions are pushed back into the call; this is
5399 // type safe since unordered compare builtins are declared as "_Bool
5400 // foo(...)".
5401 TheCall->setArg(0, OrigArg0.get());
5402 TheCall->setArg(1, OrigArg1.get());
5403
5404 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5405 return false;
5406
5407 // If the common type isn't a real floating type, then the arguments were
5408 // invalid for this operation.
5409 if (Res.isNull() || !Res->isRealFloatingType())
5410 return Diag(OrigArg0.get()->getBeginLoc(),
5411 diag::err_typecheck_call_invalid_ordered_compare)
5412 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5413 << SourceRange(OrigArg0.get()->getBeginLoc(),
5414 OrigArg1.get()->getEndLoc());
5415
5416 return false;
5417}
5418
5419bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
5420 unsigned BuiltinID) {
5421 if (checkArgCount(TheCall, NumArgs))
5422 return true;
5423
5425 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
5426 BuiltinID == Builtin::BI__builtin_isinf ||
5427 BuiltinID == Builtin::BI__builtin_isinf_sign))
5428 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5429 << 0 << 0 << TheCall->getSourceRange();
5430
5431 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
5432 BuiltinID == Builtin::BI__builtin_isunordered))
5433 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5434 << 1 << 0 << TheCall->getSourceRange();
5435
5436 bool IsFPClass = NumArgs == 2;
5437
5438 // Find out position of floating-point argument.
5439 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
5440
5441 // We can count on all parameters preceding the floating-point just being int.
5442 // Try all of those.
5443 for (unsigned i = 0; i < FPArgNo; ++i) {
5444 Expr *Arg = TheCall->getArg(i);
5445
5446 if (Arg->isTypeDependent())
5447 return false;
5448
5451
5452 if (Res.isInvalid())
5453 return true;
5454 TheCall->setArg(i, Res.get());
5455 }
5456
5457 Expr *OrigArg = TheCall->getArg(FPArgNo);
5458
5459 if (OrigArg->isTypeDependent())
5460 return false;
5461
5462 // Usual Unary Conversions will convert half to float, which we want for
5463 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5464 // type how it is, but do normal L->Rvalue conversions.
5466 ExprResult Res = UsualUnaryConversions(OrigArg);
5467
5468 if (!Res.isUsable())
5469 return true;
5470 OrigArg = Res.get();
5471 } else {
5473
5474 if (!Res.isUsable())
5475 return true;
5476 OrigArg = Res.get();
5477 }
5478 TheCall->setArg(FPArgNo, OrigArg);
5479
5480 QualType VectorResultTy;
5481 QualType ElementTy = OrigArg->getType();
5482 // TODO: When all classification function are implemented with is_fpclass,
5483 // vector argument can be supported in all of them.
5484 if (ElementTy->isVectorType() && IsFPClass) {
5485 VectorResultTy = GetSignedVectorType(ElementTy);
5486 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
5487 }
5488
5489 // This operation requires a non-_Complex floating-point number.
5490 if (!ElementTy->isRealFloatingType())
5491 return Diag(OrigArg->getBeginLoc(),
5492 diag::err_typecheck_call_invalid_unary_fp)
5493 << OrigArg->getType() << OrigArg->getSourceRange();
5494
5495 // __builtin_isfpclass has integer parameter that specify test mask. It is
5496 // passed in (...), so it should be analyzed completely here.
5497 if (IsFPClass)
5498 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
5499 return true;
5500
5501 // TODO: enable this code to all classification functions.
5502 if (IsFPClass) {
5503 QualType ResultTy;
5504 if (!VectorResultTy.isNull())
5505 ResultTy = VectorResultTy;
5506 else
5507 ResultTy = Context.IntTy;
5508 TheCall->setType(ResultTy);
5509 }
5510
5511 return false;
5512}
5513
5514bool Sema::BuiltinComplex(CallExpr *TheCall) {
5515 if (checkArgCount(TheCall, 2))
5516 return true;
5517
5518 bool Dependent = false;
5519 for (unsigned I = 0; I != 2; ++I) {
5520 Expr *Arg = TheCall->getArg(I);
5521 QualType T = Arg->getType();
5522 if (T->isDependentType()) {
5523 Dependent = true;
5524 continue;
5525 }
5526
5527 // Despite supporting _Complex int, GCC requires a real floating point type
5528 // for the operands of __builtin_complex.
5529 if (!T->isRealFloatingType()) {
5530 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
5531 << Arg->getType() << Arg->getSourceRange();
5532 }
5533
5534 ExprResult Converted = DefaultLvalueConversion(Arg);
5535 if (Converted.isInvalid())
5536 return true;
5537 TheCall->setArg(I, Converted.get());
5538 }
5539
5540 if (Dependent) {
5541 TheCall->setType(Context.DependentTy);
5542 return false;
5543 }
5544
5545 Expr *Real = TheCall->getArg(0);
5546 Expr *Imag = TheCall->getArg(1);
5547 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
5548 return Diag(Real->getBeginLoc(),
5549 diag::err_typecheck_call_different_arg_types)
5550 << Real->getType() << Imag->getType()
5551 << Real->getSourceRange() << Imag->getSourceRange();
5552 }
5553
5554 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
5555 // don't allow this builtin to form those types either.
5556 // FIXME: Should we allow these types?
5557 if (Real->getType()->isFloat16Type())
5558 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
5559 << "_Float16";
5560 if (Real->getType()->isHalfType())
5561 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
5562 << "half";
5563
5564 TheCall->setType(Context.getComplexType(Real->getType()));
5565 return false;
5566}
5567
5568/// BuiltinShuffleVector - Handle __builtin_shufflevector.
5569// This is declared to take (...), so we have to check everything.
5571 if (TheCall->getNumArgs() < 2)
5572 return ExprError(Diag(TheCall->getEndLoc(),
5573 diag::err_typecheck_call_too_few_args_at_least)
5574 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5575 << /*is non object*/ 0 << TheCall->getSourceRange());
5576
5577 // Determine which of the following types of shufflevector we're checking:
5578 // 1) unary, vector mask: (lhs, mask)
5579 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5580 QualType resType = TheCall->getArg(0)->getType();
5581 unsigned numElements = 0;
5582
5583 if (!TheCall->getArg(0)->isTypeDependent() &&
5584 !TheCall->getArg(1)->isTypeDependent()) {
5585 QualType LHSType = TheCall->getArg(0)->getType();
5586 QualType RHSType = TheCall->getArg(1)->getType();
5587
5588 if (!LHSType->isVectorType() || !RHSType->isVectorType())
5589 return ExprError(
5590 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5591 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ false
5592 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5593 TheCall->getArg(1)->getEndLoc()));
5594
5595 numElements = LHSType->castAs<VectorType>()->getNumElements();
5596 unsigned numResElements = TheCall->getNumArgs() - 2;
5597
5598 // Check to see if we have a call with 2 vector arguments, the unary shuffle
5599 // with mask. If so, verify that RHS is an integer vector type with the
5600 // same number of elts as lhs.
5601 if (TheCall->getNumArgs() == 2) {
5602 if (!RHSType->hasIntegerRepresentation() ||
5603 RHSType->castAs<VectorType>()->getNumElements() != numElements)
5604 return ExprError(Diag(TheCall->getBeginLoc(),
5605 diag::err_vec_builtin_incompatible_vector)
5606 << TheCall->getDirectCallee()
5607 << /*isMorethantwoArgs*/ false
5608 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5609 TheCall->getArg(1)->getEndLoc()));
5610 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5611 return ExprError(Diag(TheCall->getBeginLoc(),
5612 diag::err_vec_builtin_incompatible_vector)
5613 << TheCall->getDirectCallee()
5614 << /*isMorethantwoArgs*/ false
5615 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5616 TheCall->getArg(1)->getEndLoc()));
5617 } else if (numElements != numResElements) {
5618 QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5619 resType = resType->isExtVectorType()
5620 ? Context.getExtVectorType(eltType, numResElements)
5621 : Context.getVectorType(eltType, numResElements,
5623 }
5624 }
5625
5626 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5627 Expr *Arg = TheCall->getArg(i);
5628 if (Arg->isTypeDependent() || Arg->isValueDependent())
5629 continue;
5630
5631 std::optional<llvm::APSInt> Result;
5632 if (!(Result = Arg->getIntegerConstantExpr(Context)))
5633 return ExprError(Diag(TheCall->getBeginLoc(),
5634 diag::err_shufflevector_nonconstant_argument)
5635 << Arg->getSourceRange());
5636
5637 // Allow -1 which will be translated to undef in the IR.
5638 if (Result->isSigned() && Result->isAllOnes())
5639 ;
5640 else if (Result->getActiveBits() > 64 ||
5641 Result->getZExtValue() >= numElements * 2)
5642 return ExprError(Diag(TheCall->getBeginLoc(),
5643 diag::err_shufflevector_argument_too_large)
5644 << Arg->getSourceRange());
5645
5646 TheCall->setArg(i, ConstantExpr::Create(Context, Arg, APValue(*Result)));
5647 }
5648
5649 SmallVector<Expr *> exprs;
5650 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5651 exprs.push_back(TheCall->getArg(i));
5652 TheCall->setArg(i, nullptr);
5653 }
5654
5655 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5656 TheCall->getCallee()->getBeginLoc(),
5657 TheCall->getRParenLoc());
5658}
5659
5661 SourceLocation BuiltinLoc,
5662 SourceLocation RParenLoc) {
5665 QualType DstTy = TInfo->getType();
5666 QualType SrcTy = E->getType();
5667
5668 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5669 return ExprError(Diag(BuiltinLoc,
5670 diag::err_convertvector_non_vector)
5671 << E->getSourceRange());
5672 if (!DstTy->isVectorType() && !DstTy->isDependentType())
5673 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
5674 << "second"
5675 << "__builtin_convertvector");
5676
5677 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5678 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5679 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5680 if (SrcElts != DstElts)
5681 return ExprError(Diag(BuiltinLoc,
5682 diag::err_convertvector_incompatible_vector)
5683 << E->getSourceRange());
5684 }
5685
5686 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
5687 RParenLoc, CurFPFeatureOverrides());
5688}
5689
5690bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
5691 unsigned NumArgs = TheCall->getNumArgs();
5692
5693 if (NumArgs > 3)
5694 return Diag(TheCall->getEndLoc(),
5695 diag::err_typecheck_call_too_many_args_at_most)
5696 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
5697 << TheCall->getSourceRange();
5698
5699 // Argument 0 is checked for us and the remaining arguments must be
5700 // constant integers.
5701 for (unsigned i = 1; i != NumArgs; ++i)
5702 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5703 return true;
5704
5705 return false;
5706}
5707
5708bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
5710 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
5711 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5712 if (checkArgCount(TheCall, 1))
5713 return true;
5714 Expr *Arg = TheCall->getArg(0);
5715 if (Arg->isInstantiationDependent())
5716 return false;
5717
5718 QualType ArgTy = Arg->getType();
5719 if (!ArgTy->hasFloatingRepresentation())
5720 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
5721 << ArgTy;
5722 if (Arg->isLValue()) {
5723 ExprResult FirstArg = DefaultLvalueConversion(Arg);
5724 TheCall->setArg(0, FirstArg.get());
5725 }
5726 TheCall->setType(TheCall->getArg(0)->getType());
5727 return false;
5728}
5729
5730bool Sema::BuiltinAssume(CallExpr *TheCall) {
5731 Expr *Arg = TheCall->getArg(0);
5732 if (Arg->isInstantiationDependent()) return false;
5733
5734 if (Arg->HasSideEffects(Context))
5735 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5736 << Arg->getSourceRange()
5737 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5738
5739 return false;
5740}
5741
5742bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
5743 // The alignment must be a constant integer.
5744 Expr *Arg = TheCall->getArg(1);
5745
5746 // We can't check the value of a dependent argument.
5747 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5748 if (const auto *UE =
5749 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5750 if (UE->getKind() == UETT_AlignOf ||
5751 UE->getKind() == UETT_PreferredAlignOf)
5752 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5753 << Arg->getSourceRange();
5754
5755 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5756
5757 if (!Result.isPowerOf2())
5758 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5759 << Arg->getSourceRange();
5760
5761 if (Result < Context.getCharWidth())
5762 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5764
5765 if (Result > std::numeric_limits<int32_t>::max())
5766 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5767 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5768 }
5769
5770 return false;
5771}
5772
5773bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
5774 if (checkArgCountRange(TheCall, 2, 3))
5775 return true;
5776
5777 unsigned NumArgs = TheCall->getNumArgs();
5778 Expr *FirstArg = TheCall->getArg(0);
5779
5780 {
5781 ExprResult FirstArgResult =
5783 if (!FirstArgResult.get()->getType()->isPointerType()) {
5784 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
5785 << TheCall->getSourceRange();
5786 return true;
5787 }
5788 TheCall->setArg(0, FirstArgResult.get());
5789 }
5790
5791 // The alignment must be a constant integer.
5792 Expr *SecondArg = TheCall->getArg(1);
5793
5794 // We can't check the value of a dependent argument.
5795 if (!SecondArg->isValueDependent()) {
5796 llvm::APSInt Result;
5797 if (BuiltinConstantArg(TheCall, 1, Result))
5798 return true;
5799
5800 if (!Result.isPowerOf2())
5801 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5802 << SecondArg->getSourceRange();
5803
5805 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
5806 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
5807 }
5808
5809 if (NumArgs > 2) {
5810 Expr *ThirdArg = TheCall->getArg(2);
5811 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
5812 return true;
5813 TheCall->setArg(2, ThirdArg);
5814 }
5815
5816 return false;
5817}
5818
5819bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
5820 unsigned BuiltinID =
5821 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5822 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5823
5824 unsigned NumArgs = TheCall->getNumArgs();
5825 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5826 if (NumArgs < NumRequiredArgs) {
5827 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5828 << 0 /* function call */ << NumRequiredArgs << NumArgs
5829 << /*is non object*/ 0 << TheCall->getSourceRange();
5830 }
5831 if (NumArgs >= NumRequiredArgs + 0x100) {
5832 return Diag(TheCall->getEndLoc(),
5833 diag::err_typecheck_call_too_many_args_at_most)
5834 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5835 << /*is non object*/ 0 << TheCall->getSourceRange();
5836 }
5837 unsigned i = 0;
5838
5839 // For formatting call, check buffer arg.
5840 if (!IsSizeCall) {
5841 ExprResult Arg(TheCall->getArg(i));
5843 Context, Context.VoidPtrTy, false);
5844 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5845 if (Arg.isInvalid())
5846 return true;
5847 TheCall->setArg(i, Arg.get());
5848 i++;
5849 }
5850
5851 // Check string literal arg.
5852 unsigned FormatIdx = i;
5853 {
5854 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5855 if (Arg.isInvalid())
5856 return true;
5857 TheCall->setArg(i, Arg.get());
5858 i++;
5859 }
5860
5861 // Make sure variadic args are scalar.
5862 unsigned FirstDataArg = i;
5863 while (i < NumArgs) {
5865 TheCall->getArg(i), VariadicCallType::Function, nullptr);
5866 if (Arg.isInvalid())
5867 return true;
5868 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5869 if (ArgSize.getQuantity() >= 0x100) {
5870 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
5871 << i << (int)ArgSize.getQuantity() << 0xff
5872 << TheCall->getSourceRange();
5873 }
5874 TheCall->setArg(i, Arg.get());
5875 i++;
5876 }
5877
5878 // Check formatting specifiers. NOTE: We're only doing this for the non-size
5879 // call to avoid duplicate diagnostics.
5880 if (!IsSizeCall) {
5881 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5882 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5883 bool Success = CheckFormatArguments(
5884 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
5886 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
5887 if (!Success)
5888 return true;
5889 }
5890
5891 if (IsSizeCall) {
5892 TheCall->setType(Context.getSizeType());
5893 } else {
5894 TheCall->setType(Context.VoidPtrTy);
5895 }
5896 return false;
5897}
5898
5899bool Sema::BuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5900 llvm::APSInt &Result) {
5901 Expr *Arg = TheCall->getArg(ArgNum);
5902 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5903 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5904
5905 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
5906
5907 std::optional<llvm::APSInt> R;
5908 if (!(R = Arg->getIntegerConstantExpr(Context)))
5909 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
5910 << FDecl->getDeclName() << Arg->getSourceRange();
5911 Result = *R;
5912 return false;
5913}
5914
5915bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
5916 int High, bool RangeIsError) {
5918 return false;
5919 llvm::APSInt Result;
5920
5921 // We can't check the value of a dependent argument.
5922 Expr *Arg = TheCall->getArg(ArgNum);
5923 if (Arg->isTypeDependent() || Arg->isValueDependent())
5924 return false;
5925
5926 // Check constant-ness first.
5927 if (BuiltinConstantArg(TheCall, ArgNum, Result))
5928 return true;
5929
5930 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
5931 if (RangeIsError)
5932 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
5933 << toString(Result, 10) << Low << High << Arg->getSourceRange();
5934 else
5935 // Defer the warning until we know if the code will be emitted so that
5936 // dead code can ignore this.
5937 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
5938 PDiag(diag::warn_argument_invalid_range)
5939 << toString(Result, 10) << Low << High
5940 << Arg->getSourceRange());
5941 }
5942
5943 return false;
5944}
5945
5947 unsigned Num) {
5948 llvm::APSInt Result;
5949
5950 // We can't check the value of a dependent argument.
5951 Expr *Arg = TheCall->getArg(ArgNum);
5952 if (Arg->isTypeDependent() || Arg->isValueDependent())
5953 return false;
5954
5955 // Check constant-ness first.
5956 if (BuiltinConstantArg(TheCall, ArgNum, Result))
5957 return true;
5958
5959 if (Result.getSExtValue() % Num != 0)
5960 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
5961 << Num << Arg->getSourceRange();
5962
5963 return false;
5964}
5965
5966bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
5967 llvm::APSInt Result;
5968
5969 // We can't check the value of a dependent argument.
5970 Expr *Arg = TheCall->getArg(ArgNum);
5971 if (Arg->isTypeDependent() || Arg->isValueDependent())
5972 return false;
5973
5974 // Check constant-ness first.
5975 if (BuiltinConstantArg(TheCall, ArgNum, Result))
5976 return true;
5977
5978 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
5979 // and only if x is a power of 2.
5980 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
5981 return false;
5982
5983 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
5984 << Arg->getSourceRange();
5985}
5986
5987static bool IsShiftedByte(llvm::APSInt Value) {
5988 if (Value.isNegative())
5989 return false;
5990
5991 // Check if it's a shifted byte, by shifting it down
5992 while (true) {
5993 // If the value fits in the bottom byte, the check passes.
5994 if (Value < 0x100)
5995 return true;
5996
5997 // Otherwise, if the value has _any_ bits in the bottom byte, the check
5998 // fails.
5999 if ((Value & 0xFF) != 0)
6000 return false;
6001
6002 // If the bottom 8 bits are all 0, but something above that is nonzero,
6003 // then shifting the value right by 8 bits won't affect whether it's a
6004 // shifted byte or not. So do that, and go round again.
6005 Value >>= 8;
6006 }
6007}
6008
6010 unsigned ArgBits) {
6011 llvm::APSInt Result;
6012
6013 // We can't check the value of a dependent argument.
6014 Expr *Arg = TheCall->getArg(ArgNum);
6015 if (Arg->isTypeDependent() || Arg->isValueDependent())
6016 return false;
6017
6018 // Check constant-ness first.
6019 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6020 return true;
6021
6022 // Truncate to the given size.
6023 Result = Result.getLoBits(ArgBits);
6024 Result.setIsUnsigned(true);
6025
6026 if (IsShiftedByte(Result))
6027 return false;
6028
6029 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6030 << Arg->getSourceRange();
6031}
6032
6034 unsigned ArgBits) {
6035 llvm::APSInt Result;
6036
6037 // We can't check the value of a dependent argument.
6038 Expr *Arg = TheCall->getArg(ArgNum);
6039 if (Arg->isTypeDependent() || Arg->isValueDependent())
6040 return false;
6041
6042 // Check constant-ness first.
6043 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6044 return true;
6045
6046 // Truncate to the given size.
6047 Result = Result.getLoBits(ArgBits);
6048 Result.setIsUnsigned(true);
6049
6050 // Check to see if it's in either of the required forms.
6051 if (IsShiftedByte(Result) ||
6052 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6053 return false;
6054
6055 return Diag(TheCall->getBeginLoc(),
6056 diag::err_argument_not_shifted_byte_or_xxff)
6057 << Arg->getSourceRange();
6058}
6059
6060bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6062 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6063 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6064
6065 Expr *Arg = TheCall->getArg(1);
6066 llvm::APSInt Result;
6067
6068 // TODO: This is less than ideal. Overload this to take a value.
6069 if (BuiltinConstantArg(TheCall, 1, Result))
6070 return true;
6071
6072 if (Result != 1)
6073 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6074 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6075
6076 return false;
6077}
6078
6079bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6081 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6082 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6083 return false;
6084}
6085
6086bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
6087 if (checkArgCount(TheCall, 1))
6088 return true;
6089
6090 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
6091 if (ArgRes.isInvalid())
6092 return true;
6093
6094 // For simplicity, we support only limited expressions for the argument.
6095 // Specifically a pointer to a flexible array member:'ptr->array'. This
6096 // allows us to reject arguments with complex casting, which really shouldn't
6097 // be a huge problem.
6098 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
6099 if (!isa<PointerType>(Arg->getType()) && !Arg->getType()->isArrayType())
6100 return Diag(Arg->getBeginLoc(),
6101 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
6102 << Arg->getSourceRange();
6103
6104 if (Arg->HasSideEffects(Context))
6105 return Diag(Arg->getBeginLoc(),
6106 diag::err_builtin_counted_by_ref_has_side_effects)
6107 << Arg->getSourceRange();
6108
6109 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
6110 if (!ME->isFlexibleArrayMemberLike(
6111 Context, getLangOpts().getStrictFlexArraysLevel()))
6112 return Diag(Arg->getBeginLoc(),
6113 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
6114 << Arg->getSourceRange();
6115
6116 if (auto *CATy =
6117 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
6118 CATy && CATy->getKind() == CountAttributedType::CountedBy) {
6119 const auto *FAMDecl = cast<FieldDecl>(ME->getMemberDecl());
6120 if (const FieldDecl *CountFD = FAMDecl->findCountedByField()) {
6121 TheCall->setType(Context.getPointerType(CountFD->getType()));
6122 return false;
6123 }
6124 }
6125 } else {
6126 return Diag(Arg->getBeginLoc(),
6127 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
6128 << Arg->getSourceRange();
6129 }
6130
6132 return false;
6133}
6134
6135/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
6136/// It allows leaking and modification of bounds safety information.
6137bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
6139 const CallExpr *CE =
6140 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
6141 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
6142 return false;
6143
6144 switch (K) {
6147 Diag(E->getExprLoc(),
6148 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6149 << 0 << E->getSourceRange();
6150 break;
6152 Diag(E->getExprLoc(),
6153 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6154 << 1 << E->getSourceRange();
6155 break;
6157 Diag(E->getExprLoc(),
6158 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6159 << 2 << E->getSourceRange();
6160 break;
6162 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6163 << 0 << E->getSourceRange();
6164 break;
6166 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6167 << 1 << E->getSourceRange();
6168 break;
6169 }
6170
6171 return true;
6172}
6173
6174namespace {
6175
6176class UncoveredArgHandler {
6177 enum { Unknown = -1, AllCovered = -2 };
6178
6179 signed FirstUncoveredArg = Unknown;
6180 SmallVector<const Expr *, 4> DiagnosticExprs;
6181
6182public:
6183 UncoveredArgHandler() = default;
6184
6185 bool hasUncoveredArg() const {
6186 return (FirstUncoveredArg >= 0);
6187 }
6188
6189 unsigned getUncoveredArg() const {
6190 assert(hasUncoveredArg() && "no uncovered argument");
6191 return FirstUncoveredArg;
6192 }
6193
6194 void setAllCovered() {
6195 // A string has been found with all arguments covered, so clear out
6196 // the diagnostics.
6197 DiagnosticExprs.clear();
6198 FirstUncoveredArg = AllCovered;
6199 }
6200
6201 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6202 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6203
6204 // Don't update if a previous string covers all arguments.
6205 if (FirstUncoveredArg == AllCovered)
6206 return;
6207
6208 // UncoveredArgHandler tracks the highest uncovered argument index
6209 // and with it all the strings that match this index.
6210 if (NewFirstUncoveredArg == FirstUncoveredArg)
6211 DiagnosticExprs.push_back(StrExpr);
6212 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6213 DiagnosticExprs.clear();
6214 DiagnosticExprs.push_back(StrExpr);
6215 FirstUncoveredArg = NewFirstUncoveredArg;
6216 }
6217 }
6218
6219 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6220};
6221
6222enum StringLiteralCheckType {
6223 SLCT_NotALiteral,
6224 SLCT_UncheckedLiteral,
6225 SLCT_CheckedLiteral
6226};
6227
6228} // namespace
6229
6230static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6231 BinaryOperatorKind BinOpKind,
6232 bool AddendIsRight) {
6233 unsigned BitWidth = Offset.getBitWidth();
6234 unsigned AddendBitWidth = Addend.getBitWidth();
6235 // There might be negative interim results.
6236 if (Addend.isUnsigned()) {
6237 Addend = Addend.zext(++AddendBitWidth);
6238 Addend.setIsSigned(true);
6239 }
6240 // Adjust the bit width of the APSInts.
6241 if (AddendBitWidth > BitWidth) {
6242 Offset = Offset.sext(AddendBitWidth);
6243 BitWidth = AddendBitWidth;
6244 } else if (BitWidth > AddendBitWidth) {
6245 Addend = Addend.sext(BitWidth);
6246 }
6247
6248 bool Ov = false;
6249 llvm::APSInt ResOffset = Offset;
6250 if (BinOpKind == BO_Add)
6251 ResOffset = Offset.sadd_ov(Addend, Ov);
6252 else {
6253 assert(AddendIsRight && BinOpKind == BO_Sub &&
6254 "operator must be add or sub with addend on the right");
6255 ResOffset = Offset.ssub_ov(Addend, Ov);
6256 }
6257
6258 // We add an offset to a pointer here so we should support an offset as big as
6259 // possible.
6260 if (Ov) {
6261 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6262 "index (intermediate) result too big");
6263 Offset = Offset.sext(2 * BitWidth);
6264 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6265 return;
6266 }
6267
6268 Offset = ResOffset;
6269}
6270
6271namespace {
6272
6273// This is a wrapper class around StringLiteral to support offsetted string
6274// literals as format strings. It takes the offset into account when returning
6275// the string and its length or the source locations to display notes correctly.
6276class FormatStringLiteral {
6277 const StringLiteral *FExpr;
6278 int64_t Offset;
6279
6280public:
6281 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6282 : FExpr(fexpr), Offset(Offset) {}
6283
6284 const StringLiteral *getFormatString() const { return FExpr; }
6285
6286 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
6287
6288 unsigned getByteLength() const {
6289 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6290 }
6291
6292 unsigned getLength() const { return FExpr->getLength() - Offset; }
6293 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6294
6295 StringLiteralKind getKind() const { return FExpr->getKind(); }
6296
6297 QualType getType() const { return FExpr->getType(); }
6298
6299 bool isAscii() const { return FExpr->isOrdinary(); }
6300 bool isWide() const { return FExpr->isWide(); }
6301 bool isUTF8() const { return FExpr->isUTF8(); }
6302 bool isUTF16() const { return FExpr->isUTF16(); }
6303 bool isUTF32() const { return FExpr->isUTF32(); }
6304 bool isPascal() const { return FExpr->isPascal(); }
6305
6306 SourceLocation getLocationOfByte(
6307 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6308 const TargetInfo &Target, unsigned *StartToken = nullptr,
6309 unsigned *StartTokenByteOffset = nullptr) const {
6310 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6311 StartToken, StartTokenByteOffset);
6312 }
6313
6314 SourceLocation getBeginLoc() const LLVM_READONLY {
6315 return FExpr->getBeginLoc().getLocWithOffset(Offset);
6316 }
6317
6318 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6319};
6320
6321} // namespace
6322
6323static void CheckFormatString(
6324 Sema &S, const FormatStringLiteral *FExpr,
6325 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
6327 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6328 bool inFunctionCall, VariadicCallType CallType,
6329 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6330 bool IgnoreStringsWithoutSpecifiers);
6331
6332static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
6333 const Expr *E);
6334
6335// Determine if an expression is a string literal or constant string.
6336// If this function returns false on the arguments to a function expecting a
6337// format string, we will usually need to emit a warning.
6338// True string literals are then checked by CheckFormatString.
6339static StringLiteralCheckType checkFormatStringExpr(
6340 Sema &S, const StringLiteral *ReferenceFormatString, const Expr *E,
6342 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6343 VariadicCallType CallType, bool InFunctionCall,
6344 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6345 llvm::APSInt Offset, bool IgnoreStringsWithoutSpecifiers = false) {
6347 return SLCT_NotALiteral;
6348tryAgain:
6349 assert(Offset.isSigned() && "invalid offset");
6350
6351 if (E->isTypeDependent() || E->isValueDependent())
6352 return SLCT_NotALiteral;
6353
6354 E = E->IgnoreParenCasts();
6355
6357 // Technically -Wformat-nonliteral does not warn about this case.
6358 // The behavior of printf and friends in this case is implementation
6359 // dependent. Ideally if the format string cannot be null then
6360 // it should have a 'nonnull' attribute in the function prototype.
6361 return SLCT_UncheckedLiteral;
6362
6363 switch (E->getStmtClass()) {
6364 case Stmt::InitListExprClass:
6365 // Handle expressions like {"foobar"}.
6366 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
6367 return checkFormatStringExpr(
6368 S, ReferenceFormatString, SLE, Args, APK, format_idx, firstDataArg,
6369 Type, CallType, /*InFunctionCall*/ false, CheckedVarArgs,
6370 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6371 }
6372 return SLCT_NotALiteral;
6373 case Stmt::BinaryConditionalOperatorClass:
6374 case Stmt::ConditionalOperatorClass: {
6375 // The expression is a literal if both sub-expressions were, and it was
6376 // completely checked only if both sub-expressions were checked.
6378 cast<AbstractConditionalOperator>(E);
6379
6380 // Determine whether it is necessary to check both sub-expressions, for
6381 // example, because the condition expression is a constant that can be
6382 // evaluated at compile time.
6383 bool CheckLeft = true, CheckRight = true;
6384
6385 bool Cond;
6386 if (C->getCond()->EvaluateAsBooleanCondition(
6387 Cond, S.getASTContext(), S.isConstantEvaluatedContext())) {
6388 if (Cond)
6389 CheckRight = false;
6390 else
6391 CheckLeft = false;
6392 }
6393
6394 // We need to maintain the offsets for the right and the left hand side
6395 // separately to check if every possible indexed expression is a valid
6396 // string literal. They might have different offsets for different string
6397 // literals in the end.
6398 StringLiteralCheckType Left;
6399 if (!CheckLeft)
6400 Left = SLCT_UncheckedLiteral;
6401 else {
6402 Left = checkFormatStringExpr(
6403 S, ReferenceFormatString, C->getTrueExpr(), Args, APK, format_idx,
6404 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6405 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6406 if (Left == SLCT_NotALiteral || !CheckRight) {
6407 return Left;
6408 }
6409 }
6410
6411 StringLiteralCheckType Right = checkFormatStringExpr(
6412 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
6413 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6414 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6415
6416 return (CheckLeft && Left < Right) ? Left : Right;
6417 }
6418
6419 case Stmt::ImplicitCastExprClass:
6420 E = cast<ImplicitCastExpr>(E)->getSubExpr();
6421 goto tryAgain;
6422
6423 case Stmt::OpaqueValueExprClass:
6424 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6425 E = src;
6426 goto tryAgain;
6427 }
6428 return SLCT_NotALiteral;
6429
6430 case Stmt::PredefinedExprClass:
6431 // While __func__, etc., are technically not string literals, they
6432 // cannot contain format specifiers and thus are not a security
6433 // liability.
6434 return SLCT_UncheckedLiteral;
6435
6436 case Stmt::DeclRefExprClass: {
6437 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6438
6439 // As an exception, do not flag errors for variables binding to
6440 // const string literals.
6441 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6442 bool isConstant = false;
6443 QualType T = DR->getType();
6444
6445 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6446 isConstant = AT->getElementType().isConstant(S.Context);
6447 } else if (const PointerType *PT = T->getAs<PointerType>()) {
6448 isConstant = T.isConstant(S.Context) &&
6450 } else if (T->isObjCObjectPointerType()) {
6451 // In ObjC, there is usually no "const ObjectPointer" type,
6452 // so don't check if the pointee type is constant.
6453 isConstant = T.isConstant(S.Context);
6454 }
6455
6456 if (isConstant) {
6457 if (const Expr *Init = VD->getAnyInitializer()) {
6458 // Look through initializers like const char c[] = { "foo" }
6459 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6460 if (InitList->isStringLiteralInit())
6461 Init = InitList->getInit(0)->IgnoreParenImpCasts();
6462 }
6463 return checkFormatStringExpr(
6464 S, ReferenceFormatString, Init, Args, APK, format_idx,
6465 firstDataArg, Type, CallType,
6466 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg, Offset);
6467 }
6468 }
6469
6470 // When the format argument is an argument of this function, and this
6471 // function also has the format attribute, there are several interactions
6472 // for which there shouldn't be a warning. For instance, when calling
6473 // v*printf from a function that has the printf format attribute, we
6474 // should not emit a warning about using `fmt`, even though it's not
6475 // constant, because the arguments have already been checked for the
6476 // caller of `logmessage`:
6477 //
6478 // __attribute__((format(printf, 1, 2)))
6479 // void logmessage(char const *fmt, ...) {
6480 // va_list ap;
6481 // va_start(ap, fmt);
6482 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
6483 // ...
6484 // }
6485 //
6486 // Another interaction that we need to support is using a format string
6487 // specified by the format_matches attribute:
6488 //
6489 // __attribute__((format_matches(printf, 1, "%s %d")))
6490 // void logmessage(char const *fmt, const char *a, int b) {
6491 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
6492 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
6493 // ...
6494 // }
6495 //
6496 // Yet another interaction that we need to support is calling a variadic
6497 // format function from a format function that has fixed arguments. For
6498 // instance:
6499 //
6500 // __attribute__((format(printf, 1, 2)))
6501 // void logstring(char const *fmt, char const *str) {
6502 // printf(fmt, str); /* do not emit a warning about "fmt" */
6503 // }
6504 //
6505 // Same (and perhaps more relatably) for the variadic template case:
6506 //
6507 // template<typename... Args>
6508 // __attribute__((format(printf, 1, 2)))
6509 // void log(const char *fmt, Args&&... args) {
6510 // printf(fmt, forward<Args>(args)...);
6511 // /* do not emit a warning about "fmt" */
6512 // }
6513 //
6514 // Due to implementation difficulty, we only check the format, not the
6515 // format arguments, in all cases.
6516 //
6517 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
6518 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
6519 for (const auto *PVFormatMatches :
6520 D->specific_attrs<FormatMatchesAttr>()) {
6521 Sema::FormatStringInfo CalleeFSI;
6522 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
6523 0, &CalleeFSI))
6524 continue;
6525 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
6526 // If using the wrong type of format string, emit a diagnostic
6527 // here and stop checking to avoid irrelevant diagnostics.
6528 if (Type != S.GetFormatStringType(PVFormatMatches)) {
6529 S.Diag(Args[format_idx]->getBeginLoc(),
6530 diag::warn_format_string_type_incompatible)
6531 << PVFormatMatches->getType()->getName()
6533 if (!InFunctionCall) {
6534 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
6535 diag::note_format_string_defined);
6536 }
6537 return SLCT_UncheckedLiteral;
6538 }
6539 return checkFormatStringExpr(
6540 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
6541 Args, APK, format_idx, firstDataArg, Type, CallType,
6542 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
6543 Offset, IgnoreStringsWithoutSpecifiers);
6544 }
6545 }
6546
6547 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
6548 Sema::FormatStringInfo CallerFSI;
6549 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
6550 PVFormat->getFirstArg(), &CallerFSI))
6551 continue;
6552 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
6553 // We also check if the formats are compatible.
6554 // We can't pass a 'scanf' string to a 'printf' function.
6555 if (Type != S.GetFormatStringType(PVFormat)) {
6556 S.Diag(Args[format_idx]->getBeginLoc(),
6557 diag::warn_format_string_type_incompatible)
6558 << PVFormat->getType()->getName()
6560 if (!InFunctionCall) {
6561 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
6562 }
6563 return SLCT_UncheckedLiteral;
6564 }
6565 // Lastly, check that argument passing kinds transition in a
6566 // way that makes sense:
6567 // from a caller with FAPK_VAList, allow FAPK_VAList
6568 // from a caller with FAPK_Fixed, allow FAPK_Fixed
6569 // from a caller with FAPK_Fixed, allow FAPK_Variadic
6570 // from a caller with FAPK_Variadic, allow FAPK_VAList
6571 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
6576 return SLCT_UncheckedLiteral;
6577 }
6578 }
6579 }
6580 }
6581 }
6582 }
6583
6584 return SLCT_NotALiteral;
6585 }
6586
6587 case Stmt::CallExprClass:
6588 case Stmt::CXXMemberCallExprClass: {
6589 const CallExpr *CE = cast<CallExpr>(E);
6590 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6591 bool IsFirst = true;
6592 StringLiteralCheckType CommonResult;
6593 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6594 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6595 StringLiteralCheckType Result = checkFormatStringExpr(
6596 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
6597 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
6598 Offset, IgnoreStringsWithoutSpecifiers);
6599 if (IsFirst) {
6600 CommonResult = Result;
6601 IsFirst = false;
6602 }
6603 }
6604 if (!IsFirst)
6605 return CommonResult;
6606
6607 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6608 unsigned BuiltinID = FD->getBuiltinID();
6609 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6610 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6611 const Expr *Arg = CE->getArg(0);
6612 return checkFormatStringExpr(
6613 S, ReferenceFormatString, Arg, Args, APK, format_idx,
6614 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6615 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6616 }
6617 }
6618 }
6619 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
6620 return checkFormatStringExpr(
6621 S, ReferenceFormatString, SLE, Args, APK, format_idx, firstDataArg,
6622 Type, CallType, /*InFunctionCall*/ false, CheckedVarArgs,
6623 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6624 return SLCT_NotALiteral;
6625 }
6626 case Stmt::ObjCMessageExprClass: {
6627 const auto *ME = cast<ObjCMessageExpr>(E);
6628 if (const auto *MD = ME->getMethodDecl()) {
6629 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6630 // As a special case heuristic, if we're using the method -[NSBundle
6631 // localizedStringForKey:value:table:], ignore any key strings that lack
6632 // format specifiers. The idea is that if the key doesn't have any
6633 // format specifiers then its probably just a key to map to the
6634 // localized strings. If it does have format specifiers though, then its
6635 // likely that the text of the key is the format string in the
6636 // programmer's language, and should be checked.
6637 const ObjCInterfaceDecl *IFace;
6638 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6639 IFace->getIdentifier()->isStr("NSBundle") &&
6640 MD->getSelector().isKeywordSelector(
6641 {"localizedStringForKey", "value", "table"})) {
6642 IgnoreStringsWithoutSpecifiers = true;
6643 }
6644
6645 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6646 return checkFormatStringExpr(
6647 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
6648 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
6649 Offset, IgnoreStringsWithoutSpecifiers);
6650 }
6651 }
6652
6653 return SLCT_NotALiteral;
6654 }
6655 case Stmt::ObjCStringLiteralClass:
6656 case Stmt::StringLiteralClass: {
6657 const StringLiteral *StrE = nullptr;
6658
6659 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6660 StrE = ObjCFExpr->getString();
6661 else
6662 StrE = cast<StringLiteral>(E);
6663
6664 if (StrE) {
6665 if (Offset.isNegative() || Offset > StrE->getLength()) {
6666 // TODO: It would be better to have an explicit warning for out of
6667 // bounds literals.
6668 return SLCT_NotALiteral;
6669 }
6670 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6671 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
6672 format_idx, firstDataArg, Type, InFunctionCall,
6673 CallType, CheckedVarArgs, UncoveredArg,
6674 IgnoreStringsWithoutSpecifiers);
6675 return SLCT_CheckedLiteral;
6676 }
6677
6678 return SLCT_NotALiteral;
6679 }
6680 case Stmt::BinaryOperatorClass: {
6681 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6682
6683 // A string literal + an int offset is still a string literal.
6684 if (BinOp->isAdditiveOp()) {
6685 Expr::EvalResult LResult, RResult;
6686
6687 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6688 LResult, S.Context, Expr::SE_NoSideEffects,
6690 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6691 RResult, S.Context, Expr::SE_NoSideEffects,
6693
6694 if (LIsInt != RIsInt) {
6695 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6696
6697 if (LIsInt) {
6698 if (BinOpKind == BO_Add) {
6699 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6700 E = BinOp->getRHS();
6701 goto tryAgain;
6702 }
6703 } else {
6704 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6705 E = BinOp->getLHS();
6706 goto tryAgain;
6707 }
6708 }
6709 }
6710
6711 return SLCT_NotALiteral;
6712 }
6713 case Stmt::UnaryOperatorClass: {
6714 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6715 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6716 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6717 Expr::EvalResult IndexResult;
6718 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6721 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6722 /*RHS is int*/ true);
6723 E = ASE->getBase();
6724 goto tryAgain;
6725 }
6726 }
6727
6728 return SLCT_NotALiteral;
6729 }
6730
6731 default:
6732 return SLCT_NotALiteral;
6733 }
6734}
6735
6736// If this expression can be evaluated at compile-time,
6737// check if the result is a StringLiteral and return it
6738// otherwise return nullptr
6740 const Expr *E) {
6742 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
6743 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
6744 if (isa_and_nonnull<StringLiteral>(LVE))
6745 return LVE;
6746 }
6747 return nullptr;
6748}
6749
6751 switch (FST) {
6753 return "scanf";
6755 return "printf";
6757 return "NSString";
6759 return "strftime";
6761 return "strfmon";
6763 return "kprintf";
6765 return "freebsd_kprintf";
6767 return "os_log";
6768 default:
6769 return "<unknown>";
6770 }
6771}
6772
6774 return llvm::StringSwitch<FormatStringType>(Flavor)
6775 .Case("scanf", FormatStringType::Scanf)
6776 .Cases("printf", "printf0", "syslog", FormatStringType::Printf)
6777 .Cases("NSString", "CFString", FormatStringType::NSString)
6778 .Case("strftime", FormatStringType::Strftime)
6779 .Case("strfmon", FormatStringType::Strfmon)
6780 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err",
6782 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
6783 .Case("os_trace", FormatStringType::OSLog)
6784 .Case("os_log", FormatStringType::OSLog)
6785 .Default(FormatStringType::Unknown);
6786}
6787
6789 return GetFormatStringType(Format->getType()->getName());
6790}
6791
6792FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
6793 return GetFormatStringType(Format->getType()->getName());
6794}
6795
6796bool Sema::CheckFormatArguments(const FormatAttr *Format,
6797 ArrayRef<const Expr *> Args, bool IsCXXMember,
6800 llvm::SmallBitVector &CheckedVarArgs) {
6801 FormatStringInfo FSI;
6802 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
6803 IsCXXMember,
6804 CallType != VariadicCallType::DoesNotApply, &FSI))
6805 return CheckFormatArguments(
6806 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
6807 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
6808 return false;
6809}
6810
6811bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
6812 ArrayRef<const Expr *> Args, bool IsCXXMember,
6815 llvm::SmallBitVector &CheckedVarArgs) {
6816 FormatStringInfo FSI;
6817 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
6818 &FSI)) {
6819 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
6820 return CheckFormatArguments(Args, FSI.ArgPassingKind,
6821 Format->getFormatString(), FSI.FormatIdx,
6822 FSI.FirstDataArg, GetFormatStringType(Format),
6823 CallType, Loc, Range, CheckedVarArgs);
6824 }
6825 return false;
6826}
6827
6828bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6830 const StringLiteral *ReferenceFormatString,
6831 unsigned format_idx, unsigned firstDataArg,
6835 llvm::SmallBitVector &CheckedVarArgs) {
6836 // CHECK: printf/scanf-like function is called with no format string.
6837 if (format_idx >= Args.size()) {
6838 Diag(Loc, diag::warn_missing_format_string) << Range;
6839 return false;
6840 }
6841
6842 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6843
6844 // CHECK: format string is not a string literal.
6845 //
6846 // Dynamically generated format strings are difficult to
6847 // automatically vet at compile time. Requiring that format strings
6848 // are string literals: (1) permits the checking of format strings by
6849 // the compiler and thereby (2) can practically remove the source of
6850 // many format string exploits.
6851
6852 // Format string can be either ObjC string (e.g. @"%d") or
6853 // C string (e.g. "%d")
6854 // ObjC string uses the same format specifiers as C string, so we can use
6855 // the same format string checking logic for both ObjC and C strings.
6856 UncoveredArgHandler UncoveredArg;
6857 StringLiteralCheckType CT = checkFormatStringExpr(
6858 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
6859 firstDataArg, Type, CallType,
6860 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
6861 /*no string offset*/ llvm::APSInt(64, false) = 0);
6862
6863 // Generate a diagnostic where an uncovered argument is detected.
6864 if (UncoveredArg.hasUncoveredArg()) {
6865 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6866 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6867 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6868 }
6869
6870 if (CT != SLCT_NotALiteral)
6871 // Literal format string found, check done!
6872 return CT == SLCT_CheckedLiteral;
6873
6874 // Strftime is particular as it always uses a single 'time' argument,
6875 // so it is safe to pass a non-literal string.
6877 return false;
6878
6879 // Do not emit diag when the string param is a macro expansion and the
6880 // format is either NSString or CFString. This is a hack to prevent
6881 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6882 // which are usually used in place of NS and CF string literals.
6883 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
6885 SourceMgr.isInSystemMacro(FormatLoc))
6886 return false;
6887
6888 // If there are no arguments specified, warn with -Wformat-security, otherwise
6889 // warn only with -Wformat-nonliteral.
6890 if (Args.size() == firstDataArg) {
6891 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6892 << OrigFormatExpr->getSourceRange();
6893 switch (Type) {
6894 default:
6895 break;
6900 Diag(FormatLoc, diag::note_format_security_fixit)
6901 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
6902 break;
6904 Diag(FormatLoc, diag::note_format_security_fixit)
6905 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
6906 break;
6907 }
6908 } else {
6909 Diag(FormatLoc, diag::warn_format_nonliteral)
6910 << OrigFormatExpr->getSourceRange();
6911 }
6912 return false;
6913}
6914
6915namespace {
6916
6917class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6918protected:
6919 Sema &S;
6920 const FormatStringLiteral *FExpr;
6921 const Expr *OrigFormatExpr;
6922 const FormatStringType FSType;
6923 const unsigned FirstDataArg;
6924 const unsigned NumDataArgs;
6925 const char *Beg; // Start of format string.
6926 const Sema::FormatArgumentPassingKind ArgPassingKind;
6928 unsigned FormatIdx;
6929 llvm::SmallBitVector CoveredArgs;
6930 bool usesPositionalArgs = false;
6931 bool atFirstArg = true;
6932 bool inFunctionCall;
6933 VariadicCallType CallType;
6934 llvm::SmallBitVector &CheckedVarArgs;
6935 UncoveredArgHandler &UncoveredArg;
6936
6937public:
6938 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
6939 const Expr *origFormatExpr, const FormatStringType type,
6940 unsigned firstDataArg, unsigned numDataArgs,
6941 const char *beg, Sema::FormatArgumentPassingKind APK,
6942 ArrayRef<const Expr *> Args, unsigned formatIdx,
6943 bool inFunctionCall, VariadicCallType callType,
6944 llvm::SmallBitVector &CheckedVarArgs,
6945 UncoveredArgHandler &UncoveredArg)
6946 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
6947 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
6948 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
6949 inFunctionCall(inFunctionCall), CallType(callType),
6950 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
6951 CoveredArgs.resize(numDataArgs);
6952 CoveredArgs.reset();
6953 }
6954
6955 bool HasFormatArguments() const {
6956 return ArgPassingKind == Sema::FAPK_Fixed ||
6957 ArgPassingKind == Sema::FAPK_Variadic;
6958 }
6959
6960 void DoneProcessing();
6961
6962 void HandleIncompleteSpecifier(const char *startSpecifier,
6963 unsigned specifierLen) override;
6964
6965 void HandleInvalidLengthModifier(
6968 const char *startSpecifier, unsigned specifierLen,
6969 unsigned DiagID);
6970
6971 void HandleNonStandardLengthModifier(
6973 const char *startSpecifier, unsigned specifierLen);
6974
6975 void HandleNonStandardConversionSpecifier(
6977 const char *startSpecifier, unsigned specifierLen);
6978
6979 void HandlePosition(const char *startPos, unsigned posLen) override;
6980
6981 void HandleInvalidPosition(const char *startSpecifier,
6982 unsigned specifierLen,
6984
6985 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
6986
6987 void HandleNullChar(const char *nullCharacter) override;
6988
6989 template <typename Range>
6990 static void
6991 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
6992 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
6993 bool IsStringLocation, Range StringRange,
6994 ArrayRef<FixItHint> Fixit = {});
6995
6996protected:
6997 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
6998 const char *startSpec,
6999 unsigned specifierLen,
7000 const char *csStart, unsigned csLen);
7001
7002 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7003 const char *startSpec,
7004 unsigned specifierLen);
7005
7006 SourceRange getFormatStringRange();
7007 CharSourceRange getSpecifierRange(const char *startSpecifier,
7008 unsigned specifierLen);
7009 SourceLocation getLocationOfByte(const char *x);
7010
7011 const Expr *getDataArg(unsigned i) const;
7012
7013 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7015 const char *startSpecifier, unsigned specifierLen,
7016 unsigned argIndex);
7017
7018 template <typename Range>
7019 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7020 bool IsStringLocation, Range StringRange,
7021 ArrayRef<FixItHint> Fixit = {});
7022};
7023
7024} // namespace
7025
7026SourceRange CheckFormatHandler::getFormatStringRange() {
7027 return OrigFormatExpr->getSourceRange();
7028}
7029
7030CharSourceRange CheckFormatHandler::
7031getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7032 SourceLocation Start = getLocationOfByte(startSpecifier);
7033 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
7034
7035 // Advance the end SourceLocation by one due to half-open ranges.
7036 End = End.getLocWithOffset(1);
7037
7038 return CharSourceRange::getCharRange(Start, End);
7039}
7040
7041SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7042 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7044}
7045
7046void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7047 unsigned specifierLen){
7048 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7049 getLocationOfByte(startSpecifier),
7050 /*IsStringLocation*/true,
7051 getSpecifierRange(startSpecifier, specifierLen));
7052}
7053
7054void CheckFormatHandler::HandleInvalidLengthModifier(
7057 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7058 using namespace analyze_format_string;
7059
7060 const LengthModifier &LM = FS.getLengthModifier();
7061 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7062
7063 // See if we know how to fix this length modifier.
7064 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7065 if (FixedLM) {
7066 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7067 getLocationOfByte(LM.getStart()),
7068 /*IsStringLocation*/true,
7069 getSpecifierRange(startSpecifier, specifierLen));
7070
7071 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7072 << FixedLM->toString()
7073 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7074
7075 } else {
7076 FixItHint Hint;
7077 if (DiagID == diag::warn_format_nonsensical_length)
7078 Hint = FixItHint::CreateRemoval(LMRange);
7079
7080 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7081 getLocationOfByte(LM.getStart()),
7082 /*IsStringLocation*/true,
7083 getSpecifierRange(startSpecifier, specifierLen),
7084 Hint);
7085 }
7086}
7087
7088void CheckFormatHandler::HandleNonStandardLengthModifier(
7090 const char *startSpecifier, unsigned specifierLen) {
7091 using namespace analyze_format_string;
7092
7093 const LengthModifier &LM = FS.getLengthModifier();
7094 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7095
7096 // See if we know how to fix this length modifier.
7097 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7098 if (FixedLM) {
7099 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7100 << LM.toString() << 0,
7101 getLocationOfByte(LM.getStart()),
7102 /*IsStringLocation*/true,
7103 getSpecifierRange(startSpecifier, specifierLen));
7104
7105 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7106 << FixedLM->toString()
7107 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7108
7109 } else {
7110 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7111 << LM.toString() << 0,
7112 getLocationOfByte(LM.getStart()),
7113 /*IsStringLocation*/true,
7114 getSpecifierRange(startSpecifier, specifierLen));
7115 }
7116}
7117
7118void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7120 const char *startSpecifier, unsigned specifierLen) {
7121 using namespace analyze_format_string;
7122
7123 // See if we know how to fix this conversion specifier.
7124 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7125 if (FixedCS) {
7126 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7127 << CS.toString() << /*conversion specifier*/1,
7128 getLocationOfByte(CS.getStart()),
7129 /*IsStringLocation*/true,
7130 getSpecifierRange(startSpecifier, specifierLen));
7131
7132 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7133 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7134 << FixedCS->toString()
7135 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7136 } else {
7137 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7138 << CS.toString() << /*conversion specifier*/1,
7139 getLocationOfByte(CS.getStart()),
7140 /*IsStringLocation*/true,
7141 getSpecifierRange(startSpecifier, specifierLen));
7142 }
7143}
7144
7145void CheckFormatHandler::HandlePosition(const char *startPos,
7146 unsigned posLen) {
7147 if (!S.getDiagnostics().isIgnored(
7148 diag::warn_format_non_standard_positional_arg, SourceLocation()))
7149 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7150 getLocationOfByte(startPos),
7151 /*IsStringLocation*/ true,
7152 getSpecifierRange(startPos, posLen));
7153}
7154
7155void CheckFormatHandler::HandleInvalidPosition(
7156 const char *startSpecifier, unsigned specifierLen,
7158 if (!S.getDiagnostics().isIgnored(
7159 diag::warn_format_invalid_positional_specifier, SourceLocation()))
7160 EmitFormatDiagnostic(
7161 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
7162 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
7163 getSpecifierRange(startSpecifier, specifierLen));
7164}
7165
7166void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7167 unsigned posLen) {
7168 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
7169 SourceLocation()))
7170 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7171 getLocationOfByte(startPos),
7172 /*IsStringLocation*/ true,
7173 getSpecifierRange(startPos, posLen));
7174}
7175
7176void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7177 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7178 // The presence of a null character is likely an error.
7179 EmitFormatDiagnostic(
7180 S.PDiag(diag::warn_printf_format_string_contains_null_char),
7181 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7182 getFormatStringRange());
7183 }
7184}
7185
7186// Note that this may return NULL if there was an error parsing or building
7187// one of the argument expressions.
7188const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7189 return Args[FirstDataArg + i];
7190}
7191
7192void CheckFormatHandler::DoneProcessing() {
7193 // Does the number of data arguments exceed the number of
7194 // format conversions in the format string?
7195 if (HasFormatArguments()) {
7196 // Find any arguments that weren't covered.
7197 CoveredArgs.flip();
7198 signed notCoveredArg = CoveredArgs.find_first();
7199 if (notCoveredArg >= 0) {
7200 assert((unsigned)notCoveredArg < NumDataArgs);
7201 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7202 } else {
7203 UncoveredArg.setAllCovered();
7204 }
7205 }
7206}
7207
7208void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7209 const Expr *ArgExpr) {
7210 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
7211 "Invalid state");
7212
7213 if (!ArgExpr)
7214 return;
7215
7216 SourceLocation Loc = ArgExpr->getBeginLoc();
7217
7219 return;
7220
7221 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7222 for (auto E : DiagnosticExprs)
7223 PDiag << E->getSourceRange();
7224
7225 CheckFormatHandler::EmitFormatDiagnostic(
7226 S, IsFunctionCall, DiagnosticExprs[0],
7227 PDiag, Loc, /*IsStringLocation*/false,
7228 DiagnosticExprs[0]->getSourceRange());
7229}
7230
7231bool
7232CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7234 const char *startSpec,
7235 unsigned specifierLen,
7236 const char *csStart,
7237 unsigned csLen) {
7238 bool keepGoing = true;
7239 if (argIndex < NumDataArgs) {
7240 // Consider the argument coverered, even though the specifier doesn't
7241 // make sense.
7242 CoveredArgs.set(argIndex);
7243 }
7244 else {
7245 // If argIndex exceeds the number of data arguments we
7246 // don't issue a warning because that is just a cascade of warnings (and
7247 // they may have intended '%%' anyway). We don't want to continue processing
7248 // the format string after this point, however, as we will like just get
7249 // gibberish when trying to match arguments.
7250 keepGoing = false;
7251 }
7252
7253 StringRef Specifier(csStart, csLen);
7254
7255 // If the specifier in non-printable, it could be the first byte of a UTF-8
7256 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7257 // hex value.
7258 std::string CodePointStr;
7259 if (!llvm::sys::locale::isPrint(*csStart)) {
7260 llvm::UTF32 CodePoint;
7261 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7262 const llvm::UTF8 *E =
7263 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7264 llvm::ConversionResult Result =
7265 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7266
7267 if (Result != llvm::conversionOK) {
7268 unsigned char FirstChar = *csStart;
7269 CodePoint = (llvm::UTF32)FirstChar;
7270 }
7271
7272 llvm::raw_string_ostream OS(CodePointStr);
7273 if (CodePoint < 256)
7274 OS << "\\x" << llvm::format("%02x", CodePoint);
7275 else if (CodePoint <= 0xFFFF)
7276 OS << "\\u" << llvm::format("%04x", CodePoint);
7277 else
7278 OS << "\\U" << llvm::format("%08x", CodePoint);
7279 Specifier = CodePointStr;
7280 }
7281
7282 EmitFormatDiagnostic(
7283 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7284 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7285
7286 return keepGoing;
7287}
7288
7289void
7290CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7291 const char *startSpec,
7292 unsigned specifierLen) {
7293 EmitFormatDiagnostic(
7294 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7295 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7296}
7297
7298bool
7299CheckFormatHandler::CheckNumArgs(
7302 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7303
7304 if (HasFormatArguments() && argIndex >= NumDataArgs) {
7305 PartialDiagnostic PDiag = FS.usesPositionalArg()
7306 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7307 << (argIndex+1) << NumDataArgs)
7308 : S.PDiag(diag::warn_printf_insufficient_data_args);
7309 EmitFormatDiagnostic(
7310 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7311 getSpecifierRange(startSpecifier, specifierLen));
7312
7313 // Since more arguments than conversion tokens are given, by extension
7314 // all arguments are covered, so mark this as so.
7315 UncoveredArg.setAllCovered();
7316 return false;
7317 }
7318 return true;
7319}
7320
7321template<typename Range>
7322void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7324 bool IsStringLocation,
7325 Range StringRange,
7326 ArrayRef<FixItHint> FixIt) {
7327 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7328 Loc, IsStringLocation, StringRange, FixIt);
7329}
7330
7331/// If the format string is not within the function call, emit a note
7332/// so that the function call and string are in diagnostic messages.
7333///
7334/// \param InFunctionCall if true, the format string is within the function
7335/// call and only one diagnostic message will be produced. Otherwise, an
7336/// extra note will be emitted pointing to location of the format string.
7337///
7338/// \param ArgumentExpr the expression that is passed as the format string
7339/// argument in the function call. Used for getting locations when two
7340/// diagnostics are emitted.
7341///
7342/// \param PDiag the callee should already have provided any strings for the
7343/// diagnostic message. This function only adds locations and fixits
7344/// to diagnostics.
7345///
7346/// \param Loc primary location for diagnostic. If two diagnostics are
7347/// required, one will be at Loc and a new SourceLocation will be created for
7348/// the other one.
7349///
7350/// \param IsStringLocation if true, Loc points to the format string should be
7351/// used for the note. Otherwise, Loc points to the argument list and will
7352/// be used with PDiag.
7353///
7354/// \param StringRange some or all of the string to highlight. This is
7355/// templated so it can accept either a CharSourceRange or a SourceRange.
7356///
7357/// \param FixIt optional fix it hint for the format string.
7358template <typename Range>
7359void CheckFormatHandler::EmitFormatDiagnostic(
7360 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7361 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7362 Range StringRange, ArrayRef<FixItHint> FixIt) {
7363 if (InFunctionCall) {
7364 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7365 D << StringRange;
7366 D << FixIt;
7367 } else {
7368 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7369 << ArgumentExpr->getSourceRange();
7370
7372 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7373 diag::note_format_string_defined);
7374
7375 Note << StringRange;
7376 Note << FixIt;
7377 }
7378}
7379
7380//===--- CHECK: Printf format string checking -----------------------------===//
7381
7382namespace {
7383
7384class CheckPrintfHandler : public CheckFormatHandler {
7385public:
7386 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7387 const Expr *origFormatExpr, const FormatStringType type,
7388 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
7389 const char *beg, Sema::FormatArgumentPassingKind APK,
7390 ArrayRef<const Expr *> Args, unsigned formatIdx,
7391 bool inFunctionCall, VariadicCallType CallType,
7392 llvm::SmallBitVector &CheckedVarArgs,
7393 UncoveredArgHandler &UncoveredArg)
7394 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7395 numDataArgs, beg, APK, Args, formatIdx,
7396 inFunctionCall, CallType, CheckedVarArgs,
7397 UncoveredArg) {}
7398
7399 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
7400
7401 /// Returns true if '%@' specifiers are allowed in the format string.
7402 bool allowsObjCArg() const {
7403 return FSType == FormatStringType::NSString ||
7404 FSType == FormatStringType::OSLog ||
7405 FSType == FormatStringType::OSTrace;
7406 }
7407
7408 bool HandleInvalidPrintfConversionSpecifier(
7410 const char *startSpecifier,
7411 unsigned specifierLen) override;
7412
7413 void handleInvalidMaskType(StringRef MaskType) override;
7414
7415 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7416 const char *startSpecifier, unsigned specifierLen,
7417 const TargetInfo &Target) override;
7418 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7419 const char *StartSpecifier,
7420 unsigned SpecifierLen,
7421 const Expr *E);
7422
7423 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7424 const char *startSpecifier, unsigned specifierLen);
7425 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7427 unsigned type,
7428 const char *startSpecifier, unsigned specifierLen);
7429 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7430 const analyze_printf::OptionalFlag &flag,
7431 const char *startSpecifier, unsigned specifierLen);
7432 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7433 const analyze_printf::OptionalFlag &ignoredFlag,
7434 const analyze_printf::OptionalFlag &flag,
7435 const char *startSpecifier, unsigned specifierLen);
7436 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7437 const Expr *E);
7438
7439 void HandleEmptyObjCModifierFlag(const char *startFlag,
7440 unsigned flagLen) override;
7441
7442 void HandleInvalidObjCModifierFlag(const char *startFlag,
7443 unsigned flagLen) override;
7444
7445 void
7446 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7447 const char *flagsEnd,
7448 const char *conversionPosition) override;
7449};
7450
7451/// Keeps around the information needed to verify that two specifiers are
7452/// compatible.
7453class EquatableFormatArgument {
7454public:
7455 enum SpecifierSensitivity : unsigned {
7456 SS_None,
7457 SS_Private,
7458 SS_Public,
7459 SS_Sensitive
7460 };
7461
7462 enum FormatArgumentRole : unsigned {
7463 FAR_Data,
7464 FAR_FieldWidth,
7465 FAR_Precision,
7466 FAR_Auxiliary, // FreeBSD kernel %b and %D
7467 };
7468
7469private:
7472 StringRef SpecifierLetter;
7474 SourceLocation ElementLoc;
7475 FormatArgumentRole Role : 2;
7476 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
7477 unsigned Position : 14;
7478 unsigned ModifierFor : 14; // not set for FAR_Data
7479
7480 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
7481 bool InFunctionCall) const;
7482
7483public:
7484 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
7486 StringRef SpecifierLetter,
7488 FormatArgumentRole Role,
7489 SpecifierSensitivity Sensitivity, unsigned Position,
7490 unsigned ModifierFor)
7491 : ArgType(ArgType), LengthMod(LengthMod),
7492 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
7493 Role(Role), Sensitivity(Sensitivity), Position(Position),
7494 ModifierFor(ModifierFor) {}
7495
7496 unsigned getPosition() const { return Position; }
7497 SourceLocation getSourceLocation() const { return ElementLoc; }
7498 CharSourceRange getSourceRange() const { return Range; }
7499 analyze_format_string::LengthModifier getLengthModifier() const {
7500 return analyze_format_string::LengthModifier(nullptr, LengthMod);
7501 }
7502 void setModifierFor(unsigned V) { ModifierFor = V; }
7503
7504 std::string buildFormatSpecifier() const {
7505 std::string result;
7506 llvm::raw_string_ostream(result)
7507 << getLengthModifier().toString() << SpecifierLetter;
7508 return result;
7509 }
7510
7511 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
7512 const Expr *FmtExpr, bool InFunctionCall) const;
7513};
7514
7515/// Turns format strings into lists of EquatableSpecifier objects.
7516class DecomposePrintfHandler : public CheckPrintfHandler {
7518 bool HadError;
7519
7520 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7521 const Expr *origFormatExpr,
7522 const FormatStringType type, unsigned firstDataArg,
7523 unsigned numDataArgs, bool isObjC, const char *beg,
7525 ArrayRef<const Expr *> Args, unsigned formatIdx,
7526 bool inFunctionCall, VariadicCallType CallType,
7527 llvm::SmallBitVector &CheckedVarArgs,
7528 UncoveredArgHandler &UncoveredArg,
7530 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7531 numDataArgs, isObjC, beg, APK, Args, formatIdx,
7532 inFunctionCall, CallType, CheckedVarArgs,
7533 UncoveredArg),
7534 Specs(Specs), HadError(false) {}
7535
7536public:
7537 static bool
7538 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
7539 FormatStringType type, bool IsObjC, bool InFunctionCall,
7541
7542 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7543 const char *startSpecifier,
7544 unsigned specifierLen,
7545 const TargetInfo &Target) override;
7546};
7547
7548} // namespace
7549
7550bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7551 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
7552 unsigned specifierLen) {
7554 FS.getConversionSpecifier();
7555
7556 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7557 getLocationOfByte(CS.getStart()),
7558 startSpecifier, specifierLen,
7559 CS.getStart(), CS.getLength());
7560}
7561
7562void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7563 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7564}
7565
7566bool CheckPrintfHandler::HandleAmount(
7567 const analyze_format_string::OptionalAmount &Amt, unsigned k,
7568 const char *startSpecifier, unsigned specifierLen) {
7569 if (Amt.hasDataArgument()) {
7570 if (HasFormatArguments()) {
7571 unsigned argIndex = Amt.getArgIndex();
7572 if (argIndex >= NumDataArgs) {
7573 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7574 << k,
7575 getLocationOfByte(Amt.getStart()),
7576 /*IsStringLocation*/ true,
7577 getSpecifierRange(startSpecifier, specifierLen));
7578 // Don't do any more checking. We will just emit
7579 // spurious errors.
7580 return false;
7581 }
7582
7583 // Type check the data argument. It should be an 'int'.
7584 // Although not in conformance with C99, we also allow the argument to be
7585 // an 'unsigned int' as that is a reasonably safe case. GCC also
7586 // doesn't emit a warning for that case.
7587 CoveredArgs.set(argIndex);
7588 const Expr *Arg = getDataArg(argIndex);
7589 if (!Arg)
7590 return false;
7591
7592 QualType T = Arg->getType();
7593
7594 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7595 assert(AT.isValid());
7596
7597 if (!AT.matchesType(S.Context, T)) {
7598 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7600 << T << Arg->getSourceRange(),
7601 getLocationOfByte(Amt.getStart()),
7602 /*IsStringLocation*/true,
7603 getSpecifierRange(startSpecifier, specifierLen));
7604 // Don't do any more checking. We will just emit
7605 // spurious errors.
7606 return false;
7607 }
7608 }
7609 }
7610 return true;
7611}
7612
7613void CheckPrintfHandler::HandleInvalidAmount(
7616 unsigned type,
7617 const char *startSpecifier,
7618 unsigned specifierLen) {
7620 FS.getConversionSpecifier();
7621
7622 FixItHint fixit =
7624 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7625 Amt.getConstantLength()))
7626 : FixItHint();
7627
7628 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7629 << type << CS.toString(),
7630 getLocationOfByte(Amt.getStart()),
7631 /*IsStringLocation*/true,
7632 getSpecifierRange(startSpecifier, specifierLen),
7633 fixit);
7634}
7635
7636void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7637 const analyze_printf::OptionalFlag &flag,
7638 const char *startSpecifier,
7639 unsigned specifierLen) {
7640 // Warn about pointless flag with a fixit removal.
7642 FS.getConversionSpecifier();
7643 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7644 << flag.toString() << CS.toString(),
7645 getLocationOfByte(flag.getPosition()),
7646 /*IsStringLocation*/true,
7647 getSpecifierRange(startSpecifier, specifierLen),
7649 getSpecifierRange(flag.getPosition(), 1)));
7650}
7651
7652void CheckPrintfHandler::HandleIgnoredFlag(
7654 const analyze_printf::OptionalFlag &ignoredFlag,
7655 const analyze_printf::OptionalFlag &flag,
7656 const char *startSpecifier,
7657 unsigned specifierLen) {
7658 // Warn about ignored flag with a fixit removal.
7659 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7660 << ignoredFlag.toString() << flag.toString(),
7661 getLocationOfByte(ignoredFlag.getPosition()),
7662 /*IsStringLocation*/true,
7663 getSpecifierRange(startSpecifier, specifierLen),
7665 getSpecifierRange(ignoredFlag.getPosition(), 1)));
7666}
7667
7668void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7669 unsigned flagLen) {
7670 // Warn about an empty flag.
7671 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7672 getLocationOfByte(startFlag),
7673 /*IsStringLocation*/true,
7674 getSpecifierRange(startFlag, flagLen));
7675}
7676
7677void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7678 unsigned flagLen) {
7679 // Warn about an invalid flag.
7680 auto Range = getSpecifierRange(startFlag, flagLen);
7681 StringRef flag(startFlag, flagLen);
7682 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7683 getLocationOfByte(startFlag),
7684 /*IsStringLocation*/true,
7686}
7687
7688void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7689 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7690 // Warn about using '[...]' without a '@' conversion.
7691 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7692 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7693 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7694 getLocationOfByte(conversionPosition),
7695 /*IsStringLocation*/ true, Range,
7697}
7698
7699void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
7700 const Expr *FmtExpr,
7701 bool InFunctionCall) const {
7702 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
7703 ElementLoc, true, Range);
7704}
7705
7706bool EquatableFormatArgument::VerifyCompatible(
7707 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
7708 bool InFunctionCall) const {
7710 if (Role != Other.Role) {
7711 // diagnose and stop
7712 EmitDiagnostic(
7713 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
7714 FmtExpr, InFunctionCall);
7715 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
7716 return false;
7717 }
7718
7719 if (Role != FAR_Data) {
7720 if (ModifierFor != Other.ModifierFor) {
7721 // diagnose and stop
7722 EmitDiagnostic(S,
7723 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
7724 << (ModifierFor + 1) << (Other.ModifierFor + 1),
7725 FmtExpr, InFunctionCall);
7726 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
7727 return false;
7728 }
7729 return true;
7730 }
7731
7732 bool HadError = false;
7733 if (Sensitivity != Other.Sensitivity) {
7734 // diagnose and continue
7735 EmitDiagnostic(S,
7736 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
7737 << Sensitivity << Other.Sensitivity,
7738 FmtExpr, InFunctionCall);
7739 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7740 << 0 << Other.Range;
7741 }
7742
7743 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
7744 case MK::Match:
7745 break;
7746
7747 case MK::MatchPromotion:
7748 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
7749 // MatchPromotion is treated as a failure by format_matches.
7750 case MK::NoMatch:
7751 case MK::NoMatchTypeConfusion:
7752 case MK::NoMatchPromotionTypeConfusion:
7753 EmitDiagnostic(S,
7754 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
7755 << buildFormatSpecifier()
7756 << Other.buildFormatSpecifier(),
7757 FmtExpr, InFunctionCall);
7758 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7759 << 0 << Other.Range;
7760 break;
7761
7762 case MK::NoMatchPedantic:
7763 EmitDiagnostic(S,
7764 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
7765 << buildFormatSpecifier()
7766 << Other.buildFormatSpecifier(),
7767 FmtExpr, InFunctionCall);
7768 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7769 << 0 << Other.Range;
7770 break;
7771
7772 case MK::NoMatchSignedness:
7773 EmitDiagnostic(S,
7774 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
7775 << buildFormatSpecifier()
7776 << Other.buildFormatSpecifier(),
7777 FmtExpr, InFunctionCall);
7778 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7779 << 0 << Other.Range;
7780 break;
7781 }
7782 return !HadError;
7783}
7784
7785bool DecomposePrintfHandler::GetSpecifiers(
7786 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
7787 FormatStringType Type, bool IsObjC, bool InFunctionCall,
7789 StringRef Data = FSL->getString();
7790 const char *Str = Data.data();
7791 llvm::SmallBitVector BV;
7792 UncoveredArgHandler UA;
7793 const Expr *PrintfArgs[] = {FSL->getFormatString()};
7794 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
7795 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
7796 InFunctionCall, VariadicCallType::DoesNotApply, BV,
7797 UA, Args);
7798
7800 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
7802 H.DoneProcessing();
7803 if (H.HadError)
7804 return false;
7805
7806 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
7807 const EquatableFormatArgument &B) {
7808 return A.getPosition() < B.getPosition();
7809 });
7810 return true;
7811}
7812
7813bool DecomposePrintfHandler::HandlePrintfSpecifier(
7814 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
7815 unsigned specifierLen, const TargetInfo &Target) {
7816 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
7817 specifierLen, Target)) {
7818 HadError = true;
7819 return false;
7820 }
7821
7822 // Do not add any specifiers to the list for %%. This is possibly incorrect
7823 // if using a precision/width with a data argument, but that combination is
7824 // meaningless and we wouldn't know which format to attach the
7825 // precision/width to.
7826 const auto &CS = FS.getConversionSpecifier();
7828 return true;
7829
7830 // have to patch these to have the right ModifierFor if they are used
7831 const unsigned Unset = ~0;
7832 unsigned FieldWidthIndex = Unset;
7833 unsigned PrecisionIndex = Unset;
7834
7835 // field width?
7836 const auto &FieldWidth = FS.getFieldWidth();
7837 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
7838 FieldWidthIndex = Specs.size();
7839 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
7840 getLocationOfByte(FieldWidth.getStart()),
7842 FieldWidth.getArgType(S.Context),
7843 EquatableFormatArgument::FAR_FieldWidth,
7844 EquatableFormatArgument::SS_None,
7845 FieldWidth.usesPositionalArg()
7846 ? FieldWidth.getPositionalArgIndex() - 1
7847 : FieldWidthIndex,
7848 0);
7849 }
7850 // precision?
7851 const auto &Precision = FS.getPrecision();
7852 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
7853 PrecisionIndex = Specs.size();
7854 Specs.emplace_back(
7855 getSpecifierRange(startSpecifier, specifierLen),
7856 getLocationOfByte(Precision.getStart()),
7858 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
7859 EquatableFormatArgument::SS_None,
7860 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
7861 : PrecisionIndex,
7862 0);
7863 }
7864
7865 // this specifier
7866 unsigned SpecIndex =
7867 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
7868 if (FieldWidthIndex != Unset)
7869 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
7870 if (PrecisionIndex != Unset)
7871 Specs[PrecisionIndex].setModifierFor(SpecIndex);
7872
7873 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
7874 if (FS.isPrivate())
7875 Sensitivity = EquatableFormatArgument::SS_Private;
7876 else if (FS.isPublic())
7877 Sensitivity = EquatableFormatArgument::SS_Public;
7878 else if (FS.isSensitive())
7879 Sensitivity = EquatableFormatArgument::SS_Sensitive;
7880 else
7881 Sensitivity = EquatableFormatArgument::SS_None;
7882
7883 Specs.emplace_back(
7884 getSpecifierRange(startSpecifier, specifierLen),
7885 getLocationOfByte(CS.getStart()), FS.getLengthModifier().getKind(),
7886 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
7887 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
7888
7889 // auxiliary argument?
7892 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
7893 getLocationOfByte(CS.getStart()),
7895 CS.getCharacters(),
7897 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
7898 SpecIndex + 1, SpecIndex);
7899 }
7900 return true;
7901}
7902
7903// Determines if the specified is a C++ class or struct containing
7904// a member with the specified name and kind (e.g. a CXXMethodDecl named
7905// "c_str()").
7906template<typename MemberKind>
7908CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7909 auto *RD = Ty->getAsCXXRecordDecl();
7911
7912 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
7913 return Results;
7914
7915 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7918
7919 // We just need to include all members of the right kind turned up by the
7920 // filter, at this point.
7921 if (S.LookupQualifiedName(R, RD))
7922 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7923 NamedDecl *decl = (*I)->getUnderlyingDecl();
7924 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7925 Results.insert(FK);
7926 }
7927 return Results;
7928}
7929
7930/// Check if we could call '.c_str()' on an object.
7931///
7932/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7933/// allow the call, or if it would be ambiguous).
7935 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7936
7937 MethodSet Results =
7938 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7939 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7940 MI != ME; ++MI)
7941 if ((*MI)->getMinRequiredArguments() == 0)
7942 return true;
7943 return false;
7944}
7945
7946// Check if a (w)string was passed when a (w)char* was needed, and offer a
7947// better diagnostic if so. AT is assumed to be valid.
7948// Returns true when a c_str() conversion method is found.
7949bool CheckPrintfHandler::checkForCStrMembers(
7950 const analyze_printf::ArgType &AT, const Expr *E) {
7951 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7952
7953 MethodSet Results =
7954 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7955
7956 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7957 MI != ME; ++MI) {
7958 const CXXMethodDecl *Method = *MI;
7959 if (Method->getMinRequiredArguments() == 0 &&
7960 AT.matchesType(S.Context, Method->getReturnType())) {
7961 // FIXME: Suggest parens if the expression needs them.
7963 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7964 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7965 return true;
7966 }
7967 }
7968
7969 return false;
7970}
7971
7972bool CheckPrintfHandler::HandlePrintfSpecifier(
7973 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
7974 unsigned specifierLen, const TargetInfo &Target) {
7975 using namespace analyze_format_string;
7976 using namespace analyze_printf;
7977
7978 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7979
7980 if (FS.consumesDataArgument()) {
7981 if (atFirstArg) {
7982 atFirstArg = false;
7983 usesPositionalArgs = FS.usesPositionalArg();
7984 }
7985 else if (usesPositionalArgs != FS.usesPositionalArg()) {
7986 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7987 startSpecifier, specifierLen);
7988 return false;
7989 }
7990 }
7991
7992 // First check if the field width, precision, and conversion specifier
7993 // have matching data arguments.
7994 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7995 startSpecifier, specifierLen)) {
7996 return false;
7997 }
7998
7999 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8000 startSpecifier, specifierLen)) {
8001 return false;
8002 }
8003
8004 if (!CS.consumesDataArgument()) {
8005 // FIXME: Technically specifying a precision or field width here
8006 // makes no sense. Worth issuing a warning at some point.
8007 return true;
8008 }
8009
8010 // Consume the argument.
8011 unsigned argIndex = FS.getArgIndex();
8012 if (argIndex < NumDataArgs) {
8013 // The check to see if the argIndex is valid will come later.
8014 // We set the bit here because we may exit early from this
8015 // function if we encounter some other error.
8016 CoveredArgs.set(argIndex);
8017 }
8018
8019 // FreeBSD kernel extensions.
8020 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8021 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8022 // We need at least two arguments.
8023 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8024 return false;
8025
8026 if (HasFormatArguments()) {
8027 // Claim the second argument.
8028 CoveredArgs.set(argIndex + 1);
8029
8030 // Type check the first argument (int for %b, pointer for %D)
8031 const Expr *Ex = getDataArg(argIndex);
8032 const analyze_printf::ArgType &AT =
8033 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
8034 ? ArgType(S.Context.IntTy)
8035 : ArgType::CPointerTy;
8036 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8037 EmitFormatDiagnostic(
8038 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8039 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8040 << false << Ex->getSourceRange(),
8041 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8042 getSpecifierRange(startSpecifier, specifierLen));
8043
8044 // Type check the second argument (char * for both %b and %D)
8045 Ex = getDataArg(argIndex + 1);
8046 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8047 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8048 EmitFormatDiagnostic(
8049 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8050 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8051 << false << Ex->getSourceRange(),
8052 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8053 getSpecifierRange(startSpecifier, specifierLen));
8054 }
8055 return true;
8056 }
8057
8058 // Check for using an Objective-C specific conversion specifier
8059 // in a non-ObjC literal.
8060 if (!allowsObjCArg() && CS.isObjCArg()) {
8061 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8062 specifierLen);
8063 }
8064
8065 // %P can only be used with os_log.
8066 if (FSType != FormatStringType::OSLog &&
8067 CS.getKind() == ConversionSpecifier::PArg) {
8068 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8069 specifierLen);
8070 }
8071
8072 // %n is not allowed with os_log.
8073 if (FSType == FormatStringType::OSLog &&
8074 CS.getKind() == ConversionSpecifier::nArg) {
8075 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8076 getLocationOfByte(CS.getStart()),
8077 /*IsStringLocation*/ false,
8078 getSpecifierRange(startSpecifier, specifierLen));
8079
8080 return true;
8081 }
8082
8083 // Only scalars are allowed for os_trace.
8084 if (FSType == FormatStringType::OSTrace &&
8085 (CS.getKind() == ConversionSpecifier::PArg ||
8086 CS.getKind() == ConversionSpecifier::sArg ||
8087 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8088 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8089 specifierLen);
8090 }
8091
8092 // Check for use of public/private annotation outside of os_log().
8093 if (FSType != FormatStringType::OSLog) {
8094 if (FS.isPublic().isSet()) {
8095 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8096 << "public",
8097 getLocationOfByte(FS.isPublic().getPosition()),
8098 /*IsStringLocation*/ false,
8099 getSpecifierRange(startSpecifier, specifierLen));
8100 }
8101 if (FS.isPrivate().isSet()) {
8102 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8103 << "private",
8104 getLocationOfByte(FS.isPrivate().getPosition()),
8105 /*IsStringLocation*/ false,
8106 getSpecifierRange(startSpecifier, specifierLen));
8107 }
8108 }
8109
8110 const llvm::Triple &Triple = Target.getTriple();
8111 if (CS.getKind() == ConversionSpecifier::nArg &&
8112 (Triple.isAndroid() || Triple.isOSFuchsia())) {
8113 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
8114 getLocationOfByte(CS.getStart()),
8115 /*IsStringLocation*/ false,
8116 getSpecifierRange(startSpecifier, specifierLen));
8117 }
8118
8119 // Check for invalid use of field width
8120 if (!FS.hasValidFieldWidth()) {
8121 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8122 startSpecifier, specifierLen);
8123 }
8124
8125 // Check for invalid use of precision
8126 if (!FS.hasValidPrecision()) {
8127 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8128 startSpecifier, specifierLen);
8129 }
8130
8131 // Precision is mandatory for %P specifier.
8132 if (CS.getKind() == ConversionSpecifier::PArg &&
8133 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8134 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8135 getLocationOfByte(startSpecifier),
8136 /*IsStringLocation*/ false,
8137 getSpecifierRange(startSpecifier, specifierLen));
8138 }
8139
8140 // Check each flag does not conflict with any other component.
8141 if (!FS.hasValidThousandsGroupingPrefix())
8142 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8143 if (!FS.hasValidLeadingZeros())
8144 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8145 if (!FS.hasValidPlusPrefix())
8146 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8147 if (!FS.hasValidSpacePrefix())
8148 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8149 if (!FS.hasValidAlternativeForm())
8150 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8151 if (!FS.hasValidLeftJustified())
8152 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8153
8154 // Check that flags are not ignored by another flag
8155 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8156 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8157 startSpecifier, specifierLen);
8158 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8159 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8160 startSpecifier, specifierLen);
8161
8162 // Check the length modifier is valid with the given conversion specifier.
8163 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8164 S.getLangOpts()))
8165 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8166 diag::warn_format_nonsensical_length);
8167 else if (!FS.hasStandardLengthModifier())
8168 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8169 else if (!FS.hasStandardLengthConversionCombination())
8170 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8171 diag::warn_format_non_standard_conversion_spec);
8172
8173 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8174 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8175
8176 // The remaining checks depend on the data arguments.
8177 if (!HasFormatArguments())
8178 return true;
8179
8180 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8181 return false;
8182
8183 const Expr *Arg = getDataArg(argIndex);
8184 if (!Arg)
8185 return true;
8186
8187 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8188}
8189
8190static bool requiresParensToAddCast(const Expr *E) {
8191 // FIXME: We should have a general way to reason about operator
8192 // precedence and whether parens are actually needed here.
8193 // Take care of a few common cases where they aren't.
8194 const Expr *Inside = E->IgnoreImpCasts();
8195 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8196 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8197
8198 switch (Inside->getStmtClass()) {
8199 case Stmt::ArraySubscriptExprClass:
8200 case Stmt::CallExprClass:
8201 case Stmt::CharacterLiteralClass:
8202 case Stmt::CXXBoolLiteralExprClass:
8203 case Stmt::DeclRefExprClass:
8204 case Stmt::FloatingLiteralClass:
8205 case Stmt::IntegerLiteralClass:
8206 case Stmt::MemberExprClass:
8207 case Stmt::ObjCArrayLiteralClass:
8208 case Stmt::ObjCBoolLiteralExprClass:
8209 case Stmt::ObjCBoxedExprClass:
8210 case Stmt::ObjCDictionaryLiteralClass:
8211 case Stmt::ObjCEncodeExprClass:
8212 case Stmt::ObjCIvarRefExprClass:
8213 case Stmt::ObjCMessageExprClass:
8214 case Stmt::ObjCPropertyRefExprClass:
8215 case Stmt::ObjCStringLiteralClass:
8216 case Stmt::ObjCSubscriptRefExprClass:
8217 case Stmt::ParenExprClass:
8218 case Stmt::StringLiteralClass:
8219 case Stmt::UnaryOperatorClass:
8220 return false;
8221 default:
8222 return true;
8223 }
8224}
8225
8226static std::pair<QualType, StringRef>
8228 QualType IntendedTy,
8229 const Expr *E) {
8230 // Use a 'while' to peel off layers of typedefs.
8231 QualType TyTy = IntendedTy;
8232 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8233 StringRef Name = UserTy->getDecl()->getName();
8234 QualType CastTy = llvm::StringSwitch<QualType>(Name)
8235 .Case("CFIndex", Context.getNSIntegerType())
8236 .Case("NSInteger", Context.getNSIntegerType())
8237 .Case("NSUInteger", Context.getNSUIntegerType())
8238 .Case("SInt32", Context.IntTy)
8239 .Case("UInt32", Context.UnsignedIntTy)
8240 .Default(QualType());
8241
8242 if (!CastTy.isNull())
8243 return std::make_pair(CastTy, Name);
8244
8245 TyTy = UserTy->desugar();
8246 }
8247
8248 // Strip parens if necessary.
8249 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8250 return shouldNotPrintDirectly(Context,
8251 PE->getSubExpr()->getType(),
8252 PE->getSubExpr());
8253
8254 // If this is a conditional expression, then its result type is constructed
8255 // via usual arithmetic conversions and thus there might be no necessary
8256 // typedef sugar there. Recurse to operands to check for NSInteger &
8257 // Co. usage condition.
8258 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8259 QualType TrueTy, FalseTy;
8260 StringRef TrueName, FalseName;
8261
8262 std::tie(TrueTy, TrueName) =
8263 shouldNotPrintDirectly(Context,
8264 CO->getTrueExpr()->getType(),
8265 CO->getTrueExpr());
8266 std::tie(FalseTy, FalseName) =
8267 shouldNotPrintDirectly(Context,
8268 CO->getFalseExpr()->getType(),
8269 CO->getFalseExpr());
8270
8271 if (TrueTy == FalseTy)
8272 return std::make_pair(TrueTy, TrueName);
8273 else if (TrueTy.isNull())
8274 return std::make_pair(FalseTy, FalseName);
8275 else if (FalseTy.isNull())
8276 return std::make_pair(TrueTy, TrueName);
8277 }
8278
8279 return std::make_pair(QualType(), StringRef());
8280}
8281
8282/// Return true if \p ICE is an implicit argument promotion of an arithmetic
8283/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8284/// type do not count.
8285static bool
8287 QualType From = ICE->getSubExpr()->getType();
8288 QualType To = ICE->getType();
8289 // It's an integer promotion if the destination type is the promoted
8290 // source type.
8291 if (ICE->getCastKind() == CK_IntegralCast &&
8293 S.Context.getPromotedIntegerType(From) == To)
8294 return true;
8295 // Look through vector types, since we do default argument promotion for
8296 // those in OpenCL.
8297 if (const auto *VecTy = From->getAs<ExtVectorType>())
8298 From = VecTy->getElementType();
8299 if (const auto *VecTy = To->getAs<ExtVectorType>())
8300 To = VecTy->getElementType();
8301 // It's a floating promotion if the source type is a lower rank.
8302 return ICE->getCastKind() == CK_FloatingCast &&
8303 S.Context.getFloatingTypeOrder(From, To) < 0;
8304}
8305
8310 if (Diags.isIgnored(
8311 diag::warn_format_conversion_argument_type_mismatch_signedness,
8312 Loc) ||
8313 Diags.isIgnored(
8314 // Arbitrary -Wformat diagnostic to detect -Wno-format:
8315 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
8317 }
8318 }
8319 return Match;
8320}
8321
8322bool
8323CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8324 const char *StartSpecifier,
8325 unsigned SpecifierLen,
8326 const Expr *E) {
8327 using namespace analyze_format_string;
8328 using namespace analyze_printf;
8329
8330 // Now type check the data expression that matches the
8331 // format specifier.
8332 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8333 if (!AT.isValid())
8334 return true;
8335
8336 QualType ExprTy = E->getType();
8337 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8338 ExprTy = TET->getUnderlyingExpr()->getType();
8339 }
8340
8341 // When using the format attribute in C++, you can receive a function or an
8342 // array that will necessarily decay to a pointer when passed to the final
8343 // format consumer. Apply decay before type comparison.
8344 if (ExprTy->canDecayToPointerType())
8345 ExprTy = S.Context.getDecayedType(ExprTy);
8346
8347 // Diagnose attempts to print a boolean value as a character. Unlike other
8348 // -Wformat diagnostics, this is fine from a type perspective, but it still
8349 // doesn't make sense.
8350 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8352 const CharSourceRange &CSR =
8353 getSpecifierRange(StartSpecifier, SpecifierLen);
8354 SmallString<4> FSString;
8355 llvm::raw_svector_ostream os(FSString);
8356 FS.toString(os);
8357 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8358 << FSString,
8359 E->getExprLoc(), false, CSR);
8360 return true;
8361 }
8362
8363 // Diagnose attempts to use '%P' with ObjC object types, which will result in
8364 // dumping raw class data (like is-a pointer), not actual data.
8365 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::PArg &&
8366 ExprTy->isObjCObjectPointerType()) {
8367 const CharSourceRange &CSR =
8368 getSpecifierRange(StartSpecifier, SpecifierLen);
8369 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
8370 E->getExprLoc(), false, CSR);
8371 return true;
8372 }
8373
8374 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
8375 ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8376 ArgType::MatchKind OrigMatch = Match;
8377
8379 if (Match == ArgType::Match)
8380 return true;
8381
8382 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
8383 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
8384
8385 // Look through argument promotions for our error message's reported type.
8386 // This includes the integral and floating promotions, but excludes array
8387 // and function pointer decay (seeing that an argument intended to be a
8388 // string has type 'char [6]' is probably more confusing than 'char *') and
8389 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8390 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8391 if (isArithmeticArgumentPromotion(S, ICE)) {
8392 E = ICE->getSubExpr();
8393 ExprTy = E->getType();
8394
8395 // Check if we didn't match because of an implicit cast from a 'char'
8396 // or 'short' to an 'int'. This is done because printf is a varargs
8397 // function.
8398 if (ICE->getType() == S.Context.IntTy ||
8399 ICE->getType() == S.Context.UnsignedIntTy) {
8400 // All further checking is done on the subexpression
8401 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
8402 if (OrigMatch == ArgType::NoMatchSignedness &&
8403 ImplicitMatch != ArgType::NoMatchSignedness)
8404 // If the original match was a signedness match this match on the
8405 // implicit cast type also need to be signedness match otherwise we
8406 // might introduce new unexpected warnings from -Wformat-signedness.
8407 return true;
8408 ImplicitMatch = handleFormatSignedness(
8409 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
8410 if (ImplicitMatch == ArgType::Match)
8411 return true;
8412 }
8413 }
8414 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8415 // Special case for 'a', which has type 'int' in C.
8416 // Note, however, that we do /not/ want to treat multibyte constants like
8417 // 'MooV' as characters! This form is deprecated but still exists. In
8418 // addition, don't treat expressions as of type 'char' if one byte length
8419 // modifier is provided.
8420 if (ExprTy == S.Context.IntTy &&
8421 FS.getLengthModifier().getKind() != LengthModifier::AsChar)
8422 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
8423 ExprTy = S.Context.CharTy;
8424 // To improve check results, we consider a character literal in C
8425 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
8426 // more likely a type confusion situation, so we will suggest to
8427 // use '%hhd' instead by discarding the MatchPromotion.
8428 if (Match == ArgType::MatchPromotion)
8429 Match = ArgType::NoMatch;
8430 }
8431 }
8432 if (Match == ArgType::MatchPromotion) {
8433 // WG14 N2562 only clarified promotions in *printf
8434 // For NSLog in ObjC, just preserve -Wformat behavior
8435 if (!S.getLangOpts().ObjC &&
8436 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
8437 ImplicitMatch != ArgType::NoMatchTypeConfusion)
8438 return true;
8439 Match = ArgType::NoMatch;
8440 }
8441 if (ImplicitMatch == ArgType::NoMatchPedantic ||
8442 ImplicitMatch == ArgType::NoMatchTypeConfusion)
8443 Match = ImplicitMatch;
8444 assert(Match != ArgType::MatchPromotion);
8445
8446 // Look through unscoped enums to their underlying type.
8447 bool IsEnum = false;
8448 bool IsScopedEnum = false;
8449 QualType IntendedTy = ExprTy;
8450 if (const auto *ED = ExprTy->getAsEnumDecl()) {
8451 IntendedTy = ED->getIntegerType();
8452 if (!ED->isScoped()) {
8453 ExprTy = IntendedTy;
8454 // This controls whether we're talking about the underlying type or not,
8455 // which we only want to do when it's an unscoped enum.
8456 IsEnum = true;
8457 } else {
8458 IsScopedEnum = true;
8459 }
8460 }
8461
8462 // %C in an Objective-C context prints a unichar, not a wchar_t.
8463 // If the argument is an integer of some kind, believe the %C and suggest
8464 // a cast instead of changing the conversion specifier.
8465 if (isObjCContext() &&
8466 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8468 !ExprTy->isCharType()) {
8469 // 'unichar' is defined as a typedef of unsigned short, but we should
8470 // prefer using the typedef if it is visible.
8471 IntendedTy = S.Context.UnsignedShortTy;
8472
8473 // While we are here, check if the value is an IntegerLiteral that happens
8474 // to be within the valid range.
8475 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8476 const llvm::APInt &V = IL->getValue();
8477 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8478 return true;
8479 }
8480
8481 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8483 if (S.LookupName(Result, S.getCurScope())) {
8484 NamedDecl *ND = Result.getFoundDecl();
8485 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8486 if (TD->getUnderlyingType() == IntendedTy)
8487 IntendedTy =
8489 /*Qualifier=*/std::nullopt, TD);
8490 }
8491 }
8492 }
8493
8494 // Special-case some of Darwin's platform-independence types by suggesting
8495 // casts to primitive types that are known to be large enough.
8496 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8497 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8498 QualType CastTy;
8499 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8500 if (!CastTy.isNull()) {
8501 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8502 // (long in ASTContext). Only complain to pedants or when they're the
8503 // underlying type of a scoped enum (which always needs a cast).
8504 if (!IsScopedEnum &&
8505 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8506 (AT.isSizeT() || AT.isPtrdiffT()) &&
8507 AT.matchesType(S.Context, CastTy))
8508 Match = ArgType::NoMatchPedantic;
8509 IntendedTy = CastTy;
8510 ShouldNotPrintDirectly = true;
8511 }
8512 }
8513
8514 // We may be able to offer a FixItHint if it is a supported type.
8515 PrintfSpecifier fixedFS = FS;
8516 bool Success =
8517 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8518
8519 if (Success) {
8520 // Get the fix string from the fixed format specifier
8521 SmallString<16> buf;
8522 llvm::raw_svector_ostream os(buf);
8523 fixedFS.toString(os);
8524
8525 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8526
8527 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
8528 unsigned Diag;
8529 switch (Match) {
8530 case ArgType::Match:
8531 case ArgType::MatchPromotion:
8532 case ArgType::NoMatchPromotionTypeConfusion:
8533 llvm_unreachable("expected non-matching");
8534 case ArgType::NoMatchSignedness:
8535 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
8536 break;
8537 case ArgType::NoMatchPedantic:
8538 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8539 break;
8540 case ArgType::NoMatchTypeConfusion:
8541 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8542 break;
8543 case ArgType::NoMatch:
8544 Diag = diag::warn_format_conversion_argument_type_mismatch;
8545 break;
8546 }
8547
8548 // In this case, the specifier is wrong and should be changed to match
8549 // the argument.
8550 EmitFormatDiagnostic(S.PDiag(Diag)
8552 << IntendedTy << IsEnum << E->getSourceRange(),
8553 E->getBeginLoc(),
8554 /*IsStringLocation*/ false, SpecRange,
8555 FixItHint::CreateReplacement(SpecRange, os.str()));
8556 } else {
8557 // The canonical type for formatting this value is different from the
8558 // actual type of the expression. (This occurs, for example, with Darwin's
8559 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8560 // should be printed as 'long' for 64-bit compatibility.)
8561 // Rather than emitting a normal format/argument mismatch, we want to
8562 // add a cast to the recommended type (and correct the format string
8563 // if necessary). We should also do so for scoped enumerations.
8564 SmallString<16> CastBuf;
8565 llvm::raw_svector_ostream CastFix(CastBuf);
8566 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
8567 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8568 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
8569
8571 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
8572 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
8573 E->getExprLoc());
8574 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
8575 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8576
8577 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8578 // If there's already a cast present, just replace it.
8579 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8580 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8581
8582 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
8583 // If the expression has high enough precedence,
8584 // just write the C-style cast.
8585 Hints.push_back(
8586 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8587 } else {
8588 // Otherwise, add parens around the expression as well as the cast.
8589 CastFix << "(";
8590 Hints.push_back(
8591 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8592
8593 // We don't use getLocForEndOfToken because it returns invalid source
8594 // locations for macro expansions (by design).
8598 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8599 }
8600
8601 if (ShouldNotPrintDirectly && !IsScopedEnum) {
8602 // The expression has a type that should not be printed directly.
8603 // We extract the name from the typedef because we don't want to show
8604 // the underlying type in the diagnostic.
8605 StringRef Name;
8606 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
8607 Name = TypedefTy->getDecl()->getName();
8608 else
8609 Name = CastTyName;
8610 unsigned Diag = Match == ArgType::NoMatchPedantic
8611 ? diag::warn_format_argument_needs_cast_pedantic
8612 : diag::warn_format_argument_needs_cast;
8613 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8614 << E->getSourceRange(),
8615 E->getBeginLoc(), /*IsStringLocation=*/false,
8616 SpecRange, Hints);
8617 } else {
8618 // In this case, the expression could be printed using a different
8619 // specifier, but we've decided that the specifier is probably correct
8620 // and we should cast instead. Just use the normal warning message.
8621
8622 unsigned Diag =
8623 IsScopedEnum
8624 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8625 : diag::warn_format_conversion_argument_type_mismatch;
8626
8627 EmitFormatDiagnostic(
8628 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8629 << IsEnum << E->getSourceRange(),
8630 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8631 }
8632 }
8633 } else {
8634 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8635 SpecifierLen);
8636 // Since the warning for passing non-POD types to variadic functions
8637 // was deferred until now, we emit a warning for non-POD
8638 // arguments here.
8639 bool EmitTypeMismatch = false;
8640 switch (S.isValidVarArgType(ExprTy)) {
8641 case VarArgKind::Valid:
8643 unsigned Diag;
8644 switch (Match) {
8645 case ArgType::Match:
8646 case ArgType::MatchPromotion:
8647 case ArgType::NoMatchPromotionTypeConfusion:
8648 case ArgType::NoMatchSignedness:
8649 llvm_unreachable("expected non-matching");
8650 case ArgType::NoMatchPedantic:
8651 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8652 break;
8653 case ArgType::NoMatchTypeConfusion:
8654 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8655 break;
8656 case ArgType::NoMatch:
8657 Diag = diag::warn_format_conversion_argument_type_mismatch;
8658 break;
8659 }
8660
8661 EmitFormatDiagnostic(
8662 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8663 << IsEnum << CSR << E->getSourceRange(),
8664 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8665 break;
8666 }
8669 if (CallType == VariadicCallType::DoesNotApply) {
8670 EmitTypeMismatch = true;
8671 } else {
8672 EmitFormatDiagnostic(
8673 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8674 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8675 << AT.getRepresentativeTypeName(S.Context) << CSR
8676 << E->getSourceRange(),
8677 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8678 checkForCStrMembers(AT, E);
8679 }
8680 break;
8681
8683 if (CallType == VariadicCallType::DoesNotApply)
8684 EmitTypeMismatch = true;
8685 else if (ExprTy->isObjCObjectType())
8686 EmitFormatDiagnostic(
8687 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8688 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8689 << AT.getRepresentativeTypeName(S.Context) << CSR
8690 << E->getSourceRange(),
8691 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8692 else
8693 // FIXME: If this is an initializer list, suggest removing the braces
8694 // or inserting a cast to the target type.
8695 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8696 << isa<InitListExpr>(E) << ExprTy << CallType
8698 break;
8699 }
8700
8701 if (EmitTypeMismatch) {
8702 // The function is not variadic, so we do not generate warnings about
8703 // being allowed to pass that object as a variadic argument. Instead,
8704 // since there are inherently no printf specifiers for types which cannot
8705 // be passed as variadic arguments, emit a plain old specifier mismatch
8706 // argument.
8707 EmitFormatDiagnostic(
8708 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8709 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
8710 << E->getSourceRange(),
8711 E->getBeginLoc(), false, CSR);
8712 }
8713
8714 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8715 "format string specifier index out of range");
8716 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8717 }
8718
8719 return true;
8720}
8721
8722//===--- CHECK: Scanf format string checking ------------------------------===//
8723
8724namespace {
8725
8726class CheckScanfHandler : public CheckFormatHandler {
8727public:
8728 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8729 const Expr *origFormatExpr, FormatStringType type,
8730 unsigned firstDataArg, unsigned numDataArgs,
8731 const char *beg, Sema::FormatArgumentPassingKind APK,
8732 ArrayRef<const Expr *> Args, unsigned formatIdx,
8733 bool inFunctionCall, VariadicCallType CallType,
8734 llvm::SmallBitVector &CheckedVarArgs,
8735 UncoveredArgHandler &UncoveredArg)
8736 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8737 numDataArgs, beg, APK, Args, formatIdx,
8738 inFunctionCall, CallType, CheckedVarArgs,
8739 UncoveredArg) {}
8740
8741 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8742 const char *startSpecifier,
8743 unsigned specifierLen) override;
8744
8745 bool HandleInvalidScanfConversionSpecifier(
8747 const char *startSpecifier,
8748 unsigned specifierLen) override;
8749
8750 void HandleIncompleteScanList(const char *start, const char *end) override;
8751};
8752
8753} // namespace
8754
8755void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8756 const char *end) {
8757 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8758 getLocationOfByte(end), /*IsStringLocation*/true,
8759 getSpecifierRange(start, end - start));
8760}
8761
8762bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8764 const char *startSpecifier,
8765 unsigned specifierLen) {
8767 FS.getConversionSpecifier();
8768
8769 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8770 getLocationOfByte(CS.getStart()),
8771 startSpecifier, specifierLen,
8772 CS.getStart(), CS.getLength());
8773}
8774
8775bool CheckScanfHandler::HandleScanfSpecifier(
8777 const char *startSpecifier,
8778 unsigned specifierLen) {
8779 using namespace analyze_scanf;
8780 using namespace analyze_format_string;
8781
8782 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8783
8784 // Handle case where '%' and '*' don't consume an argument. These shouldn't
8785 // be used to decide if we are using positional arguments consistently.
8786 if (FS.consumesDataArgument()) {
8787 if (atFirstArg) {
8788 atFirstArg = false;
8789 usesPositionalArgs = FS.usesPositionalArg();
8790 }
8791 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8792 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8793 startSpecifier, specifierLen);
8794 return false;
8795 }
8796 }
8797
8798 // Check if the field with is non-zero.
8799 const OptionalAmount &Amt = FS.getFieldWidth();
8800 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8801 if (Amt.getConstantAmount() == 0) {
8802 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8803 Amt.getConstantLength());
8804 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8805 getLocationOfByte(Amt.getStart()),
8806 /*IsStringLocation*/true, R,
8808 }
8809 }
8810
8811 if (!FS.consumesDataArgument()) {
8812 // FIXME: Technically specifying a precision or field width here
8813 // makes no sense. Worth issuing a warning at some point.
8814 return true;
8815 }
8816
8817 // Consume the argument.
8818 unsigned argIndex = FS.getArgIndex();
8819 if (argIndex < NumDataArgs) {
8820 // The check to see if the argIndex is valid will come later.
8821 // We set the bit here because we may exit early from this
8822 // function if we encounter some other error.
8823 CoveredArgs.set(argIndex);
8824 }
8825
8826 // Check the length modifier is valid with the given conversion specifier.
8827 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8828 S.getLangOpts()))
8829 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8830 diag::warn_format_nonsensical_length);
8831 else if (!FS.hasStandardLengthModifier())
8832 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8833 else if (!FS.hasStandardLengthConversionCombination())
8834 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8835 diag::warn_format_non_standard_conversion_spec);
8836
8837 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8838 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8839
8840 // The remaining checks depend on the data arguments.
8841 if (!HasFormatArguments())
8842 return true;
8843
8844 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8845 return false;
8846
8847 // Check that the argument type matches the format specifier.
8848 const Expr *Ex = getDataArg(argIndex);
8849 if (!Ex)
8850 return true;
8851
8852 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8853
8854 if (!AT.isValid()) {
8855 return true;
8856 }
8857
8859 AT.matchesType(S.Context, Ex->getType());
8862 return true;
8865
8866 ScanfSpecifier fixedFS = FS;
8867 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8868 S.getLangOpts(), S.Context);
8869
8870 unsigned Diag =
8871 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8872 : Signedness
8873 ? diag::warn_format_conversion_argument_type_mismatch_signedness
8874 : diag::warn_format_conversion_argument_type_mismatch;
8875
8876 if (Success) {
8877 // Get the fix string from the fixed format specifier.
8878 SmallString<128> buf;
8879 llvm::raw_svector_ostream os(buf);
8880 fixedFS.toString(os);
8881
8882 EmitFormatDiagnostic(
8884 << Ex->getType() << false << Ex->getSourceRange(),
8885 Ex->getBeginLoc(),
8886 /*IsStringLocation*/ false,
8887 getSpecifierRange(startSpecifier, specifierLen),
8889 getSpecifierRange(startSpecifier, specifierLen), os.str()));
8890 } else {
8891 EmitFormatDiagnostic(S.PDiag(Diag)
8893 << Ex->getType() << false << Ex->getSourceRange(),
8894 Ex->getBeginLoc(),
8895 /*IsStringLocation*/ false,
8896 getSpecifierRange(startSpecifier, specifierLen));
8897 }
8898
8899 return true;
8900}
8901
8902static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
8904 const StringLiteral *Fmt,
8906 const Expr *FmtExpr, bool InFunctionCall) {
8907 bool HadError = false;
8908 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
8909 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
8910 while (FmtIter < FmtEnd && RefIter < RefEnd) {
8911 // In positional-style format strings, the same specifier can appear
8912 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
8913 // are sorted by getPosition(), and we process each range of equal
8914 // getPosition() values as one group.
8915 // RefArgs are taken from a string literal that was given to
8916 // attribute(format_matches), and if we got this far, we have already
8917 // verified that if it has positional specifiers that appear in multiple
8918 // locations, then they are all mutually compatible. What's left for us to
8919 // do is verify that all specifiers with the same position in FmtArgs are
8920 // compatible with the RefArgs specifiers. We check each specifier from
8921 // FmtArgs against the first member of the RefArgs group.
8922 for (; FmtIter < FmtEnd; ++FmtIter) {
8923 // Clang does not diagnose missing format specifiers in positional-style
8924 // strings (TODO: which it probably should do, as it is UB to skip over a
8925 // format argument). Skip specifiers if needed.
8926 if (FmtIter->getPosition() < RefIter->getPosition())
8927 continue;
8928
8929 // Delimits a new getPosition() value.
8930 if (FmtIter->getPosition() > RefIter->getPosition())
8931 break;
8932
8933 HadError |=
8934 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
8935 }
8936
8937 // Jump RefIter to the start of the next group.
8938 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
8939 return Arg.getPosition() != RefIter->getPosition();
8940 });
8941 }
8942
8943 if (FmtIter < FmtEnd) {
8944 CheckFormatHandler::EmitFormatDiagnostic(
8945 S, InFunctionCall, FmtExpr,
8946 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
8947 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
8948 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
8949 } else if (RefIter < RefEnd) {
8950 CheckFormatHandler::EmitFormatDiagnostic(
8951 S, InFunctionCall, FmtExpr,
8952 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
8953 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
8954 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
8955 << 1 << RefIter->getSourceRange();
8956 }
8957 return !HadError;
8958}
8959
8961 Sema &S, const FormatStringLiteral *FExpr,
8962 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
8964 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
8965 bool inFunctionCall, VariadicCallType CallType,
8966 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
8967 bool IgnoreStringsWithoutSpecifiers) {
8968 // CHECK: is the format string a wide literal?
8969 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8970 CheckFormatHandler::EmitFormatDiagnostic(
8971 S, inFunctionCall, Args[format_idx],
8972 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8973 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8974 return;
8975 }
8976
8977 // Str - The format string. NOTE: this is NOT null-terminated!
8978 StringRef StrRef = FExpr->getString();
8979 const char *Str = StrRef.data();
8980 // Account for cases where the string literal is truncated in a declaration.
8981 const ConstantArrayType *T =
8982 S.Context.getAsConstantArrayType(FExpr->getType());
8983 assert(T && "String literal not of constant array type!");
8984 size_t TypeSize = T->getZExtSize();
8985 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8986 const unsigned numDataArgs = Args.size() - firstDataArg;
8987
8988 if (IgnoreStringsWithoutSpecifiers &&
8990 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8991 return;
8992
8993 // Emit a warning if the string literal is truncated and does not contain an
8994 // embedded null character.
8995 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
8996 CheckFormatHandler::EmitFormatDiagnostic(
8997 S, inFunctionCall, Args[format_idx],
8998 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8999 FExpr->getBeginLoc(),
9000 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9001 return;
9002 }
9003
9004 // CHECK: empty format string?
9005 if (StrLen == 0 && numDataArgs > 0) {
9006 CheckFormatHandler::EmitFormatDiagnostic(
9007 S, inFunctionCall, Args[format_idx],
9008 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9009 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9010 return;
9011 }
9012
9018 bool IsObjC =
9020 if (ReferenceFormatString == nullptr) {
9021 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9022 numDataArgs, IsObjC, Str, APK, Args, format_idx,
9023 inFunctionCall, CallType, CheckedVarArgs,
9024 UncoveredArg);
9025
9027 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
9030 H.DoneProcessing();
9031 } else {
9033 Type, ReferenceFormatString, FExpr->getFormatString(),
9034 inFunctionCall ? nullptr : Args[format_idx]);
9035 }
9036 } else if (Type == FormatStringType::Scanf) {
9037 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9038 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
9039 CallType, CheckedVarArgs, UncoveredArg);
9040
9042 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9043 H.DoneProcessing();
9044 } // TODO: handle other formats
9045}
9046
9048 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
9049 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
9055 return true;
9056
9057 bool IsObjC =
9060 FormatStringLiteral RefLit = AuthoritativeFormatString;
9061 FormatStringLiteral TestLit = TestedFormatString;
9062 const Expr *Arg;
9063 bool DiagAtStringLiteral;
9064 if (FunctionCallArg) {
9065 Arg = FunctionCallArg;
9066 DiagAtStringLiteral = false;
9067 } else {
9068 Arg = TestedFormatString;
9069 DiagAtStringLiteral = true;
9070 }
9071 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
9072 AuthoritativeFormatString, Type,
9073 IsObjC, true, RefArgs) &&
9074 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
9075 DiagAtStringLiteral, FmtArgs)) {
9076 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
9077 TestedFormatString, FmtArgs, Arg,
9078 DiagAtStringLiteral);
9079 }
9080 return false;
9081}
9082
9084 const StringLiteral *Str) {
9090 return true;
9091
9092 FormatStringLiteral RefLit = Str;
9094 bool IsObjC =
9096 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
9097 true, Args))
9098 return false;
9099
9100 // Group arguments by getPosition() value, and check that each member of the
9101 // group is compatible with the first member. This verifies that when
9102 // positional arguments are used multiple times (such as %2$i %2$d), all uses
9103 // are mutually compatible. As an optimization, don't test the first member
9104 // against itself.
9105 bool HadError = false;
9106 auto Iter = Args.begin();
9107 auto End = Args.end();
9108 while (Iter != End) {
9109 const auto &FirstInGroup = *Iter;
9110 for (++Iter;
9111 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
9112 ++Iter) {
9113 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
9114 }
9115 }
9116 return !HadError;
9117}
9118
9120 // Str - The format string. NOTE: this is NOT null-terminated!
9121 StringRef StrRef = FExpr->getString();
9122 const char *Str = StrRef.data();
9123 // Account for cases where the string literal is truncated in a declaration.
9125 assert(T && "String literal not of constant array type!");
9126 size_t TypeSize = T->getZExtSize();
9127 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9128 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9129 getLangOpts(),
9131}
9132
9133//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9134
9135// Returns the related absolute value function that is larger, of 0 if one
9136// does not exist.
9137static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9138 switch (AbsFunction) {
9139 default:
9140 return 0;
9141
9142 case Builtin::BI__builtin_abs:
9143 return Builtin::BI__builtin_labs;
9144 case Builtin::BI__builtin_labs:
9145 return Builtin::BI__builtin_llabs;
9146 case Builtin::BI__builtin_llabs:
9147 return 0;
9148
9149 case Builtin::BI__builtin_fabsf:
9150 return Builtin::BI__builtin_fabs;
9151 case Builtin::BI__builtin_fabs:
9152 return Builtin::BI__builtin_fabsl;
9153 case Builtin::BI__builtin_fabsl:
9154 return 0;
9155
9156 case Builtin::BI__builtin_cabsf:
9157 return Builtin::BI__builtin_cabs;
9158 case Builtin::BI__builtin_cabs:
9159 return Builtin::BI__builtin_cabsl;
9160 case Builtin::BI__builtin_cabsl:
9161 return 0;
9162
9163 case Builtin::BIabs:
9164 return Builtin::BIlabs;
9165 case Builtin::BIlabs:
9166 return Builtin::BIllabs;
9167 case Builtin::BIllabs:
9168 return 0;
9169
9170 case Builtin::BIfabsf:
9171 return Builtin::BIfabs;
9172 case Builtin::BIfabs:
9173 return Builtin::BIfabsl;
9174 case Builtin::BIfabsl:
9175 return 0;
9176
9177 case Builtin::BIcabsf:
9178 return Builtin::BIcabs;
9179 case Builtin::BIcabs:
9180 return Builtin::BIcabsl;
9181 case Builtin::BIcabsl:
9182 return 0;
9183 }
9184}
9185
9186// Returns the argument type of the absolute value function.
9188 unsigned AbsType) {
9189 if (AbsType == 0)
9190 return QualType();
9191
9193 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9194 if (Error != ASTContext::GE_None)
9195 return QualType();
9196
9198 if (!FT)
9199 return QualType();
9200
9201 if (FT->getNumParams() != 1)
9202 return QualType();
9203
9204 return FT->getParamType(0);
9205}
9206
9207// Returns the best absolute value function, or zero, based on type and
9208// current absolute value function.
9209static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9210 unsigned AbsFunctionKind) {
9211 unsigned BestKind = 0;
9212 uint64_t ArgSize = Context.getTypeSize(ArgType);
9213 for (unsigned Kind = AbsFunctionKind; Kind != 0;
9214 Kind = getLargerAbsoluteValueFunction(Kind)) {
9215 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9216 if (Context.getTypeSize(ParamType) >= ArgSize) {
9217 if (BestKind == 0)
9218 BestKind = Kind;
9219 else if (Context.hasSameType(ParamType, ArgType)) {
9220 BestKind = Kind;
9221 break;
9222 }
9223 }
9224 }
9225 return BestKind;
9226}
9227
9233
9236 return AVK_Integer;
9237 if (T->isRealFloatingType())
9238 return AVK_Floating;
9239 if (T->isAnyComplexType())
9240 return AVK_Complex;
9241
9242 llvm_unreachable("Type not integer, floating, or complex");
9243}
9244
9245// Changes the absolute value function to a different type. Preserves whether
9246// the function is a builtin.
9247static unsigned changeAbsFunction(unsigned AbsKind,
9248 AbsoluteValueKind ValueKind) {
9249 switch (ValueKind) {
9250 case AVK_Integer:
9251 switch (AbsKind) {
9252 default:
9253 return 0;
9254 case Builtin::BI__builtin_fabsf:
9255 case Builtin::BI__builtin_fabs:
9256 case Builtin::BI__builtin_fabsl:
9257 case Builtin::BI__builtin_cabsf:
9258 case Builtin::BI__builtin_cabs:
9259 case Builtin::BI__builtin_cabsl:
9260 return Builtin::BI__builtin_abs;
9261 case Builtin::BIfabsf:
9262 case Builtin::BIfabs:
9263 case Builtin::BIfabsl:
9264 case Builtin::BIcabsf:
9265 case Builtin::BIcabs:
9266 case Builtin::BIcabsl:
9267 return Builtin::BIabs;
9268 }
9269 case AVK_Floating:
9270 switch (AbsKind) {
9271 default:
9272 return 0;
9273 case Builtin::BI__builtin_abs:
9274 case Builtin::BI__builtin_labs:
9275 case Builtin::BI__builtin_llabs:
9276 case Builtin::BI__builtin_cabsf:
9277 case Builtin::BI__builtin_cabs:
9278 case Builtin::BI__builtin_cabsl:
9279 return Builtin::BI__builtin_fabsf;
9280 case Builtin::BIabs:
9281 case Builtin::BIlabs:
9282 case Builtin::BIllabs:
9283 case Builtin::BIcabsf:
9284 case Builtin::BIcabs:
9285 case Builtin::BIcabsl:
9286 return Builtin::BIfabsf;
9287 }
9288 case AVK_Complex:
9289 switch (AbsKind) {
9290 default:
9291 return 0;
9292 case Builtin::BI__builtin_abs:
9293 case Builtin::BI__builtin_labs:
9294 case Builtin::BI__builtin_llabs:
9295 case Builtin::BI__builtin_fabsf:
9296 case Builtin::BI__builtin_fabs:
9297 case Builtin::BI__builtin_fabsl:
9298 return Builtin::BI__builtin_cabsf;
9299 case Builtin::BIabs:
9300 case Builtin::BIlabs:
9301 case Builtin::BIllabs:
9302 case Builtin::BIfabsf:
9303 case Builtin::BIfabs:
9304 case Builtin::BIfabsl:
9305 return Builtin::BIcabsf;
9306 }
9307 }
9308 llvm_unreachable("Unable to convert function");
9309}
9310
9311static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9312 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9313 if (!FnInfo)
9314 return 0;
9315
9316 switch (FDecl->getBuiltinID()) {
9317 default:
9318 return 0;
9319 case Builtin::BI__builtin_abs:
9320 case Builtin::BI__builtin_fabs:
9321 case Builtin::BI__builtin_fabsf:
9322 case Builtin::BI__builtin_fabsl:
9323 case Builtin::BI__builtin_labs:
9324 case Builtin::BI__builtin_llabs:
9325 case Builtin::BI__builtin_cabs:
9326 case Builtin::BI__builtin_cabsf:
9327 case Builtin::BI__builtin_cabsl:
9328 case Builtin::BIabs:
9329 case Builtin::BIlabs:
9330 case Builtin::BIllabs:
9331 case Builtin::BIfabs:
9332 case Builtin::BIfabsf:
9333 case Builtin::BIfabsl:
9334 case Builtin::BIcabs:
9335 case Builtin::BIcabsf:
9336 case Builtin::BIcabsl:
9337 return FDecl->getBuiltinID();
9338 }
9339 llvm_unreachable("Unknown Builtin type");
9340}
9341
9342// If the replacement is valid, emit a note with replacement function.
9343// Additionally, suggest including the proper header if not already included.
9345 unsigned AbsKind, QualType ArgType) {
9346 bool EmitHeaderHint = true;
9347 const char *HeaderName = nullptr;
9348 std::string FunctionName;
9349 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9350 FunctionName = "std::abs";
9351 if (ArgType->isIntegralOrEnumerationType()) {
9352 HeaderName = "cstdlib";
9353 } else if (ArgType->isRealFloatingType()) {
9354 HeaderName = "cmath";
9355 } else {
9356 llvm_unreachable("Invalid Type");
9357 }
9358
9359 // Lookup all std::abs
9360 if (NamespaceDecl *Std = S.getStdNamespace()) {
9364
9365 for (const auto *I : R) {
9366 const FunctionDecl *FDecl = nullptr;
9367 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9368 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9369 } else {
9370 FDecl = dyn_cast<FunctionDecl>(I);
9371 }
9372 if (!FDecl)
9373 continue;
9374
9375 // Found std::abs(), check that they are the right ones.
9376 if (FDecl->getNumParams() != 1)
9377 continue;
9378
9379 // Check that the parameter type can handle the argument.
9380 QualType ParamType = FDecl->getParamDecl(0)->getType();
9381 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9382 S.Context.getTypeSize(ArgType) <=
9383 S.Context.getTypeSize(ParamType)) {
9384 // Found a function, don't need the header hint.
9385 EmitHeaderHint = false;
9386 break;
9387 }
9388 }
9389 }
9390 } else {
9391 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9392 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9393
9394 if (HeaderName) {
9395 DeclarationName DN(&S.Context.Idents.get(FunctionName));
9398 S.LookupName(R, S.getCurScope());
9399
9400 if (R.isSingleResult()) {
9401 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9402 if (FD && FD->getBuiltinID() == AbsKind) {
9403 EmitHeaderHint = false;
9404 } else {
9405 return;
9406 }
9407 } else if (!R.empty()) {
9408 return;
9409 }
9410 }
9411 }
9412
9413 S.Diag(Loc, diag::note_replace_abs_function)
9414 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9415
9416 if (!HeaderName)
9417 return;
9418
9419 if (!EmitHeaderHint)
9420 return;
9421
9422 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9423 << FunctionName;
9424}
9425
9426template <std::size_t StrLen>
9427static bool IsStdFunction(const FunctionDecl *FDecl,
9428 const char (&Str)[StrLen]) {
9429 if (!FDecl)
9430 return false;
9431 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9432 return false;
9433 if (!FDecl->isInStdNamespace())
9434 return false;
9435
9436 return true;
9437}
9438
9439enum class MathCheck { NaN, Inf };
9440static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
9441 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
9442 return llvm::is_contained(names, calleeName);
9443 };
9444
9445 switch (Check) {
9446 case MathCheck::NaN:
9447 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
9448 "__builtin_nanf16", "__builtin_nanf128"});
9449 case MathCheck::Inf:
9450 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
9451 "__builtin_inff16", "__builtin_inff128"});
9452 }
9453 llvm_unreachable("unknown MathCheck");
9454}
9455
9456static bool IsInfinityFunction(const FunctionDecl *FDecl) {
9457 if (FDecl->getName() != "infinity")
9458 return false;
9459
9460 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
9461 const CXXRecordDecl *RDecl = MDecl->getParent();
9462 if (RDecl->getName() != "numeric_limits")
9463 return false;
9464
9465 if (const NamespaceDecl *NSDecl =
9466 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
9467 return NSDecl->isStdNamespace();
9468 }
9469
9470 return false;
9471}
9472
9473void Sema::CheckInfNaNFunction(const CallExpr *Call,
9474 const FunctionDecl *FDecl) {
9475 if (!FDecl->getIdentifier())
9476 return;
9477
9478 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
9479 if (FPO.getNoHonorNaNs() &&
9480 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
9481 IsInfOrNanFunction(FDecl->getName(), MathCheck::NaN))) {
9482 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9483 << 1 << 0 << Call->getSourceRange();
9484 return;
9485 }
9486
9487 if (FPO.getNoHonorInfs() &&
9488 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
9489 IsInfinityFunction(FDecl) ||
9490 IsInfOrNanFunction(FDecl->getName(), MathCheck::Inf))) {
9491 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9492 << 0 << 0 << Call->getSourceRange();
9493 }
9494}
9495
9496void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9497 const FunctionDecl *FDecl) {
9498 if (Call->getNumArgs() != 1)
9499 return;
9500
9501 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9502 bool IsStdAbs = IsStdFunction(FDecl, "abs");
9503 if (AbsKind == 0 && !IsStdAbs)
9504 return;
9505
9506 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9507 QualType ParamType = Call->getArg(0)->getType();
9508
9509 // Unsigned types cannot be negative. Suggest removing the absolute value
9510 // function call.
9511 if (ArgType->isUnsignedIntegerType()) {
9512 std::string FunctionName =
9513 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9514 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9515 Diag(Call->getExprLoc(), diag::note_remove_abs)
9516 << FunctionName
9517 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9518 return;
9519 }
9520
9521 // Taking the absolute value of a pointer is very suspicious, they probably
9522 // wanted to index into an array, dereference a pointer, call a function, etc.
9523 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9524 unsigned DiagType = 0;
9525 if (ArgType->isFunctionType())
9526 DiagType = 1;
9527 else if (ArgType->isArrayType())
9528 DiagType = 2;
9529
9530 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9531 return;
9532 }
9533
9534 // std::abs has overloads which prevent most of the absolute value problems
9535 // from occurring.
9536 if (IsStdAbs)
9537 return;
9538
9539 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9540 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9541
9542 // The argument and parameter are the same kind. Check if they are the right
9543 // size.
9544 if (ArgValueKind == ParamValueKind) {
9545 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9546 return;
9547
9548 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9549 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9550 << FDecl << ArgType << ParamType;
9551
9552 if (NewAbsKind == 0)
9553 return;
9554
9555 emitReplacement(*this, Call->getExprLoc(),
9556 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9557 return;
9558 }
9559
9560 // ArgValueKind != ParamValueKind
9561 // The wrong type of absolute value function was used. Attempt to find the
9562 // proper one.
9563 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9564 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9565 if (NewAbsKind == 0)
9566 return;
9567
9568 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9569 << FDecl << ParamValueKind << ArgValueKind;
9570
9571 emitReplacement(*this, Call->getExprLoc(),
9572 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9573}
9574
9575//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9576void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9577 const FunctionDecl *FDecl) {
9578 if (!Call || !FDecl) return;
9579
9580 // Ignore template specializations and macros.
9581 if (inTemplateInstantiation()) return;
9582 if (Call->getExprLoc().isMacroID()) return;
9583
9584 // Only care about the one template argument, two function parameter std::max
9585 if (Call->getNumArgs() != 2) return;
9586 if (!IsStdFunction(FDecl, "max")) return;
9587 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9588 if (!ArgList) return;
9589 if (ArgList->size() != 1) return;
9590
9591 // Check that template type argument is unsigned integer.
9592 const auto& TA = ArgList->get(0);
9593 if (TA.getKind() != TemplateArgument::Type) return;
9594 QualType ArgType = TA.getAsType();
9595 if (!ArgType->isUnsignedIntegerType()) return;
9596
9597 // See if either argument is a literal zero.
9598 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9599 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9600 if (!MTE) return false;
9601 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9602 if (!Num) return false;
9603 if (Num->getValue() != 0) return false;
9604 return true;
9605 };
9606
9607 const Expr *FirstArg = Call->getArg(0);
9608 const Expr *SecondArg = Call->getArg(1);
9609 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9610 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9611
9612 // Only warn when exactly one argument is zero.
9613 if (IsFirstArgZero == IsSecondArgZero) return;
9614
9615 SourceRange FirstRange = FirstArg->getSourceRange();
9616 SourceRange SecondRange = SecondArg->getSourceRange();
9617
9618 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9619
9620 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9621 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9622
9623 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9624 SourceRange RemovalRange;
9625 if (IsFirstArgZero) {
9626 RemovalRange = SourceRange(FirstRange.getBegin(),
9627 SecondRange.getBegin().getLocWithOffset(-1));
9628 } else {
9629 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9630 SecondRange.getEnd());
9631 }
9632
9633 Diag(Call->getExprLoc(), diag::note_remove_max_call)
9634 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9635 << FixItHint::CreateRemoval(RemovalRange);
9636}
9637
9638//===--- CHECK: Standard memory functions ---------------------------------===//
9639
9640/// Takes the expression passed to the size_t parameter of functions
9641/// such as memcmp, strncat, etc and warns if it's a comparison.
9642///
9643/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9645 const IdentifierInfo *FnName,
9646 SourceLocation FnLoc,
9647 SourceLocation RParenLoc) {
9648 const auto *Size = dyn_cast<BinaryOperator>(E);
9649 if (!Size)
9650 return false;
9651
9652 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9653 if (!Size->isComparisonOp() && !Size->isLogicalOp())
9654 return false;
9655
9656 SourceRange SizeRange = Size->getSourceRange();
9657 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9658 << SizeRange << FnName;
9659 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9660 << FnName
9662 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9663 << FixItHint::CreateRemoval(RParenLoc);
9664 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9665 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9667 ")");
9668
9669 return true;
9670}
9671
9672/// Determine whether the given type is or contains a dynamic class type
9673/// (e.g., whether it has a vtable).
9675 bool &IsContained) {
9676 // Look through array types while ignoring qualifiers.
9677 const Type *Ty = T->getBaseElementTypeUnsafe();
9678 IsContained = false;
9679
9680 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9681 RD = RD ? RD->getDefinition() : nullptr;
9682 if (!RD || RD->isInvalidDecl())
9683 return nullptr;
9684
9685 if (RD->isDynamicClass())
9686 return RD;
9687
9688 // Check all the fields. If any bases were dynamic, the class is dynamic.
9689 // It's impossible for a class to transitively contain itself by value, so
9690 // infinite recursion is impossible.
9691 for (auto *FD : RD->fields()) {
9692 bool SubContained;
9693 if (const CXXRecordDecl *ContainedRD =
9694 getContainedDynamicClass(FD->getType(), SubContained)) {
9695 IsContained = true;
9696 return ContainedRD;
9697 }
9698 }
9699
9700 return nullptr;
9701}
9702
9704 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9705 if (Unary->getKind() == UETT_SizeOf)
9706 return Unary;
9707 return nullptr;
9708}
9709
9710/// If E is a sizeof expression, returns its argument expression,
9711/// otherwise returns NULL.
9712static const Expr *getSizeOfExprArg(const Expr *E) {
9714 if (!SizeOf->isArgumentType())
9715 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9716 return nullptr;
9717}
9718
9719/// If E is a sizeof expression, returns its argument type.
9722 return SizeOf->getTypeOfArgument();
9723 return QualType();
9724}
9725
9726namespace {
9727
9728struct SearchNonTrivialToInitializeField
9729 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9730 using Super =
9732
9733 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9734
9735 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9736 SourceLocation SL) {
9737 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9738 asDerived().visitArray(PDIK, AT, SL);
9739 return;
9740 }
9741
9742 Super::visitWithKind(PDIK, FT, SL);
9743 }
9744
9745 void visitARCStrong(QualType FT, SourceLocation SL) {
9746 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9747 }
9748 void visitARCWeak(QualType FT, SourceLocation SL) {
9749 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9750 }
9751 void visitStruct(QualType FT, SourceLocation SL) {
9752 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
9753 visit(FD->getType(), FD->getLocation());
9754 }
9755 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9756 const ArrayType *AT, SourceLocation SL) {
9757 visit(getContext().getBaseElementType(AT), SL);
9758 }
9759 void visitTrivial(QualType FT, SourceLocation SL) {}
9760
9761 static void diag(QualType RT, const Expr *E, Sema &S) {
9762 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9763 }
9764
9765 ASTContext &getContext() { return S.getASTContext(); }
9766
9767 const Expr *E;
9768 Sema &S;
9769};
9770
9771struct SearchNonTrivialToCopyField
9772 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9774
9775 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9776
9777 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9778 SourceLocation SL) {
9779 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9780 asDerived().visitArray(PCK, AT, SL);
9781 return;
9782 }
9783
9784 Super::visitWithKind(PCK, FT, SL);
9785 }
9786
9787 void visitARCStrong(QualType FT, SourceLocation SL) {
9788 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9789 }
9790 void visitARCWeak(QualType FT, SourceLocation SL) {
9791 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9792 }
9793 void visitPtrAuth(QualType FT, SourceLocation SL) {
9794 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9795 }
9796 void visitStruct(QualType FT, SourceLocation SL) {
9797 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
9798 visit(FD->getType(), FD->getLocation());
9799 }
9800 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9801 SourceLocation SL) {
9802 visit(getContext().getBaseElementType(AT), SL);
9803 }
9804 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9805 SourceLocation SL) {}
9806 void visitTrivial(QualType FT, SourceLocation SL) {}
9807 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9808
9809 static void diag(QualType RT, const Expr *E, Sema &S) {
9810 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9811 }
9812
9813 ASTContext &getContext() { return S.getASTContext(); }
9814
9815 const Expr *E;
9816 Sema &S;
9817};
9818
9819}
9820
9821/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9822static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9823 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9824
9825 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9826 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9827 return false;
9828
9829 return doesExprLikelyComputeSize(BO->getLHS()) ||
9830 doesExprLikelyComputeSize(BO->getRHS());
9831 }
9832
9833 return getAsSizeOfExpr(SizeofExpr) != nullptr;
9834}
9835
9836/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9837///
9838/// \code
9839/// #define MACRO 0
9840/// foo(MACRO);
9841/// foo(0);
9842/// \endcode
9843///
9844/// This should return true for the first call to foo, but not for the second
9845/// (regardless of whether foo is a macro or function).
9847 SourceLocation CallLoc,
9848 SourceLocation ArgLoc) {
9849 if (!CallLoc.isMacroID())
9850 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9851
9852 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9853 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9854}
9855
9856/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9857/// last two arguments transposed.
9858static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9859 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9860 return;
9861
9862 const Expr *SizeArg =
9863 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9864
9865 auto isLiteralZero = [](const Expr *E) {
9866 return (isa<IntegerLiteral>(E) &&
9867 cast<IntegerLiteral>(E)->getValue() == 0) ||
9868 (isa<CharacterLiteral>(E) &&
9869 cast<CharacterLiteral>(E)->getValue() == 0);
9870 };
9871
9872 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9873 SourceLocation CallLoc = Call->getRParenLoc();
9875 if (isLiteralZero(SizeArg) &&
9876 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9877
9878 SourceLocation DiagLoc = SizeArg->getExprLoc();
9879
9880 // Some platforms #define bzero to __builtin_memset. See if this is the
9881 // case, and if so, emit a better diagnostic.
9882 if (BId == Builtin::BIbzero ||
9884 CallLoc, SM, S.getLangOpts()) == "bzero")) {
9885 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9886 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9887 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9888 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9889 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9890 }
9891 return;
9892 }
9893
9894 // If the second argument to a memset is a sizeof expression and the third
9895 // isn't, this is also likely an error. This should catch
9896 // 'memset(buf, sizeof(buf), 0xff)'.
9897 if (BId == Builtin::BImemset &&
9898 doesExprLikelyComputeSize(Call->getArg(1)) &&
9899 !doesExprLikelyComputeSize(Call->getArg(2))) {
9900 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9901 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9902 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9903 return;
9904 }
9905}
9906
9907void Sema::CheckMemaccessArguments(const CallExpr *Call,
9908 unsigned BId,
9909 IdentifierInfo *FnName) {
9910 assert(BId != 0);
9911
9912 // It is possible to have a non-standard definition of memset. Validate
9913 // we have enough arguments, and if not, abort further checking.
9914 unsigned ExpectedNumArgs =
9915 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9916 if (Call->getNumArgs() < ExpectedNumArgs)
9917 return;
9918
9919 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9920 BId == Builtin::BIstrndup ? 1 : 2);
9921 unsigned LenArg =
9922 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9923 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9924
9925 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9926 Call->getBeginLoc(), Call->getRParenLoc()))
9927 return;
9928
9929 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9930 CheckMemaccessSize(*this, BId, Call);
9931
9932 // We have special checking when the length is a sizeof expression.
9933 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9934 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9935 llvm::FoldingSetNodeID SizeOfArgID;
9936
9937 // Although widely used, 'bzero' is not a standard function. Be more strict
9938 // with the argument types before allowing diagnostics and only allow the
9939 // form bzero(ptr, sizeof(...)).
9940 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9941 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9942 return;
9943
9944 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9945 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9946 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9947
9948 QualType DestTy = Dest->getType();
9949 QualType PointeeTy;
9950 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9951 PointeeTy = DestPtrTy->getPointeeType();
9952
9953 // Never warn about void type pointers. This can be used to suppress
9954 // false positives.
9955 if (PointeeTy->isVoidType())
9956 continue;
9957
9958 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9959 // actually comparing the expressions for equality. Because computing the
9960 // expression IDs can be expensive, we only do this if the diagnostic is
9961 // enabled.
9962 if (SizeOfArg &&
9963 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9964 SizeOfArg->getExprLoc())) {
9965 // We only compute IDs for expressions if the warning is enabled, and
9966 // cache the sizeof arg's ID.
9967 if (SizeOfArgID == llvm::FoldingSetNodeID())
9968 SizeOfArg->Profile(SizeOfArgID, Context, true);
9969 llvm::FoldingSetNodeID DestID;
9970 Dest->Profile(DestID, Context, true);
9971 if (DestID == SizeOfArgID) {
9972 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9973 // over sizeof(src) as well.
9974 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9975 StringRef ReadableName = FnName->getName();
9976
9977 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9978 if (UnaryOp->getOpcode() == UO_AddrOf)
9979 ActionIdx = 1; // If its an address-of operator, just remove it.
9980 if (!PointeeTy->isIncompleteType() &&
9981 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9982 ActionIdx = 2; // If the pointee's size is sizeof(char),
9983 // suggest an explicit length.
9984
9985 // If the function is defined as a builtin macro, do not show macro
9986 // expansion.
9987 SourceLocation SL = SizeOfArg->getExprLoc();
9988 SourceRange DSR = Dest->getSourceRange();
9989 SourceRange SSR = SizeOfArg->getSourceRange();
9991
9992 if (SM.isMacroArgExpansion(SL)) {
9993 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9994 SL = SM.getSpellingLoc(SL);
9995 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9996 SM.getSpellingLoc(DSR.getEnd()));
9997 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9998 SM.getSpellingLoc(SSR.getEnd()));
9999 }
10000
10001 DiagRuntimeBehavior(SL, SizeOfArg,
10002 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10003 << ReadableName
10004 << PointeeTy
10005 << DestTy
10006 << DSR
10007 << SSR);
10008 DiagRuntimeBehavior(SL, SizeOfArg,
10009 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10010 << ActionIdx
10011 << SSR);
10012
10013 break;
10014 }
10015 }
10016
10017 // Also check for cases where the sizeof argument is the exact same
10018 // type as the memory argument, and where it points to a user-defined
10019 // record type.
10020 if (SizeOfArgTy != QualType()) {
10021 if (PointeeTy->isRecordType() &&
10022 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10023 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10024 PDiag(diag::warn_sizeof_pointer_type_memaccess)
10025 << FnName << SizeOfArgTy << ArgIdx
10026 << PointeeTy << Dest->getSourceRange()
10027 << LenExpr->getSourceRange());
10028 break;
10029 }
10030 }
10031 } else if (DestTy->isArrayType()) {
10032 PointeeTy = DestTy;
10033 }
10034
10035 if (PointeeTy == QualType())
10036 continue;
10037
10038 // Always complain about dynamic classes.
10039 bool IsContained;
10040 if (const CXXRecordDecl *ContainedRD =
10041 getContainedDynamicClass(PointeeTy, IsContained)) {
10042
10043 unsigned OperationType = 0;
10044 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10045 // "overwritten" if we're warning about the destination for any call
10046 // but memcmp; otherwise a verb appropriate to the call.
10047 if (ArgIdx != 0 || IsCmp) {
10048 if (BId == Builtin::BImemcpy)
10049 OperationType = 1;
10050 else if(BId == Builtin::BImemmove)
10051 OperationType = 2;
10052 else if (IsCmp)
10053 OperationType = 3;
10054 }
10055
10056 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10057 PDiag(diag::warn_dyn_class_memaccess)
10058 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10059 << IsContained << ContainedRD << OperationType
10060 << Call->getCallee()->getSourceRange());
10061 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10062 BId != Builtin::BImemset)
10064 Dest->getExprLoc(), Dest,
10065 PDiag(diag::warn_arc_object_memaccess)
10066 << ArgIdx << FnName << PointeeTy
10067 << Call->getCallee()->getSourceRange());
10068 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
10069
10070 // FIXME: Do not consider incomplete types even though they may be
10071 // completed later. GCC does not diagnose such code, but we may want to
10072 // consider diagnosing it in the future, perhaps under a different, but
10073 // related, diagnostic group.
10074 bool NonTriviallyCopyableCXXRecord =
10075 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
10076 !PointeeTy.isTriviallyCopyableType(Context);
10077
10078 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10080 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10081 PDiag(diag::warn_cstruct_memaccess)
10082 << ArgIdx << FnName << PointeeTy << 0);
10083 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10084 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10085 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10086 // FIXME: Limiting this warning to dest argument until we decide
10087 // whether it's valid for source argument too.
10088 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10089 PDiag(diag::warn_cxxstruct_memaccess)
10090 << FnName << PointeeTy);
10091 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10093 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10094 PDiag(diag::warn_cstruct_memaccess)
10095 << ArgIdx << FnName << PointeeTy << 1);
10096 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10097 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10098 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10099 // FIXME: Limiting this warning to dest argument until we decide
10100 // whether it's valid for source argument too.
10101 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10102 PDiag(diag::warn_cxxstruct_memaccess)
10103 << FnName << PointeeTy);
10104 } else {
10105 continue;
10106 }
10107 } else
10108 continue;
10109
10111 Dest->getExprLoc(), Dest,
10112 PDiag(diag::note_bad_memaccess_silence)
10113 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10114 break;
10115 }
10116}
10117
10118// A little helper routine: ignore addition and subtraction of integer literals.
10119// This intentionally does not ignore all integer constant expressions because
10120// we don't want to remove sizeof().
10121static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10122 Ex = Ex->IgnoreParenCasts();
10123
10124 while (true) {
10125 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10126 if (!BO || !BO->isAdditiveOp())
10127 break;
10128
10129 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10130 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10131
10132 if (isa<IntegerLiteral>(RHS))
10133 Ex = LHS;
10134 else if (isa<IntegerLiteral>(LHS))
10135 Ex = RHS;
10136 else
10137 break;
10138 }
10139
10140 return Ex;
10141}
10142
10144 ASTContext &Context) {
10145 // Only handle constant-sized or VLAs, but not flexible members.
10146 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10147 // Only issue the FIXIT for arrays of size > 1.
10148 if (CAT->getZExtSize() <= 1)
10149 return false;
10150 } else if (!Ty->isVariableArrayType()) {
10151 return false;
10152 }
10153 return true;
10154}
10155
10156void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10157 IdentifierInfo *FnName) {
10158
10159 // Don't crash if the user has the wrong number of arguments
10160 unsigned NumArgs = Call->getNumArgs();
10161 if ((NumArgs != 3) && (NumArgs != 4))
10162 return;
10163
10164 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10165 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10166 const Expr *CompareWithSrc = nullptr;
10167
10168 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10169 Call->getBeginLoc(), Call->getRParenLoc()))
10170 return;
10171
10172 // Look for 'strlcpy(dst, x, sizeof(x))'
10173 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10174 CompareWithSrc = Ex;
10175 else {
10176 // Look for 'strlcpy(dst, x, strlen(x))'
10177 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10178 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10179 SizeCall->getNumArgs() == 1)
10180 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10181 }
10182 }
10183
10184 if (!CompareWithSrc)
10185 return;
10186
10187 // Determine if the argument to sizeof/strlen is equal to the source
10188 // argument. In principle there's all kinds of things you could do
10189 // here, for instance creating an == expression and evaluating it with
10190 // EvaluateAsBooleanCondition, but this uses a more direct technique:
10191 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10192 if (!SrcArgDRE)
10193 return;
10194
10195 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10196 if (!CompareWithSrcDRE ||
10197 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10198 return;
10199
10200 const Expr *OriginalSizeArg = Call->getArg(2);
10201 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10202 << OriginalSizeArg->getSourceRange() << FnName;
10203
10204 // Output a FIXIT hint if the destination is an array (rather than a
10205 // pointer to an array). This could be enhanced to handle some
10206 // pointers if we know the actual size, like if DstArg is 'array+2'
10207 // we could say 'sizeof(array)-2'.
10208 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10210 return;
10211
10212 SmallString<128> sizeString;
10213 llvm::raw_svector_ostream OS(sizeString);
10214 OS << "sizeof(";
10215 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10216 OS << ")";
10217
10218 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10219 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10220 OS.str());
10221}
10222
10223/// Check if two expressions refer to the same declaration.
10224static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10225 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10226 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10227 return D1->getDecl() == D2->getDecl();
10228 return false;
10229}
10230
10231static const Expr *getStrlenExprArg(const Expr *E) {
10232 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10233 const FunctionDecl *FD = CE->getDirectCallee();
10234 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10235 return nullptr;
10236 return CE->getArg(0)->IgnoreParenCasts();
10237 }
10238 return nullptr;
10239}
10240
10241void Sema::CheckStrncatArguments(const CallExpr *CE,
10242 const IdentifierInfo *FnName) {
10243 // Don't crash if the user has the wrong number of arguments.
10244 if (CE->getNumArgs() < 3)
10245 return;
10246 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10247 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10248 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10249
10250 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10251 CE->getRParenLoc()))
10252 return;
10253
10254 // Identify common expressions, which are wrongly used as the size argument
10255 // to strncat and may lead to buffer overflows.
10256 unsigned PatternType = 0;
10257 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10258 // - sizeof(dst)
10259 if (referToTheSameDecl(SizeOfArg, DstArg))
10260 PatternType = 1;
10261 // - sizeof(src)
10262 else if (referToTheSameDecl(SizeOfArg, SrcArg))
10263 PatternType = 2;
10264 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10265 if (BE->getOpcode() == BO_Sub) {
10266 const Expr *L = BE->getLHS()->IgnoreParenCasts();
10267 const Expr *R = BE->getRHS()->IgnoreParenCasts();
10268 // - sizeof(dst) - strlen(dst)
10269 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10271 PatternType = 1;
10272 // - sizeof(src) - (anything)
10273 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10274 PatternType = 2;
10275 }
10276 }
10277
10278 if (PatternType == 0)
10279 return;
10280
10281 // Generate the diagnostic.
10282 SourceLocation SL = LenArg->getBeginLoc();
10283 SourceRange SR = LenArg->getSourceRange();
10285
10286 // If the function is defined as a builtin macro, do not show macro expansion.
10287 if (SM.isMacroArgExpansion(SL)) {
10288 SL = SM.getSpellingLoc(SL);
10289 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10290 SM.getSpellingLoc(SR.getEnd()));
10291 }
10292
10293 // Check if the destination is an array (rather than a pointer to an array).
10294 QualType DstTy = DstArg->getType();
10295 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10296 Context);
10297 if (!isKnownSizeArray) {
10298 if (PatternType == 1)
10299 Diag(SL, diag::warn_strncat_wrong_size) << SR;
10300 else
10301 Diag(SL, diag::warn_strncat_src_size) << SR;
10302 return;
10303 }
10304
10305 if (PatternType == 1)
10306 Diag(SL, diag::warn_strncat_large_size) << SR;
10307 else
10308 Diag(SL, diag::warn_strncat_src_size) << SR;
10309
10310 SmallString<128> sizeString;
10311 llvm::raw_svector_ostream OS(sizeString);
10312 OS << "sizeof(";
10313 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10314 OS << ") - ";
10315 OS << "strlen(";
10316 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10317 OS << ") - 1";
10318
10319 Diag(SL, diag::note_strncat_wrong_size)
10320 << FixItHint::CreateReplacement(SR, OS.str());
10321}
10322
10323namespace {
10324void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10325 const UnaryOperator *UnaryExpr, const Decl *D) {
10326 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10327 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10328 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10329 return;
10330 }
10331}
10332
10333void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10334 const UnaryOperator *UnaryExpr) {
10335 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10336 const Decl *D = Lvalue->getDecl();
10337 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
10338 if (!DD->getType()->isReferenceType())
10339 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10340 }
10341 }
10342
10343 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10344 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10345 Lvalue->getMemberDecl());
10346}
10347
10348void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10349 const UnaryOperator *UnaryExpr) {
10350 const auto *Lambda = dyn_cast<LambdaExpr>(
10352 if (!Lambda)
10353 return;
10354
10355 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10356 << CalleeName << 2 /*object: lambda expression*/;
10357}
10358
10359void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10360 const DeclRefExpr *Lvalue) {
10361 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10362 if (Var == nullptr)
10363 return;
10364
10365 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10366 << CalleeName << 0 /*object: */ << Var;
10367}
10368
10369void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10370 const CastExpr *Cast) {
10371 SmallString<128> SizeString;
10372 llvm::raw_svector_ostream OS(SizeString);
10373
10374 clang::CastKind Kind = Cast->getCastKind();
10375 if (Kind == clang::CK_BitCast &&
10376 !Cast->getSubExpr()->getType()->isFunctionPointerType())
10377 return;
10378 if (Kind == clang::CK_IntegralToPointer &&
10379 !isa<IntegerLiteral>(
10380 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10381 return;
10382
10383 switch (Cast->getCastKind()) {
10384 case clang::CK_BitCast:
10385 case clang::CK_IntegralToPointer:
10386 case clang::CK_FunctionToPointerDecay:
10387 OS << '\'';
10388 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10389 OS << '\'';
10390 break;
10391 default:
10392 return;
10393 }
10394
10395 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10396 << CalleeName << 0 /*object: */ << OS.str();
10397}
10398} // namespace
10399
10400void Sema::CheckFreeArguments(const CallExpr *E) {
10401 const std::string CalleeName =
10402 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10403
10404 { // Prefer something that doesn't involve a cast to make things simpler.
10405 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10406 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10407 switch (UnaryExpr->getOpcode()) {
10408 case UnaryOperator::Opcode::UO_AddrOf:
10409 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10410 case UnaryOperator::Opcode::UO_Plus:
10411 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10412 default:
10413 break;
10414 }
10415
10416 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10417 if (Lvalue->getType()->isArrayType())
10418 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10419
10420 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10421 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10422 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10423 return;
10424 }
10425
10426 if (isa<BlockExpr>(Arg)) {
10427 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10428 << CalleeName << 1 /*object: block*/;
10429 return;
10430 }
10431 }
10432 // Maybe the cast was important, check after the other cases.
10433 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10434 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10435}
10436
10437void
10438Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10439 SourceLocation ReturnLoc,
10440 bool isObjCMethod,
10441 const AttrVec *Attrs,
10442 const FunctionDecl *FD) {
10443 // Check if the return value is null but should not be.
10444 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10445 (!isObjCMethod && isNonNullType(lhsType))) &&
10446 CheckNonNullExpr(*this, RetValExp))
10447 Diag(ReturnLoc, diag::warn_null_ret)
10448 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10449
10450 // C++11 [basic.stc.dynamic.allocation]p4:
10451 // If an allocation function declared with a non-throwing
10452 // exception-specification fails to allocate storage, it shall return
10453 // a null pointer. Any other allocation function that fails to allocate
10454 // storage shall indicate failure only by throwing an exception [...]
10455 if (FD) {
10457 if (Op == OO_New || Op == OO_Array_New) {
10458 const FunctionProtoType *Proto
10459 = FD->getType()->castAs<FunctionProtoType>();
10460 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10461 CheckNonNullExpr(*this, RetValExp))
10462 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10463 << FD << getLangOpts().CPlusPlus11;
10464 }
10465 }
10466
10467 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
10468 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
10469 }
10470
10471 // PPC MMA non-pointer types are not allowed as return type. Checking the type
10472 // here prevent the user from using a PPC MMA type as trailing return type.
10473 if (Context.getTargetInfo().getTriple().isPPC64())
10474 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10475}
10476
10478 const Expr *RHS, BinaryOperatorKind Opcode) {
10479 if (!BinaryOperator::isEqualityOp(Opcode))
10480 return;
10481
10482 // Match and capture subexpressions such as "(float) X == 0.1".
10483 const FloatingLiteral *FPLiteral;
10484 const CastExpr *FPCast;
10485 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
10486 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
10487 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
10488 return FPLiteral && FPCast;
10489 };
10490
10491 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
10492 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
10493 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
10494 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
10495 TargetTy->isFloatingPoint()) {
10496 bool Lossy;
10497 llvm::APFloat TargetC = FPLiteral->getValue();
10498 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
10499 llvm::APFloat::rmNearestTiesToEven, &Lossy);
10500 if (Lossy) {
10501 // If the literal cannot be represented in the source type, then a
10502 // check for == is always false and check for != is always true.
10503 Diag(Loc, diag::warn_float_compare_literal)
10504 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
10505 << LHS->getSourceRange() << RHS->getSourceRange();
10506 return;
10507 }
10508 }
10509 }
10510
10511 // Match a more general floating-point equality comparison (-Wfloat-equal).
10512 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
10513 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
10514
10515 // Special case: check for x == x (which is OK).
10516 // Do not emit warnings for such cases.
10517 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10518 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10519 if (DRL->getDecl() == DRR->getDecl())
10520 return;
10521
10522 // Special case: check for comparisons against literals that can be exactly
10523 // represented by APFloat. In such cases, do not emit a warning. This
10524 // is a heuristic: often comparison against such literals are used to
10525 // detect if a value in a variable has not changed. This clearly can
10526 // lead to false negatives.
10527 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10528 if (FLL->isExact())
10529 return;
10530 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10531 if (FLR->isExact())
10532 return;
10533
10534 // Check for comparisons with builtin types.
10535 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
10536 CL && CL->getBuiltinCallee())
10537 return;
10538
10539 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
10540 CR && CR->getBuiltinCallee())
10541 return;
10542
10543 // Emit the diagnostic.
10544 Diag(Loc, diag::warn_floatingpoint_eq)
10545 << LHS->getSourceRange() << RHS->getSourceRange();
10546}
10547
10548//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10549//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10550
10551namespace {
10552
10553/// Structure recording the 'active' range of an integer-valued
10554/// expression.
10555struct IntRange {
10556 /// The number of bits active in the int. Note that this includes exactly one
10557 /// sign bit if !NonNegative.
10558 unsigned Width;
10559
10560 /// True if the int is known not to have negative values. If so, all leading
10561 /// bits before Width are known zero, otherwise they are known to be the
10562 /// same as the MSB within Width.
10563 bool NonNegative;
10564
10565 IntRange(unsigned Width, bool NonNegative)
10566 : Width(Width), NonNegative(NonNegative) {}
10567
10568 /// Number of bits excluding the sign bit.
10569 unsigned valueBits() const {
10570 return NonNegative ? Width : Width - 1;
10571 }
10572
10573 /// Returns the range of the bool type.
10574 static IntRange forBoolType() {
10575 return IntRange(1, true);
10576 }
10577
10578 /// Returns the range of an opaque value of the given integral type.
10579 static IntRange forValueOfType(ASTContext &C, QualType T) {
10580 return forValueOfCanonicalType(C,
10582 }
10583
10584 /// Returns the range of an opaque value of a canonical integral type.
10585 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10586 assert(T->isCanonicalUnqualified());
10587
10588 if (const auto *VT = dyn_cast<VectorType>(T))
10589 T = VT->getElementType().getTypePtr();
10590 if (const auto *CT = dyn_cast<ComplexType>(T))
10591 T = CT->getElementType().getTypePtr();
10592 if (const auto *AT = dyn_cast<AtomicType>(T))
10593 T = AT->getValueType().getTypePtr();
10594
10595 if (!C.getLangOpts().CPlusPlus) {
10596 // For enum types in C code, use the underlying datatype.
10597 if (const auto *ED = T->getAsEnumDecl())
10598 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
10599 } else if (auto *Enum = T->getAsEnumDecl()) {
10600 // For enum types in C++, use the known bit width of the enumerators.
10601 // In C++11, enums can have a fixed underlying type. Use this type to
10602 // compute the range.
10603 if (Enum->isFixed()) {
10604 return IntRange(C.getIntWidth(QualType(T, 0)),
10605 !Enum->getIntegerType()->isSignedIntegerType());
10606 }
10607
10608 unsigned NumPositive = Enum->getNumPositiveBits();
10609 unsigned NumNegative = Enum->getNumNegativeBits();
10610
10611 if (NumNegative == 0)
10612 return IntRange(NumPositive, true/*NonNegative*/);
10613 else
10614 return IntRange(std::max(NumPositive + 1, NumNegative),
10615 false/*NonNegative*/);
10616 }
10617
10618 if (const auto *EIT = dyn_cast<BitIntType>(T))
10619 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10620
10621 const BuiltinType *BT = cast<BuiltinType>(T);
10622 assert(BT->isInteger());
10623
10624 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10625 }
10626
10627 /// Returns the "target" range of a canonical integral type, i.e.
10628 /// the range of values expressible in the type.
10629 ///
10630 /// This matches forValueOfCanonicalType except that enums have the
10631 /// full range of their type, not the range of their enumerators.
10632 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10633 assert(T->isCanonicalUnqualified());
10634
10635 if (const VectorType *VT = dyn_cast<VectorType>(T))
10636 T = VT->getElementType().getTypePtr();
10637 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10638 T = CT->getElementType().getTypePtr();
10639 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10640 T = AT->getValueType().getTypePtr();
10641 if (const auto *ED = T->getAsEnumDecl())
10642 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
10643
10644 if (const auto *EIT = dyn_cast<BitIntType>(T))
10645 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10646
10647 const BuiltinType *BT = cast<BuiltinType>(T);
10648 assert(BT->isInteger());
10649
10650 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10651 }
10652
10653 /// Returns the supremum of two ranges: i.e. their conservative merge.
10654 static IntRange join(IntRange L, IntRange R) {
10655 bool Unsigned = L.NonNegative && R.NonNegative;
10656 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10657 L.NonNegative && R.NonNegative);
10658 }
10659
10660 /// Return the range of a bitwise-AND of the two ranges.
10661 static IntRange bit_and(IntRange L, IntRange R) {
10662 unsigned Bits = std::max(L.Width, R.Width);
10663 bool NonNegative = false;
10664 if (L.NonNegative) {
10665 Bits = std::min(Bits, L.Width);
10666 NonNegative = true;
10667 }
10668 if (R.NonNegative) {
10669 Bits = std::min(Bits, R.Width);
10670 NonNegative = true;
10671 }
10672 return IntRange(Bits, NonNegative);
10673 }
10674
10675 /// Return the range of a sum of the two ranges.
10676 static IntRange sum(IntRange L, IntRange R) {
10677 bool Unsigned = L.NonNegative && R.NonNegative;
10678 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10679 Unsigned);
10680 }
10681
10682 /// Return the range of a difference of the two ranges.
10683 static IntRange difference(IntRange L, IntRange R) {
10684 // We need a 1-bit-wider range if:
10685 // 1) LHS can be negative: least value can be reduced.
10686 // 2) RHS can be negative: greatest value can be increased.
10687 bool CanWiden = !L.NonNegative || !R.NonNegative;
10688 bool Unsigned = L.NonNegative && R.Width == 0;
10689 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10690 !Unsigned,
10691 Unsigned);
10692 }
10693
10694 /// Return the range of a product of the two ranges.
10695 static IntRange product(IntRange L, IntRange R) {
10696 // If both LHS and RHS can be negative, we can form
10697 // -2^L * -2^R = 2^(L + R)
10698 // which requires L + R + 1 value bits to represent.
10699 bool CanWiden = !L.NonNegative && !R.NonNegative;
10700 bool Unsigned = L.NonNegative && R.NonNegative;
10701 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10702 Unsigned);
10703 }
10704
10705 /// Return the range of a remainder operation between the two ranges.
10706 static IntRange rem(IntRange L, IntRange R) {
10707 // The result of a remainder can't be larger than the result of
10708 // either side. The sign of the result is the sign of the LHS.
10709 bool Unsigned = L.NonNegative;
10710 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10711 Unsigned);
10712 }
10713};
10714
10715} // namespace
10716
10717static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
10718 if (value.isSigned() && value.isNegative())
10719 return IntRange(value.getSignificantBits(), false);
10720
10721 if (value.getBitWidth() > MaxWidth)
10722 value = value.trunc(MaxWidth);
10723
10724 // isNonNegative() just checks the sign bit without considering
10725 // signedness.
10726 return IntRange(value.getActiveBits(), true);
10727}
10728
10729static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
10730 if (result.isInt())
10731 return GetValueRange(result.getInt(), MaxWidth);
10732
10733 if (result.isVector()) {
10734 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
10735 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10736 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
10737 R = IntRange::join(R, El);
10738 }
10739 return R;
10740 }
10741
10742 if (result.isComplexInt()) {
10743 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
10744 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
10745 return IntRange::join(R, I);
10746 }
10747
10748 // This can happen with lossless casts to intptr_t of "based" lvalues.
10749 // Assume it might use arbitrary bits.
10750 // FIXME: The only reason we need to pass the type in here is to get
10751 // the sign right on this one case. It would be nice if APValue
10752 // preserved this.
10753 assert(result.isLValue() || result.isAddrLabelDiff());
10754 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10755}
10756
10757static QualType GetExprType(const Expr *E) {
10758 QualType Ty = E->getType();
10759 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
10760 Ty = AtomicRHS->getValueType();
10761 return Ty;
10762}
10763
10764/// Attempts to estimate an approximate range for the given integer expression.
10765/// Returns a range if successful, otherwise it returns \c std::nullopt if a
10766/// reliable estimation cannot be determined.
10767///
10768/// \param MaxWidth The width to which the value will be truncated.
10769/// \param InConstantContext If \c true, interpret the expression within a
10770/// constant context.
10771/// \param Approximate If \c true, provide a likely range of values by assuming
10772/// that arithmetic on narrower types remains within those types.
10773/// If \c false, return a range that includes all possible values
10774/// resulting from the expression.
10775/// \returns A range of values that the expression might take, or
10776/// std::nullopt if a reliable estimation cannot be determined.
10777static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
10778 unsigned MaxWidth,
10779 bool InConstantContext,
10780 bool Approximate) {
10781 E = E->IgnoreParens();
10782
10783 // Try a full evaluation first.
10784 Expr::EvalResult result;
10785 if (E->EvaluateAsRValue(result, C, InConstantContext))
10786 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
10787
10788 // I think we only want to look through implicit casts here; if the
10789 // user has an explicit widening cast, we should treat the value as
10790 // being of the new, wider type.
10791 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10792 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10793 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
10794 Approximate);
10795
10796 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10797
10798 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10799 CE->getCastKind() == CK_BooleanToSignedIntegral;
10800
10801 // Assume that non-integer casts can span the full range of the type.
10802 if (!isIntegerCast)
10803 return OutputTypeRange;
10804
10805 std::optional<IntRange> SubRange = TryGetExprRange(
10806 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
10807 InConstantContext, Approximate);
10808 if (!SubRange)
10809 return std::nullopt;
10810
10811 // Bail out if the subexpr's range is as wide as the cast type.
10812 if (SubRange->Width >= OutputTypeRange.Width)
10813 return OutputTypeRange;
10814
10815 // Otherwise, we take the smaller width, and we're non-negative if
10816 // either the output type or the subexpr is.
10817 return IntRange(SubRange->Width,
10818 SubRange->NonNegative || OutputTypeRange.NonNegative);
10819 }
10820
10821 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10822 // If we can fold the condition, just take that operand.
10823 bool CondResult;
10824 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10825 return TryGetExprRange(
10826 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
10827 InConstantContext, Approximate);
10828
10829 // Otherwise, conservatively merge.
10830 // TryGetExprRange requires an integer expression, but a throw expression
10831 // results in a void type.
10832 Expr *TrueExpr = CO->getTrueExpr();
10833 if (TrueExpr->getType()->isVoidType())
10834 return std::nullopt;
10835
10836 std::optional<IntRange> L =
10837 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
10838 if (!L)
10839 return std::nullopt;
10840
10841 Expr *FalseExpr = CO->getFalseExpr();
10842 if (FalseExpr->getType()->isVoidType())
10843 return std::nullopt;
10844
10845 std::optional<IntRange> R =
10846 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
10847 if (!R)
10848 return std::nullopt;
10849
10850 return IntRange::join(*L, *R);
10851 }
10852
10853 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10854 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
10855
10856 switch (BO->getOpcode()) {
10857 case BO_Cmp:
10858 llvm_unreachable("builtin <=> should have class type");
10859
10860 // Boolean-valued operations are single-bit and positive.
10861 case BO_LAnd:
10862 case BO_LOr:
10863 case BO_LT:
10864 case BO_GT:
10865 case BO_LE:
10866 case BO_GE:
10867 case BO_EQ:
10868 case BO_NE:
10869 return IntRange::forBoolType();
10870
10871 // The type of the assignments is the type of the LHS, so the RHS
10872 // is not necessarily the same type.
10873 case BO_MulAssign:
10874 case BO_DivAssign:
10875 case BO_RemAssign:
10876 case BO_AddAssign:
10877 case BO_SubAssign:
10878 case BO_XorAssign:
10879 case BO_OrAssign:
10880 // TODO: bitfields?
10881 return IntRange::forValueOfType(C, GetExprType(E));
10882
10883 // Simple assignments just pass through the RHS, which will have
10884 // been coerced to the LHS type.
10885 case BO_Assign:
10886 // TODO: bitfields?
10887 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10888 Approximate);
10889
10890 // Operations with opaque sources are black-listed.
10891 case BO_PtrMemD:
10892 case BO_PtrMemI:
10893 return IntRange::forValueOfType(C, GetExprType(E));
10894
10895 // Bitwise-and uses the *infinum* of the two source ranges.
10896 case BO_And:
10897 case BO_AndAssign:
10898 Combine = IntRange::bit_and;
10899 break;
10900
10901 // Left shift gets black-listed based on a judgement call.
10902 case BO_Shl:
10903 // ...except that we want to treat '1 << (blah)' as logically
10904 // positive. It's an important idiom.
10905 if (IntegerLiteral *I
10906 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10907 if (I->getValue() == 1) {
10908 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10909 return IntRange(R.Width, /*NonNegative*/ true);
10910 }
10911 }
10912 [[fallthrough]];
10913
10914 case BO_ShlAssign:
10915 return IntRange::forValueOfType(C, GetExprType(E));
10916
10917 // Right shift by a constant can narrow its left argument.
10918 case BO_Shr:
10919 case BO_ShrAssign: {
10920 std::optional<IntRange> L = TryGetExprRange(
10921 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
10922 if (!L)
10923 return std::nullopt;
10924
10925 // If the shift amount is a positive constant, drop the width by
10926 // that much.
10927 if (std::optional<llvm::APSInt> shift =
10928 BO->getRHS()->getIntegerConstantExpr(C)) {
10929 if (shift->isNonNegative()) {
10930 if (shift->uge(L->Width))
10931 L->Width = (L->NonNegative ? 0 : 1);
10932 else
10933 L->Width -= shift->getZExtValue();
10934 }
10935 }
10936
10937 return L;
10938 }
10939
10940 // Comma acts as its right operand.
10941 case BO_Comma:
10942 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10943 Approximate);
10944
10945 case BO_Add:
10946 if (!Approximate)
10947 Combine = IntRange::sum;
10948 break;
10949
10950 case BO_Sub:
10951 if (BO->getLHS()->getType()->isPointerType())
10952 return IntRange::forValueOfType(C, GetExprType(E));
10953 if (!Approximate)
10954 Combine = IntRange::difference;
10955 break;
10956
10957 case BO_Mul:
10958 if (!Approximate)
10959 Combine = IntRange::product;
10960 break;
10961
10962 // The width of a division result is mostly determined by the size
10963 // of the LHS.
10964 case BO_Div: {
10965 // Don't 'pre-truncate' the operands.
10966 unsigned opWidth = C.getIntWidth(GetExprType(E));
10967 std::optional<IntRange> L = TryGetExprRange(
10968 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
10969 if (!L)
10970 return std::nullopt;
10971
10972 // If the divisor is constant, use that.
10973 if (std::optional<llvm::APSInt> divisor =
10974 BO->getRHS()->getIntegerConstantExpr(C)) {
10975 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
10976 if (log2 >= L->Width)
10977 L->Width = (L->NonNegative ? 0 : 1);
10978 else
10979 L->Width = std::min(L->Width - log2, MaxWidth);
10980 return L;
10981 }
10982
10983 // Otherwise, just use the LHS's width.
10984 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
10985 // could be -1.
10986 std::optional<IntRange> R = TryGetExprRange(
10987 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
10988 if (!R)
10989 return std::nullopt;
10990
10991 return IntRange(L->Width, L->NonNegative && R->NonNegative);
10992 }
10993
10994 case BO_Rem:
10995 Combine = IntRange::rem;
10996 break;
10997
10998 // The default behavior is okay for these.
10999 case BO_Xor:
11000 case BO_Or:
11001 break;
11002 }
11003
11004 // Combine the two ranges, but limit the result to the type in which we
11005 // performed the computation.
11007 unsigned opWidth = C.getIntWidth(T);
11008 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
11009 InConstantContext, Approximate);
11010 if (!L)
11011 return std::nullopt;
11012
11013 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
11014 InConstantContext, Approximate);
11015 if (!R)
11016 return std::nullopt;
11017
11018 IntRange C = Combine(*L, *R);
11019 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11020 C.Width = std::min(C.Width, MaxWidth);
11021 return C;
11022 }
11023
11024 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11025 switch (UO->getOpcode()) {
11026 // Boolean-valued operations are white-listed.
11027 case UO_LNot:
11028 return IntRange::forBoolType();
11029
11030 // Operations with opaque sources are black-listed.
11031 case UO_Deref:
11032 case UO_AddrOf: // should be impossible
11033 return IntRange::forValueOfType(C, GetExprType(E));
11034
11035 case UO_Minus: {
11036 if (E->getType()->isUnsignedIntegerType()) {
11037 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11038 Approximate);
11039 }
11040
11041 std::optional<IntRange> SubRange = TryGetExprRange(
11042 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11043
11044 if (!SubRange)
11045 return std::nullopt;
11046
11047 // If the range was previously non-negative, we need an extra bit for the
11048 // sign bit. Otherwise, we need an extra bit because the negation of the
11049 // most-negative value is one bit wider than that value.
11050 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
11051 }
11052
11053 case UO_Not: {
11054 if (E->getType()->isUnsignedIntegerType()) {
11055 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11056 Approximate);
11057 }
11058
11059 std::optional<IntRange> SubRange = TryGetExprRange(
11060 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11061
11062 if (!SubRange)
11063 return std::nullopt;
11064
11065 // The width increments by 1 if the sub-expression cannot be negative
11066 // since it now can be.
11067 return IntRange(
11068 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
11069 false);
11070 }
11071
11072 default:
11073 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11074 Approximate);
11075 }
11076 }
11077
11078 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11079 return TryGetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11080 Approximate);
11081
11082 if (const auto *BitField = E->getSourceBitField())
11083 return IntRange(BitField->getBitWidthValue(),
11084 BitField->getType()->isUnsignedIntegerOrEnumerationType());
11085
11086 if (GetExprType(E)->isVoidType())
11087 return std::nullopt;
11088
11089 return IntRange::forValueOfType(C, GetExprType(E));
11090}
11091
11092static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11093 bool InConstantContext,
11094 bool Approximate) {
11095 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11096 Approximate);
11097}
11098
11099/// Checks whether the given value, which currently has the given
11100/// source semantics, has the same value when coerced through the
11101/// target semantics.
11102static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11103 const llvm::fltSemantics &Src,
11104 const llvm::fltSemantics &Tgt) {
11105 llvm::APFloat truncated = value;
11106
11107 bool ignored;
11108 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11109 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11110
11111 return truncated.bitwiseIsEqual(value);
11112}
11113
11114/// Checks whether the given value, which currently has the given
11115/// source semantics, has the same value when coerced through the
11116/// target semantics.
11117///
11118/// The value might be a vector of floats (or a complex number).
11119static bool IsSameFloatAfterCast(const APValue &value,
11120 const llvm::fltSemantics &Src,
11121 const llvm::fltSemantics &Tgt) {
11122 if (value.isFloat())
11123 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11124
11125 if (value.isVector()) {
11126 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11127 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11128 return false;
11129 return true;
11130 }
11131
11132 assert(value.isComplexFloat());
11133 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11134 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11135}
11136
11138 bool IsListInit = false);
11139
11140static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
11141 // Suppress cases where we are comparing against an enum constant.
11142 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11143 if (isa<EnumConstantDecl>(DR->getDecl()))
11144 return true;
11145
11146 // Suppress cases where the value is expanded from a macro, unless that macro
11147 // is how a language represents a boolean literal. This is the case in both C
11148 // and Objective-C.
11149 SourceLocation BeginLoc = E->getBeginLoc();
11150 if (BeginLoc.isMacroID()) {
11151 StringRef MacroName = Lexer::getImmediateMacroName(
11152 BeginLoc, S.getSourceManager(), S.getLangOpts());
11153 return MacroName != "YES" && MacroName != "NO" &&
11154 MacroName != "true" && MacroName != "false";
11155 }
11156
11157 return false;
11158}
11159
11160static bool isKnownToHaveUnsignedValue(const Expr *E) {
11161 return E->getType()->isIntegerType() &&
11162 (!E->getType()->isSignedIntegerType() ||
11164}
11165
11166namespace {
11167/// The promoted range of values of a type. In general this has the
11168/// following structure:
11169///
11170/// |-----------| . . . |-----------|
11171/// ^ ^ ^ ^
11172/// Min HoleMin HoleMax Max
11173///
11174/// ... where there is only a hole if a signed type is promoted to unsigned
11175/// (in which case Min and Max are the smallest and largest representable
11176/// values).
11177struct PromotedRange {
11178 // Min, or HoleMax if there is a hole.
11179 llvm::APSInt PromotedMin;
11180 // Max, or HoleMin if there is a hole.
11181 llvm::APSInt PromotedMax;
11182
11183 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11184 if (R.Width == 0)
11185 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11186 else if (R.Width >= BitWidth && !Unsigned) {
11187 // Promotion made the type *narrower*. This happens when promoting
11188 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11189 // Treat all values of 'signed int' as being in range for now.
11190 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11191 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11192 } else {
11193 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11194 .extOrTrunc(BitWidth);
11195 PromotedMin.setIsUnsigned(Unsigned);
11196
11197 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11198 .extOrTrunc(BitWidth);
11199 PromotedMax.setIsUnsigned(Unsigned);
11200 }
11201 }
11202
11203 // Determine whether this range is contiguous (has no hole).
11204 bool isContiguous() const { return PromotedMin <= PromotedMax; }
11205
11206 // Where a constant value is within the range.
11207 enum ComparisonResult {
11208 LT = 0x1,
11209 LE = 0x2,
11210 GT = 0x4,
11211 GE = 0x8,
11212 EQ = 0x10,
11213 NE = 0x20,
11214 InRangeFlag = 0x40,
11215
11216 Less = LE | LT | NE,
11217 Min = LE | InRangeFlag,
11218 InRange = InRangeFlag,
11219 Max = GE | InRangeFlag,
11220 Greater = GE | GT | NE,
11221
11222 OnlyValue = LE | GE | EQ | InRangeFlag,
11223 InHole = NE
11224 };
11225
11226 ComparisonResult compare(const llvm::APSInt &Value) const {
11227 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11228 Value.isUnsigned() == PromotedMin.isUnsigned());
11229 if (!isContiguous()) {
11230 assert(Value.isUnsigned() && "discontiguous range for signed compare");
11231 if (Value.isMinValue()) return Min;
11232 if (Value.isMaxValue()) return Max;
11233 if (Value >= PromotedMin) return InRange;
11234 if (Value <= PromotedMax) return InRange;
11235 return InHole;
11236 }
11237
11238 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11239 case -1: return Less;
11240 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11241 case 1:
11242 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11243 case -1: return InRange;
11244 case 0: return Max;
11245 case 1: return Greater;
11246 }
11247 }
11248
11249 llvm_unreachable("impossible compare result");
11250 }
11251
11252 static std::optional<StringRef>
11253 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11254 if (Op == BO_Cmp) {
11255 ComparisonResult LTFlag = LT, GTFlag = GT;
11256 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11257
11258 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11259 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11260 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11261 return std::nullopt;
11262 }
11263
11264 ComparisonResult TrueFlag, FalseFlag;
11265 if (Op == BO_EQ) {
11266 TrueFlag = EQ;
11267 FalseFlag = NE;
11268 } else if (Op == BO_NE) {
11269 TrueFlag = NE;
11270 FalseFlag = EQ;
11271 } else {
11272 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11273 TrueFlag = LT;
11274 FalseFlag = GE;
11275 } else {
11276 TrueFlag = GT;
11277 FalseFlag = LE;
11278 }
11279 if (Op == BO_GE || Op == BO_LE)
11280 std::swap(TrueFlag, FalseFlag);
11281 }
11282 if (R & TrueFlag)
11283 return StringRef("true");
11284 if (R & FalseFlag)
11285 return StringRef("false");
11286 return std::nullopt;
11287 }
11288};
11289}
11290
11291static bool HasEnumType(const Expr *E) {
11292 // Strip off implicit integral promotions.
11293 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11294 if (ICE->getCastKind() != CK_IntegralCast &&
11295 ICE->getCastKind() != CK_NoOp)
11296 break;
11297 E = ICE->getSubExpr();
11298 }
11299
11300 return E->getType()->isEnumeralType();
11301}
11302
11303static int classifyConstantValue(Expr *Constant) {
11304 // The values of this enumeration are used in the diagnostics
11305 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11306 enum ConstantValueKind {
11307 Miscellaneous = 0,
11308 LiteralTrue,
11309 LiteralFalse
11310 };
11311 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11312 return BL->getValue() ? ConstantValueKind::LiteralTrue
11313 : ConstantValueKind::LiteralFalse;
11314 return ConstantValueKind::Miscellaneous;
11315}
11316
11318 Expr *Constant, Expr *Other,
11319 const llvm::APSInt &Value,
11320 bool RhsConstant) {
11322 return false;
11323
11324 Expr *OriginalOther = Other;
11325
11326 Constant = Constant->IgnoreParenImpCasts();
11327 Other = Other->IgnoreParenImpCasts();
11328
11329 // Suppress warnings on tautological comparisons between values of the same
11330 // enumeration type. There are only two ways we could warn on this:
11331 // - If the constant is outside the range of representable values of
11332 // the enumeration. In such a case, we should warn about the cast
11333 // to enumeration type, not about the comparison.
11334 // - If the constant is the maximum / minimum in-range value. For an
11335 // enumeratin type, such comparisons can be meaningful and useful.
11336 if (Constant->getType()->isEnumeralType() &&
11337 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11338 return false;
11339
11340 std::optional<IntRange> OtherValueRange = TryGetExprRange(
11341 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
11342 if (!OtherValueRange)
11343 return false;
11344
11345 QualType OtherT = Other->getType();
11346 if (const auto *AT = OtherT->getAs<AtomicType>())
11347 OtherT = AT->getValueType();
11348 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11349
11350 // Special case for ObjC BOOL on targets where its a typedef for a signed char
11351 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11352 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11353 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
11354 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11355
11356 // Whether we're treating Other as being a bool because of the form of
11357 // expression despite it having another type (typically 'int' in C).
11358 bool OtherIsBooleanDespiteType =
11359 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11360 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11361 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
11362
11363 // Check if all values in the range of possible values of this expression
11364 // lead to the same comparison outcome.
11365 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
11366 Value.isUnsigned());
11367 auto Cmp = OtherPromotedValueRange.compare(Value);
11368 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11369 if (!Result)
11370 return false;
11371
11372 // Also consider the range determined by the type alone. This allows us to
11373 // classify the warning under the proper diagnostic group.
11374 bool TautologicalTypeCompare = false;
11375 {
11376 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11377 Value.isUnsigned());
11378 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11379 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11380 RhsConstant)) {
11381 TautologicalTypeCompare = true;
11382 Cmp = TypeCmp;
11384 }
11385 }
11386
11387 // Don't warn if the non-constant operand actually always evaluates to the
11388 // same value.
11389 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
11390 return false;
11391
11392 // Suppress the diagnostic for an in-range comparison if the constant comes
11393 // from a macro or enumerator. We don't want to diagnose
11394 //
11395 // some_long_value <= INT_MAX
11396 //
11397 // when sizeof(int) == sizeof(long).
11398 bool InRange = Cmp & PromotedRange::InRangeFlag;
11399 if (InRange && IsEnumConstOrFromMacro(S, Constant))
11400 return false;
11401
11402 // A comparison of an unsigned bit-field against 0 is really a type problem,
11403 // even though at the type level the bit-field might promote to 'signed int'.
11404 if (Other->refersToBitField() && InRange && Value == 0 &&
11405 Other->getType()->isUnsignedIntegerOrEnumerationType())
11406 TautologicalTypeCompare = true;
11407
11408 // If this is a comparison to an enum constant, include that
11409 // constant in the diagnostic.
11410 const EnumConstantDecl *ED = nullptr;
11411 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
11412 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11413
11414 // Should be enough for uint128 (39 decimal digits)
11415 SmallString<64> PrettySourceValue;
11416 llvm::raw_svector_ostream OS(PrettySourceValue);
11417 if (ED) {
11418 OS << '\'' << *ED << "' (" << Value << ")";
11419 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11420 Constant->IgnoreParenImpCasts())) {
11421 OS << (BL->getValue() ? "YES" : "NO");
11422 } else {
11423 OS << Value;
11424 }
11425
11426 if (!TautologicalTypeCompare) {
11427 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11428 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
11429 << E->getOpcodeStr() << OS.str() << *Result
11430 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11431 return true;
11432 }
11433
11434 if (IsObjCSignedCharBool) {
11435 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11436 S.PDiag(diag::warn_tautological_compare_objc_bool)
11437 << OS.str() << *Result);
11438 return true;
11439 }
11440
11441 // FIXME: We use a somewhat different formatting for the in-range cases and
11442 // cases involving boolean values for historical reasons. We should pick a
11443 // consistent way of presenting these diagnostics.
11444 if (!InRange || Other->isKnownToHaveBooleanValue()) {
11445
11447 E->getOperatorLoc(), E,
11448 S.PDiag(!InRange ? diag::warn_out_of_range_compare
11449 : diag::warn_tautological_bool_compare)
11450 << OS.str() << classifyConstantValue(Constant) << OtherT
11451 << OtherIsBooleanDespiteType << *Result
11452 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11453 } else {
11454 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11455 unsigned Diag =
11456 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11457 ? (HasEnumType(OriginalOther)
11458 ? diag::warn_unsigned_enum_always_true_comparison
11459 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11460 : diag::warn_unsigned_always_true_comparison)
11461 : diag::warn_tautological_constant_compare;
11462
11463 S.Diag(E->getOperatorLoc(), Diag)
11464 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11465 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11466 }
11467
11468 return true;
11469}
11470
11471/// Analyze the operands of the given comparison. Implements the
11472/// fallback case from AnalyzeComparison.
11474 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11475 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11476}
11477
11478/// Implements -Wsign-compare.
11479///
11480/// \param E the binary operator to check for warnings
11482 // The type the comparison is being performed in.
11483 QualType T = E->getLHS()->getType();
11484
11485 // Only analyze comparison operators where both sides have been converted to
11486 // the same type.
11487 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11488 return AnalyzeImpConvsInComparison(S, E);
11489
11490 // Don't analyze value-dependent comparisons directly.
11491 if (E->isValueDependent())
11492 return AnalyzeImpConvsInComparison(S, E);
11493
11494 Expr *LHS = E->getLHS();
11495 Expr *RHS = E->getRHS();
11496
11497 if (T->isIntegralType(S.Context)) {
11498 std::optional<llvm::APSInt> RHSValue =
11500 std::optional<llvm::APSInt> LHSValue =
11502
11503 // We don't care about expressions whose result is a constant.
11504 if (RHSValue && LHSValue)
11505 return AnalyzeImpConvsInComparison(S, E);
11506
11507 // We only care about expressions where just one side is literal
11508 if ((bool)RHSValue ^ (bool)LHSValue) {
11509 // Is the constant on the RHS or LHS?
11510 const bool RhsConstant = (bool)RHSValue;
11511 Expr *Const = RhsConstant ? RHS : LHS;
11512 Expr *Other = RhsConstant ? LHS : RHS;
11513 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11514
11515 // Check whether an integer constant comparison results in a value
11516 // of 'true' or 'false'.
11517 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11518 return AnalyzeImpConvsInComparison(S, E);
11519 }
11520 }
11521
11523 // We don't do anything special if this isn't an unsigned integral
11524 // comparison: we're only interested in integral comparisons, and
11525 // signed comparisons only happen in cases we don't care to warn about.
11526 return AnalyzeImpConvsInComparison(S, E);
11527 }
11528
11529 LHS = LHS->IgnoreParenImpCasts();
11530 RHS = RHS->IgnoreParenImpCasts();
11531
11532 if (!S.getLangOpts().CPlusPlus) {
11533 // Avoid warning about comparison of integers with different signs when
11534 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11535 // the type of `E`.
11536 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11537 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11538 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11539 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11540 }
11541
11542 // Check to see if one of the (unmodified) operands is of different
11543 // signedness.
11544 Expr *signedOperand, *unsignedOperand;
11546 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11547 "unsigned comparison between two signed integer expressions?");
11548 signedOperand = LHS;
11549 unsignedOperand = RHS;
11550 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11551 signedOperand = RHS;
11552 unsignedOperand = LHS;
11553 } else {
11554 return AnalyzeImpConvsInComparison(S, E);
11555 }
11556
11557 // Otherwise, calculate the effective range of the signed operand.
11558 std::optional<IntRange> signedRange =
11560 /*Approximate=*/true);
11561 if (!signedRange)
11562 return;
11563
11564 // Go ahead and analyze implicit conversions in the operands. Note
11565 // that we skip the implicit conversions on both sides.
11566 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11567 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11568
11569 // If the signed range is non-negative, -Wsign-compare won't fire.
11570 if (signedRange->NonNegative)
11571 return;
11572
11573 // For (in)equality comparisons, if the unsigned operand is a
11574 // constant which cannot collide with a overflowed signed operand,
11575 // then reinterpreting the signed operand as unsigned will not
11576 // change the result of the comparison.
11577 if (E->isEqualityOp()) {
11578 unsigned comparisonWidth = S.Context.getIntWidth(T);
11579 std::optional<IntRange> unsignedRange = TryGetExprRange(
11580 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
11581 /*Approximate=*/true);
11582 if (!unsignedRange)
11583 return;
11584
11585 // We should never be unable to prove that the unsigned operand is
11586 // non-negative.
11587 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
11588
11589 if (unsignedRange->Width < comparisonWidth)
11590 return;
11591 }
11592
11593 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11594 S.PDiag(diag::warn_mixed_sign_comparison)
11595 << LHS->getType() << RHS->getType()
11596 << LHS->getSourceRange() << RHS->getSourceRange());
11597}
11598
11599/// Analyzes an attempt to assign the given value to a bitfield.
11600///
11601/// Returns true if there was something fishy about the attempt.
11603 SourceLocation InitLoc) {
11604 assert(Bitfield->isBitField());
11605 if (Bitfield->isInvalidDecl())
11606 return false;
11607
11608 // White-list bool bitfields.
11609 QualType BitfieldType = Bitfield->getType();
11610 if (BitfieldType->isBooleanType())
11611 return false;
11612
11613 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
11614 // If the underlying enum type was not explicitly specified as an unsigned
11615 // type and the enum contain only positive values, MSVC++ will cause an
11616 // inconsistency by storing this as a signed type.
11617 if (S.getLangOpts().CPlusPlus11 &&
11618 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11619 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11620 BitfieldEnumDecl->getNumNegativeBits() == 0) {
11621 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11622 << BitfieldEnumDecl;
11623 }
11624 }
11625
11626 // Ignore value- or type-dependent expressions.
11627 if (Bitfield->getBitWidth()->isValueDependent() ||
11628 Bitfield->getBitWidth()->isTypeDependent() ||
11629 Init->isValueDependent() ||
11630 Init->isTypeDependent())
11631 return false;
11632
11633 Expr *OriginalInit = Init->IgnoreParenImpCasts();
11634 unsigned FieldWidth = Bitfield->getBitWidthValue();
11635
11637 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11639 // The RHS is not constant. If the RHS has an enum type, make sure the
11640 // bitfield is wide enough to hold all the values of the enum without
11641 // truncation.
11642 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
11643 const PreferredTypeAttr *PTAttr = nullptr;
11644 if (!ED) {
11645 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
11646 if (PTAttr)
11647 ED = PTAttr->getType()->getAsEnumDecl();
11648 }
11649 if (ED) {
11650 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
11651
11652 // Enum types are implicitly signed on Windows, so check if there are any
11653 // negative enumerators to see if the enum was intended to be signed or
11654 // not.
11655 bool SignedEnum = ED->getNumNegativeBits() > 0;
11656
11657 // Check for surprising sign changes when assigning enum values to a
11658 // bitfield of different signedness. If the bitfield is signed and we
11659 // have exactly the right number of bits to store this unsigned enum,
11660 // suggest changing the enum to an unsigned type. This typically happens
11661 // on Windows where unfixed enums always use an underlying type of 'int'.
11662 unsigned DiagID = 0;
11663 if (SignedEnum && !SignedBitfield) {
11664 DiagID =
11665 PTAttr == nullptr
11666 ? diag::warn_unsigned_bitfield_assigned_signed_enum
11667 : diag::
11668 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
11669 } else if (SignedBitfield && !SignedEnum &&
11670 ED->getNumPositiveBits() == FieldWidth) {
11671 DiagID =
11672 PTAttr == nullptr
11673 ? diag::warn_signed_bitfield_enum_conversion
11674 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
11675 }
11676 if (DiagID) {
11677 S.Diag(InitLoc, DiagID) << Bitfield << ED;
11678 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11679 SourceRange TypeRange =
11680 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11681 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11682 << SignedEnum << TypeRange;
11683 if (PTAttr)
11684 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
11685 << ED;
11686 }
11687
11688 // Compute the required bitwidth. If the enum has negative values, we need
11689 // one more bit than the normal number of positive bits to represent the
11690 // sign bit.
11691 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11692 ED->getNumNegativeBits())
11693 : ED->getNumPositiveBits();
11694
11695 // Check the bitwidth.
11696 if (BitsNeeded > FieldWidth) {
11697 Expr *WidthExpr = Bitfield->getBitWidth();
11698 auto DiagID =
11699 PTAttr == nullptr
11700 ? diag::warn_bitfield_too_small_for_enum
11701 : diag::warn_preferred_type_bitfield_too_small_for_enum;
11702 S.Diag(InitLoc, DiagID) << Bitfield << ED;
11703 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11704 << BitsNeeded << ED << WidthExpr->getSourceRange();
11705 if (PTAttr)
11706 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
11707 << ED;
11708 }
11709 }
11710
11711 return false;
11712 }
11713
11714 llvm::APSInt Value = Result.Val.getInt();
11715
11716 unsigned OriginalWidth = Value.getBitWidth();
11717
11718 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
11719 // false positives where the user is demonstrating they intend to use the
11720 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
11721 // to a one-bit bit-field to see if the value came from a macro named 'true'.
11722 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
11723 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
11724 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
11725 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
11726 S.findMacroSpelling(MaybeMacroLoc, "true"))
11727 return false;
11728 }
11729
11730 if (!Value.isSigned() || Value.isNegative())
11731 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11732 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11733 OriginalWidth = Value.getSignificantBits();
11734
11735 if (OriginalWidth <= FieldWidth)
11736 return false;
11737
11738 // Compute the value which the bitfield will contain.
11739 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11740 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11741
11742 // Check whether the stored value is equal to the original value.
11743 TruncatedValue = TruncatedValue.extend(OriginalWidth);
11744 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11745 return false;
11746
11747 std::string PrettyValue = toString(Value, 10);
11748 std::string PrettyTrunc = toString(TruncatedValue, 10);
11749
11750 S.Diag(InitLoc, OneAssignedToOneBitBitfield
11751 ? diag::warn_impcast_single_bit_bitield_precision_constant
11752 : diag::warn_impcast_bitfield_precision_constant)
11753 << PrettyValue << PrettyTrunc << OriginalInit->getType()
11754 << Init->getSourceRange();
11755
11756 return true;
11757}
11758
11759/// Analyze the given simple or compound assignment for warning-worthy
11760/// operations.
11762 // Just recurse on the LHS.
11763 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11764
11765 // We want to recurse on the RHS as normal unless we're assigning to
11766 // a bitfield.
11767 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11768 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11769 E->getOperatorLoc())) {
11770 // Recurse, ignoring any implicit conversions on the RHS.
11771 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11772 E->getOperatorLoc());
11773 }
11774 }
11775
11776 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11777
11778 // Diagnose implicitly sequentially-consistent atomic assignment.
11779 if (E->getLHS()->getType()->isAtomicType())
11780 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11781}
11782
11783/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
11784static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
11785 QualType T, SourceLocation CContext, unsigned diag,
11786 bool PruneControlFlow = false) {
11787 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
11788 // address space annotations isn't really useful. The warnings aren't because
11789 // you're converting a `private int` to `unsigned int`, it is because you're
11790 // conerting `int` to `unsigned int`.
11791 if (SourceType.hasAddressSpace())
11792 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
11793 if (T.hasAddressSpace())
11795 if (PruneControlFlow) {
11797 S.PDiag(diag)
11798 << SourceType << T << E->getSourceRange()
11799 << SourceRange(CContext));
11800 return;
11801 }
11802 S.Diag(E->getExprLoc(), diag)
11803 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11804}
11805
11806/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
11807static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
11808 SourceLocation CContext, unsigned diag,
11809 bool PruneControlFlow = false) {
11810 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
11811}
11812
11813/// Diagnose an implicit cast from a floating point value to an integer value.
11815 SourceLocation CContext) {
11816 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11817 bool PruneWarnings = S.inTemplateInstantiation();
11818
11819 const Expr *InnerE = E->IgnoreParenImpCasts();
11820 // We also want to warn on, e.g., "int i = -1.234"
11821 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
11822 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11823 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11824
11825 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11826
11827 llvm::APFloat Value(0.0);
11828 bool IsConstant =
11830 if (!IsConstant) {
11831 if (S.ObjC().isSignedCharBool(T)) {
11833 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11834 << E->getType());
11835 }
11836
11837 return DiagnoseImpCast(S, E, T, CContext,
11838 diag::warn_impcast_float_integer, PruneWarnings);
11839 }
11840
11841 bool isExact = false;
11842
11843 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11845 llvm::APFloat::opStatus Result = Value.convertToInteger(
11846 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11847
11848 // FIXME: Force the precision of the source value down so we don't print
11849 // digits which are usually useless (we don't really care here if we
11850 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
11851 // would automatically print the shortest representation, but it's a bit
11852 // tricky to implement.
11853 SmallString<16> PrettySourceValue;
11854 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11855 precision = (precision * 59 + 195) / 196;
11856 Value.toString(PrettySourceValue, precision);
11857
11858 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
11860 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11861 << PrettySourceValue);
11862 }
11863
11864 if (Result == llvm::APFloat::opOK && isExact) {
11865 if (IsLiteral) return;
11866 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11867 PruneWarnings);
11868 }
11869
11870 // Conversion of a floating-point value to a non-bool integer where the
11871 // integral part cannot be represented by the integer type is undefined.
11872 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11873 return DiagnoseImpCast(
11874 S, E, T, CContext,
11875 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11876 : diag::warn_impcast_float_to_integer_out_of_range,
11877 PruneWarnings);
11878
11879 unsigned DiagID = 0;
11880 if (IsLiteral) {
11881 // Warn on floating point literal to integer.
11882 DiagID = diag::warn_impcast_literal_float_to_integer;
11883 } else if (IntegerValue == 0) {
11884 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
11885 return DiagnoseImpCast(S, E, T, CContext,
11886 diag::warn_impcast_float_integer, PruneWarnings);
11887 }
11888 // Warn on non-zero to zero conversion.
11889 DiagID = diag::warn_impcast_float_to_integer_zero;
11890 } else {
11891 if (IntegerValue.isUnsigned()) {
11892 if (!IntegerValue.isMaxValue()) {
11893 return DiagnoseImpCast(S, E, T, CContext,
11894 diag::warn_impcast_float_integer, PruneWarnings);
11895 }
11896 } else { // IntegerValue.isSigned()
11897 if (!IntegerValue.isMaxSignedValue() &&
11898 !IntegerValue.isMinSignedValue()) {
11899 return DiagnoseImpCast(S, E, T, CContext,
11900 diag::warn_impcast_float_integer, PruneWarnings);
11901 }
11902 }
11903 // Warn on evaluatable floating point expression to integer conversion.
11904 DiagID = diag::warn_impcast_float_to_integer;
11905 }
11906
11907 SmallString<16> PrettyTargetValue;
11908 if (IsBool)
11909 PrettyTargetValue = Value.isZero() ? "false" : "true";
11910 else
11911 IntegerValue.toString(PrettyTargetValue);
11912
11913 if (PruneWarnings) {
11915 S.PDiag(DiagID)
11916 << E->getType() << T.getUnqualifiedType()
11917 << PrettySourceValue << PrettyTargetValue
11918 << E->getSourceRange() << SourceRange(CContext));
11919 } else {
11920 S.Diag(E->getExprLoc(), DiagID)
11921 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11922 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11923 }
11924}
11925
11926/// Analyze the given compound assignment for the possible losing of
11927/// floating-point precision.
11929 assert(isa<CompoundAssignOperator>(E) &&
11930 "Must be compound assignment operation");
11931 // Recurse on the LHS and RHS in here
11932 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11933 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11934
11935 if (E->getLHS()->getType()->isAtomicType())
11936 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11937
11938 // Now check the outermost expression
11939 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11940 const auto *RBT = cast<CompoundAssignOperator>(E)
11941 ->getComputationResultType()
11942 ->getAs<BuiltinType>();
11943
11944 // The below checks assume source is floating point.
11945 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11946
11947 // If source is floating point but target is an integer.
11948 if (ResultBT->isInteger())
11949 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11950 E->getExprLoc(), diag::warn_impcast_float_integer);
11951
11952 if (!ResultBT->isFloatingPoint())
11953 return;
11954
11955 // If both source and target are floating points, warn about losing precision.
11957 QualType(ResultBT, 0), QualType(RBT, 0));
11958 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11959 // warn about dropping FP rank.
11960 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11961 diag::warn_impcast_float_result_precision);
11962}
11963
11964static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11965 IntRange Range) {
11966 if (!Range.Width) return "0";
11967
11968 llvm::APSInt ValueInRange = Value;
11969 ValueInRange.setIsSigned(!Range.NonNegative);
11970 ValueInRange = ValueInRange.trunc(Range.Width);
11971 return toString(ValueInRange, 10);
11972}
11973
11974static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
11975 bool ToBool) {
11976 if (!isa<ImplicitCastExpr>(Ex))
11977 return false;
11978
11979 const Expr *InnerE = Ex->IgnoreParenImpCasts();
11981 const Type *Source =
11983 if (Target->isDependentType())
11984 return false;
11985
11986 const auto *FloatCandidateBT =
11987 dyn_cast<BuiltinType>(ToBool ? Source : Target);
11988 const Type *BoolCandidateType = ToBool ? Target : Source;
11989
11990 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11991 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11992}
11993
11994static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
11995 SourceLocation CC) {
11996 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
11997 const Expr *CurrA = TheCall->getArg(I);
11998 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11999 continue;
12000
12001 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
12002 S, TheCall->getArg(I - 1), false));
12003 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
12004 S, TheCall->getArg(I + 1), false));
12005 if (IsSwapped) {
12006 // Warn on this floating-point to bool conversion.
12008 CurrA->getType(), CC,
12009 diag::warn_impcast_floating_point_to_bool);
12010 }
12011 }
12012}
12013
12015 SourceLocation CC) {
12016 // Don't warn on functions which have return type nullptr_t.
12017 if (isa<CallExpr>(E))
12018 return;
12019
12020 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12021 const Expr *NewE = E->IgnoreParenImpCasts();
12022 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
12023 bool HasNullPtrType = NewE->getType()->isNullPtrType();
12024 if (!IsGNUNullExpr && !HasNullPtrType)
12025 return;
12026
12027 // Return if target type is a safe conversion.
12028 if (T->isAnyPointerType() || T->isBlockPointerType() ||
12030 return;
12031
12032 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12033 E->getExprLoc()))
12034 return;
12035
12037
12038 // Venture through the macro stacks to get to the source of macro arguments.
12039 // The new location is a better location than the complete location that was
12040 // passed in.
12043
12044 // __null is usually wrapped in a macro. Go up a macro if that is the case.
12045 if (IsGNUNullExpr && Loc.isMacroID()) {
12046 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12047 Loc, S.SourceMgr, S.getLangOpts());
12048 if (MacroName == "NULL")
12050 }
12051
12052 // Only warn if the null and context location are in the same macro expansion.
12053 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12054 return;
12055
12056 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12057 << HasNullPtrType << T << SourceRange(CC)
12060}
12061
12062// Helper function to filter out cases for constant width constant conversion.
12063// Don't warn on char array initialization or for non-decimal values.
12065 SourceLocation CC) {
12066 // If initializing from a constant, and the constant starts with '0',
12067 // then it is a binary, octal, or hexadecimal. Allow these constants
12068 // to fill all the bits, even if there is a sign change.
12069 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12070 const char FirstLiteralCharacter =
12071 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12072 if (FirstLiteralCharacter == '0')
12073 return false;
12074 }
12075
12076 // If the CC location points to a '{', and the type is char, then assume
12077 // assume it is an array initialization.
12078 if (CC.isValid() && T->isCharType()) {
12079 const char FirstContextCharacter =
12081 if (FirstContextCharacter == '{')
12082 return false;
12083 }
12084
12085 return true;
12086}
12087
12089 const auto *IL = dyn_cast<IntegerLiteral>(E);
12090 if (!IL) {
12091 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12092 if (UO->getOpcode() == UO_Minus)
12093 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12094 }
12095 }
12096
12097 return IL;
12098}
12099
12101 E = E->IgnoreParenImpCasts();
12102 SourceLocation ExprLoc = E->getExprLoc();
12103
12104 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12105 BinaryOperator::Opcode Opc = BO->getOpcode();
12107 // Do not diagnose unsigned shifts.
12108 if (Opc == BO_Shl) {
12109 const auto *LHS = getIntegerLiteral(BO->getLHS());
12110 const auto *RHS = getIntegerLiteral(BO->getRHS());
12111 if (LHS && LHS->getValue() == 0)
12112 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12113 else if (!E->isValueDependent() && LHS && RHS &&
12114 RHS->getValue().isNonNegative() &&
12116 S.Diag(ExprLoc, diag::warn_left_shift_always)
12117 << (Result.Val.getInt() != 0);
12118 else if (E->getType()->isSignedIntegerType())
12119 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
12122 ") != 0");
12123 }
12124 }
12125
12126 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12127 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12128 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12129 if (!LHS || !RHS)
12130 return;
12131 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12132 (RHS->getValue() == 0 || RHS->getValue() == 1))
12133 // Do not diagnose common idioms.
12134 return;
12135 if (LHS->getValue() != 0 && RHS->getValue() != 0)
12136 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12137 }
12138}
12139
12141 const Type *Target, Expr *E,
12142 QualType T,
12143 SourceLocation CC) {
12144 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
12145 Source != Target);
12149 llvm::APSInt Value(32);
12150 Value = Result.Val.getInt();
12151 bool IsASCII = Value <= 0x7F;
12152 bool IsBMP = Value <= 0xD7FF || (Value >= 0xE000 && Value <= 0xFFFF);
12153 bool ConversionPreservesSemantics =
12154 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
12155
12156 if (!ConversionPreservesSemantics) {
12157 auto IsSingleCodeUnitCP = [](const QualType &T,
12158 const llvm::APSInt &Value) {
12159 if (T->isChar8Type())
12160 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
12161 if (T->isChar16Type())
12162 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
12163 assert(T->isChar32Type());
12164 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
12165 };
12166
12167 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
12168 << E->getType() << T
12169 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
12170 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
12171 }
12172 } else {
12173 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
12175 DiagnoseImpCast(S, E, T, CC,
12176 LosesPrecision ? diag::warn_impcast_unicode_precision
12177 : diag::warn_impcast_unicode_char_type);
12178 }
12179}
12180
12185};
12186
12188 QualType To) {
12189 QualType MaybePointee = From->getPointeeType();
12190 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12191 From = MaybePointee;
12192 MaybePointee = To->getPointeeType();
12193 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12194 To = MaybePointee;
12195
12196 if (const auto *FromFn = From->getAs<FunctionType>()) {
12197 if (const auto *ToFn = To->getAs<FunctionType>()) {
12198 if (FromFn->getCFIUncheckedCalleeAttr() &&
12199 !ToFn->getCFIUncheckedCalleeAttr())
12200 return Discarding;
12201 if (!FromFn->getCFIUncheckedCalleeAttr() &&
12202 ToFn->getCFIUncheckedCalleeAttr())
12203 return Adding;
12204 }
12205 }
12206 return None;
12207}
12208
12210 From = Context.getCanonicalType(From);
12211 To = Context.getCanonicalType(To);
12212 return ::AdjustingCFIUncheckedCallee(From, To) == Discarding;
12213}
12214
12216 From = Context.getCanonicalType(From);
12217 To = Context.getCanonicalType(To);
12218 return ::AdjustingCFIUncheckedCallee(From, To) == Adding;
12219}
12220
12222 bool *ICContext, bool IsListInit) {
12223 if (E->isTypeDependent() || E->isValueDependent()) return;
12224
12225 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
12227 if (Source == Target) return;
12228 if (Target->isDependentType()) return;
12229
12230 // If the conversion context location is invalid don't complain. We also
12231 // don't want to emit a warning if the issue occurs from the expansion of
12232 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12233 // delay this check as long as possible. Once we detect we are in that
12234 // scenario, we just return.
12235 if (CC.isInvalid())
12236 return;
12237
12238 if (Source->isAtomicType())
12239 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12240
12241 // Diagnose implicit casts to bool.
12242 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12243 if (isa<StringLiteral>(E))
12244 // Warn on string literal to bool. Checks for string literals in logical
12245 // and expressions, for instance, assert(0 && "error here"), are
12246 // prevented by a check in AnalyzeImplicitConversions().
12247 return DiagnoseImpCast(*this, E, T, CC,
12248 diag::warn_impcast_string_literal_to_bool);
12249 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12250 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12251 // This covers the literal expressions that evaluate to Objective-C
12252 // objects.
12253 return DiagnoseImpCast(*this, E, T, CC,
12254 diag::warn_impcast_objective_c_literal_to_bool);
12255 }
12256 if (Source->isPointerType() || Source->canDecayToPointerType()) {
12257 // Warn on pointer to bool conversion that is always true.
12259 SourceRange(CC));
12260 }
12261 }
12262
12263 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12264 // is a typedef for signed char (macOS), then that constant value has to be 1
12265 // or 0.
12266 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
12269 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12271 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12272 << toString(Result.Val.getInt(), 10));
12273 }
12274 return;
12275 }
12276 }
12277
12278 // Check implicit casts from Objective-C collection literals to specialized
12279 // collection types, e.g., NSArray<NSString *> *.
12280 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12281 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
12282 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12283 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
12284
12285 // Strip vector types.
12286 if (isa<VectorType>(Source)) {
12287 if (Target->isSveVLSBuiltinType() &&
12288 (ARM().areCompatibleSveTypes(QualType(Target, 0),
12289 QualType(Source, 0)) ||
12290 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
12291 QualType(Source, 0))))
12292 return;
12293
12294 if (Target->isRVVVLSBuiltinType() &&
12296 QualType(Source, 0)) ||
12298 QualType(Source, 0))))
12299 return;
12300
12301 if (!isa<VectorType>(Target)) {
12302 if (SourceMgr.isInSystemMacro(CC))
12303 return;
12304 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
12305 } else if (getLangOpts().HLSL &&
12306 Target->castAs<VectorType>()->getNumElements() <
12307 Source->castAs<VectorType>()->getNumElements()) {
12308 // Diagnose vector truncation but don't return. We may also want to
12309 // diagnose an element conversion.
12310 DiagnoseImpCast(*this, E, T, CC,
12311 diag::warn_hlsl_impcast_vector_truncation);
12312 }
12313
12314 // If the vector cast is cast between two vectors of the same size, it is
12315 // a bitcast, not a conversion, except under HLSL where it is a conversion.
12316 if (!getLangOpts().HLSL &&
12318 return;
12319
12320 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12321 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12322 }
12323 if (auto VecTy = dyn_cast<VectorType>(Target))
12324 Target = VecTy->getElementType().getTypePtr();
12325
12326 // Strip complex types.
12327 if (isa<ComplexType>(Source)) {
12328 if (!isa<ComplexType>(Target)) {
12329 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12330 return;
12331
12332 return DiagnoseImpCast(*this, E, T, CC,
12334 ? diag::err_impcast_complex_scalar
12335 : diag::warn_impcast_complex_scalar);
12336 }
12337
12338 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12339 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12340 }
12341
12342 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12343 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12344
12345 // Strip SVE vector types
12346 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
12347 // Need the original target type for vector type checks
12348 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
12349 // Handle conversion from scalable to fixed when msve-vector-bits is
12350 // specified
12351 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
12352 QualType(Source, 0)) ||
12353 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
12354 QualType(Source, 0)))
12355 return;
12356
12357 // If the vector cast is cast between two vectors of the same size, it is
12358 // a bitcast, not a conversion.
12360 return;
12361
12362 Source = SourceBT->getSveEltType(Context).getTypePtr();
12363 }
12364
12365 if (TargetBT && TargetBT->isSveVLSBuiltinType())
12366 Target = TargetBT->getSveEltType(Context).getTypePtr();
12367
12368 // If the source is floating point...
12369 if (SourceBT && SourceBT->isFloatingPoint()) {
12370 // ...and the target is floating point...
12371 if (TargetBT && TargetBT->isFloatingPoint()) {
12372 // ...then warn if we're dropping FP rank.
12373
12375 QualType(SourceBT, 0), QualType(TargetBT, 0));
12376 if (Order > 0) {
12377 // Don't warn about float constants that are precisely
12378 // representable in the target type.
12379 Expr::EvalResult result;
12380 if (E->EvaluateAsRValue(result, Context)) {
12381 // Value might be a float, a float vector, or a float complex.
12383 result.Val,
12385 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12386 return;
12387 }
12388
12389 if (SourceMgr.isInSystemMacro(CC))
12390 return;
12391
12392 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
12393 }
12394 // ... or possibly if we're increasing rank, too
12395 else if (Order < 0) {
12396 if (SourceMgr.isInSystemMacro(CC))
12397 return;
12398
12399 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
12400 }
12401 return;
12402 }
12403
12404 // If the target is integral, always warn.
12405 if (TargetBT && TargetBT->isInteger()) {
12406 if (SourceMgr.isInSystemMacro(CC))
12407 return;
12408
12409 DiagnoseFloatingImpCast(*this, E, T, CC);
12410 }
12411
12412 // Detect the case where a call result is converted from floating-point to
12413 // to bool, and the final argument to the call is converted from bool, to
12414 // discover this typo:
12415 //
12416 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
12417 //
12418 // FIXME: This is an incredibly special case; is there some more general
12419 // way to detect this class of misplaced-parentheses bug?
12420 if (Target->isBooleanType() && isa<CallExpr>(E)) {
12421 // Check last argument of function call to see if it is an
12422 // implicit cast from a type matching the type the result
12423 // is being cast to.
12424 CallExpr *CEx = cast<CallExpr>(E);
12425 if (unsigned NumArgs = CEx->getNumArgs()) {
12426 Expr *LastA = CEx->getArg(NumArgs - 1);
12427 Expr *InnerE = LastA->IgnoreParenImpCasts();
12428 if (isa<ImplicitCastExpr>(LastA) &&
12429 InnerE->getType()->isBooleanType()) {
12430 // Warn on this floating-point to bool conversion
12431 DiagnoseImpCast(*this, E, T, CC,
12432 diag::warn_impcast_floating_point_to_bool);
12433 }
12434 }
12435 }
12436 return;
12437 }
12438
12439 // Valid casts involving fixed point types should be accounted for here.
12440 if (Source->isFixedPointType()) {
12441 if (Target->isUnsaturatedFixedPointType()) {
12445 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12446 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
12447 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
12448 if (Value > MaxVal || Value < MinVal) {
12450 PDiag(diag::warn_impcast_fixed_point_range)
12451 << Value.toString() << T
12452 << E->getSourceRange()
12453 << clang::SourceRange(CC));
12454 return;
12455 }
12456 }
12457 } else if (Target->isIntegerType()) {
12461 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12462
12463 bool Overflowed;
12464 llvm::APSInt IntResult = FXResult.convertToInt(
12465 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
12466 &Overflowed);
12467
12468 if (Overflowed) {
12470 PDiag(diag::warn_impcast_fixed_point_range)
12471 << FXResult.toString() << T
12472 << E->getSourceRange()
12473 << clang::SourceRange(CC));
12474 return;
12475 }
12476 }
12477 }
12478 } else if (Target->isUnsaturatedFixedPointType()) {
12479 if (Source->isIntegerType()) {
12483 llvm::APSInt Value = Result.Val.getInt();
12484
12485 bool Overflowed;
12486 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12487 Value, Context.getFixedPointSemantics(T), &Overflowed);
12488
12489 if (Overflowed) {
12491 PDiag(diag::warn_impcast_fixed_point_range)
12492 << toString(Value, /*Radix=*/10) << T
12493 << E->getSourceRange()
12494 << clang::SourceRange(CC));
12495 return;
12496 }
12497 }
12498 }
12499 }
12500
12501 // If we are casting an integer type to a floating point type without
12502 // initialization-list syntax, we might lose accuracy if the floating
12503 // point type has a narrower significand than the integer type.
12504 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12505 TargetBT->isFloatingType() && !IsListInit) {
12506 // Determine the number of precision bits in the source integer type.
12507 std::optional<IntRange> SourceRange =
12509 /*Approximate=*/true);
12510 if (!SourceRange)
12511 return;
12512 unsigned int SourcePrecision = SourceRange->Width;
12513
12514 // Determine the number of precision bits in the
12515 // target floating point type.
12516 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12517 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12518
12519 if (SourcePrecision > 0 && TargetPrecision > 0 &&
12520 SourcePrecision > TargetPrecision) {
12521
12522 if (std::optional<llvm::APSInt> SourceInt =
12524 // If the source integer is a constant, convert it to the target
12525 // floating point type. Issue a warning if the value changes
12526 // during the whole conversion.
12527 llvm::APFloat TargetFloatValue(
12528 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12529 llvm::APFloat::opStatus ConversionStatus =
12530 TargetFloatValue.convertFromAPInt(
12531 *SourceInt, SourceBT->isSignedInteger(),
12532 llvm::APFloat::rmNearestTiesToEven);
12533
12534 if (ConversionStatus != llvm::APFloat::opOK) {
12535 SmallString<32> PrettySourceValue;
12536 SourceInt->toString(PrettySourceValue, 10);
12537 SmallString<32> PrettyTargetValue;
12538 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12539
12541 E->getExprLoc(), E,
12542 PDiag(diag::warn_impcast_integer_float_precision_constant)
12543 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12544 << E->getSourceRange() << clang::SourceRange(CC));
12545 }
12546 } else {
12547 // Otherwise, the implicit conversion may lose precision.
12548 DiagnoseImpCast(*this, E, T, CC,
12549 diag::warn_impcast_integer_float_precision);
12550 }
12551 }
12552 }
12553
12554 DiagnoseNullConversion(*this, E, T, CC);
12555
12557
12558 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
12559 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
12560 return;
12561 }
12562
12563 if (Target->isBooleanType())
12565
12567 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
12568 << QualType(Source, 0) << QualType(Target, 0);
12569 }
12570
12571 if (!Source->isIntegerType() || !Target->isIntegerType())
12572 return;
12573
12574 // TODO: remove this early return once the false positives for constant->bool
12575 // in templates, macros, etc, are reduced or removed.
12576 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12577 return;
12578
12579 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
12580 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12582 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12583 << E->getType());
12584 }
12585 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
12586 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
12587 if (!LikelySourceRange)
12588 return;
12589
12590 IntRange SourceTypeRange =
12591 IntRange::forTargetOfCanonicalType(Context, Source);
12592 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
12593
12594 if (LikelySourceRange->Width > TargetRange.Width) {
12595 // If the source is a constant, use a default-on diagnostic.
12596 // TODO: this should happen for bitfield stores, too.
12600 llvm::APSInt Value(32);
12601 Value = Result.Val.getInt();
12602
12603 if (SourceMgr.isInSystemMacro(CC))
12604 return;
12605
12606 std::string PrettySourceValue = toString(Value, 10);
12607 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12608
12610 PDiag(diag::warn_impcast_integer_precision_constant)
12611 << PrettySourceValue << PrettyTargetValue
12612 << E->getType() << T << E->getSourceRange()
12613 << SourceRange(CC));
12614 return;
12615 }
12616
12617 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12618 if (SourceMgr.isInSystemMacro(CC))
12619 return;
12620
12621 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
12622 if (UO->getOpcode() == UO_Minus)
12623 return DiagnoseImpCast(
12624 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
12625 }
12626
12627 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
12628 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
12629 /* pruneControlFlow */ true);
12630 return DiagnoseImpCast(*this, E, T, CC,
12631 diag::warn_impcast_integer_precision);
12632 }
12633
12634 if (TargetRange.Width > SourceTypeRange.Width) {
12635 if (auto *UO = dyn_cast<UnaryOperator>(E))
12636 if (UO->getOpcode() == UO_Minus)
12637 if (Source->isUnsignedIntegerType()) {
12638 if (Target->isUnsignedIntegerType())
12639 return DiagnoseImpCast(*this, E, T, CC,
12640 diag::warn_impcast_high_order_zero_bits);
12641 if (Target->isSignedIntegerType())
12642 return DiagnoseImpCast(*this, E, T, CC,
12643 diag::warn_impcast_nonnegative_result);
12644 }
12645 }
12646
12647 if (TargetRange.Width == LikelySourceRange->Width &&
12648 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
12649 Source->isSignedIntegerType()) {
12650 // Warn when doing a signed to signed conversion, warn if the positive
12651 // source value is exactly the width of the target type, which will
12652 // cause a negative value to be stored.
12653
12657 llvm::APSInt Value = Result.Val.getInt();
12658 if (isSameWidthConstantConversion(*this, E, T, CC)) {
12659 std::string PrettySourceValue = toString(Value, 10);
12660 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12661
12662 Diag(E->getExprLoc(),
12663 PDiag(diag::warn_impcast_integer_precision_constant)
12664 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12665 << E->getSourceRange() << SourceRange(CC));
12666 return;
12667 }
12668 }
12669
12670 // Fall through for non-constants to give a sign conversion warning.
12671 }
12672
12673 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
12674 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
12675 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
12676 LikelySourceRange->Width == TargetRange.Width))) {
12677 if (SourceMgr.isInSystemMacro(CC))
12678 return;
12679
12680 if (SourceBT && SourceBT->isInteger() && TargetBT &&
12681 TargetBT->isInteger() &&
12682 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
12683 return;
12684 }
12685
12686 unsigned DiagID = diag::warn_impcast_integer_sign;
12687
12688 // Traditionally, gcc has warned about this under -Wsign-compare.
12689 // We also want to warn about it in -Wconversion.
12690 // So if -Wconversion is off, use a completely identical diagnostic
12691 // in the sign-compare group.
12692 // The conditional-checking code will
12693 if (ICContext) {
12694 DiagID = diag::warn_impcast_integer_sign_conditional;
12695 *ICContext = true;
12696 }
12697
12698 DiagnoseImpCast(*this, E, T, CC, DiagID);
12699 }
12700
12701 // If we're implicitly converting from an integer into an enumeration, that
12702 // is valid in C but invalid in C++.
12703 QualType SourceType = E->getEnumCoercedType(Context);
12704 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
12705 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
12706 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
12707
12708 // Diagnose conversions between different enumeration types.
12709 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12710 // type, to give us better diagnostics.
12711 Source = Context.getCanonicalType(SourceType).getTypePtr();
12712
12713 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
12714 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
12715 if (SourceEnum->getOriginalDecl()->hasNameForLinkage() &&
12716 TargetEnum->getOriginalDecl()->hasNameForLinkage() &&
12717 SourceEnum != TargetEnum) {
12718 if (SourceMgr.isInSystemMacro(CC))
12719 return;
12720
12721 return DiagnoseImpCast(*this, E, SourceType, T, CC,
12722 diag::warn_impcast_different_enum_types);
12723 }
12724}
12725
12728
12730 SourceLocation CC, bool &ICContext) {
12731 E = E->IgnoreParenImpCasts();
12732 // Diagnose incomplete type for second or third operand in C.
12733 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
12734 S.RequireCompleteExprType(E, diag::err_incomplete_type);
12735
12736 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12737 return CheckConditionalOperator(S, CO, CC, T);
12738
12740 if (E->getType() != T)
12741 return S.CheckImplicitConversion(E, T, CC, &ICContext);
12742}
12743
12746 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12747
12748 Expr *TrueExpr = E->getTrueExpr();
12749 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12750 TrueExpr = BCO->getCommon();
12751
12752 bool Suspicious = false;
12753 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12754 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12755
12756 if (T->isBooleanType())
12758
12759 // If -Wconversion would have warned about either of the candidates
12760 // for a signedness conversion to the context type...
12761 if (!Suspicious) return;
12762
12763 // ...but it's currently ignored...
12764 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12765 return;
12766
12767 // ...then check whether it would have warned about either of the
12768 // candidates for a signedness conversion to the condition type.
12769 if (E->getType() == T) return;
12770
12771 Suspicious = false;
12773 &Suspicious);
12774 if (!Suspicious)
12775 S.CheckImplicitConversion(E->getFalseExpr()->IgnoreParenImpCasts(),
12776 E->getType(), CC, &Suspicious);
12777}
12778
12779/// Check conversion of given expression to boolean.
12780/// Input argument E is a logical expression.
12782 // Run the bool-like conversion checks only for C since there bools are
12783 // still not used as the return type from "boolean" operators or as the input
12784 // type for conditional operators.
12785 if (S.getLangOpts().CPlusPlus)
12786 return;
12788 return;
12790}
12791
12792namespace {
12793struct AnalyzeImplicitConversionsWorkItem {
12794 Expr *E;
12795 SourceLocation CC;
12796 bool IsListInit;
12797};
12798}
12799
12801 Sema &S, Expr *E, QualType T, SourceLocation CC,
12802 bool ExtraCheckForImplicitConversion,
12804 E = E->IgnoreParenImpCasts();
12805 WorkList.push_back({E, CC, false});
12806
12807 if (ExtraCheckForImplicitConversion && E->getType() != T)
12808 S.CheckImplicitConversion(E, T, CC);
12809}
12810
12811/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12812/// that should be visited are added to WorkList.
12814 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12816 Expr *OrigE = Item.E;
12817 SourceLocation CC = Item.CC;
12818
12819 QualType T = OrigE->getType();
12820 Expr *E = OrigE->IgnoreParenImpCasts();
12821
12822 // Propagate whether we are in a C++ list initialization expression.
12823 // If so, we do not issue warnings for implicit int-float conversion
12824 // precision loss, because C++11 narrowing already handles it.
12825 //
12826 // HLSL's initialization lists are special, so they shouldn't observe the C++
12827 // behavior here.
12828 bool IsListInit =
12829 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
12830 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
12831
12832 if (E->isTypeDependent() || E->isValueDependent())
12833 return;
12834
12835 Expr *SourceExpr = E;
12836 // Examine, but don't traverse into the source expression of an
12837 // OpaqueValueExpr, since it may have multiple parents and we don't want to
12838 // emit duplicate diagnostics. Its fine to examine the form or attempt to
12839 // evaluate it in the context of checking the specific conversion to T though.
12840 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12841 if (auto *Src = OVE->getSourceExpr())
12842 SourceExpr = Src;
12843
12844 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12845 if (UO->getOpcode() == UO_Not &&
12846 UO->getSubExpr()->isKnownToHaveBooleanValue())
12847 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12848 << OrigE->getSourceRange() << T->isBooleanType()
12849 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12850
12851 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
12852 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
12853 BO->getLHS()->isKnownToHaveBooleanValue() &&
12854 BO->getRHS()->isKnownToHaveBooleanValue() &&
12855 BO->getLHS()->HasSideEffects(S.Context) &&
12856 BO->getRHS()->HasSideEffects(S.Context)) {
12858 const LangOptions &LO = S.getLangOpts();
12859 SourceLocation BLoc = BO->getOperatorLoc();
12860 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
12861 StringRef SR = clang::Lexer::getSourceText(
12862 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
12863 // To reduce false positives, only issue the diagnostic if the operator
12864 // is explicitly spelled as a punctuator. This suppresses the diagnostic
12865 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
12866 // in C, along with other macro spellings the user might invent.
12867 if (SR.str() == "&" || SR.str() == "|") {
12868
12869 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
12870 << (BO->getOpcode() == BO_And ? "&" : "|")
12871 << OrigE->getSourceRange()
12873 BO->getOperatorLoc(),
12874 (BO->getOpcode() == BO_And ? "&&" : "||"));
12875 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
12876 }
12877 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
12878 /// Analyze the given comma operator. The basic idea behind the analysis
12879 /// is to analyze the left and right operands slightly differently. The
12880 /// left operand needs to check whether the operand itself has an implicit
12881 /// conversion, but not whether the left operand induces an implicit
12882 /// conversion for the entire comma expression itself. This is similar to
12883 /// how CheckConditionalOperand behaves; it's as-if the correct operand
12884 /// were directly used for the implicit conversion check.
12885 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
12886 /*ExtraCheckForImplicitConversion=*/false, WorkList);
12887 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
12888 /*ExtraCheckForImplicitConversion=*/true, WorkList);
12889 return;
12890 }
12891 }
12892
12893 // For conditional operators, we analyze the arguments as if they
12894 // were being fed directly into the output.
12895 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
12896 CheckConditionalOperator(S, CO, CC, T);
12897 return;
12898 }
12899
12900 // Check implicit argument conversions for function calls.
12901 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
12903
12904 // Go ahead and check any implicit conversions we might have skipped.
12905 // The non-canonical typecheck is just an optimization;
12906 // CheckImplicitConversion will filter out dead implicit conversions.
12907 if (SourceExpr->getType() != T)
12908 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
12909
12910 // Now continue drilling into this expression.
12911
12912 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12913 // The bound subexpressions in a PseudoObjectExpr are not reachable
12914 // as transitive children.
12915 // FIXME: Use a more uniform representation for this.
12916 for (auto *SE : POE->semantics())
12917 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12918 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
12919 }
12920
12921 // Skip past explicit casts.
12922 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12923 E = CE->getSubExpr()->IgnoreParenImpCasts();
12924 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12925 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12926 WorkList.push_back({E, CC, IsListInit});
12927 return;
12928 }
12929
12930 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
12931 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
12932 // The base expression is only used to initialize the parameter for
12933 // arguments to `inout` parameters, so we only traverse down the base
12934 // expression for `inout` cases.
12935 if (OutArgE->isInOut())
12936 WorkList.push_back(
12937 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
12938 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
12939 return;
12940 }
12941
12942 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12943 // Do a somewhat different check with comparison operators.
12944 if (BO->isComparisonOp())
12945 return AnalyzeComparison(S, BO);
12946
12947 // And with simple assignments.
12948 if (BO->getOpcode() == BO_Assign)
12949 return AnalyzeAssignment(S, BO);
12950 // And with compound assignments.
12951 if (BO->isAssignmentOp())
12952 return AnalyzeCompoundAssignment(S, BO);
12953 }
12954
12955 // These break the otherwise-useful invariant below. Fortunately,
12956 // we don't really need to recurse into them, because any internal
12957 // expressions should have been analyzed already when they were
12958 // built into statements.
12959 if (isa<StmtExpr>(E)) return;
12960
12961 // Don't descend into unevaluated contexts.
12962 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12963
12964 // Now just recurse over the expression's children.
12965 CC = E->getExprLoc();
12966 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12967 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12968 for (Stmt *SubStmt : E->children()) {
12969 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12970 if (!ChildExpr)
12971 continue;
12972
12973 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
12974 if (ChildExpr == CSE->getOperand())
12975 // Do not recurse over a CoroutineSuspendExpr's operand.
12976 // The operand is also a subexpression of getCommonExpr(), and
12977 // recursing into it directly would produce duplicate diagnostics.
12978 continue;
12979
12980 if (IsLogicalAndOperator &&
12981 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12982 // Ignore checking string literals that are in logical and operators.
12983 // This is a common pattern for asserts.
12984 continue;
12985 WorkList.push_back({ChildExpr, CC, IsListInit});
12986 }
12987
12988 if (BO && BO->isLogicalOp()) {
12989 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12990 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12991 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12992
12993 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12994 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12995 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12996 }
12997
12998 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12999 if (U->getOpcode() == UO_LNot) {
13000 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13001 } else if (U->getOpcode() != UO_AddrOf) {
13002 if (U->getSubExpr()->getType()->isAtomicType())
13003 S.Diag(U->getSubExpr()->getBeginLoc(),
13004 diag::warn_atomic_implicit_seq_cst);
13005 }
13006 }
13007}
13008
13009/// AnalyzeImplicitConversions - Find and report any interesting
13010/// implicit conversions in the given expression. There are a couple
13011/// of competing diagnostics here, -Wconversion and -Wsign-compare.
13013 bool IsListInit/*= false*/) {
13015 WorkList.push_back({OrigE, CC, IsListInit});
13016 while (!WorkList.empty())
13017 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13018}
13019
13020// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13021// Returns true when emitting a warning about taking the address of a reference.
13022static bool CheckForReference(Sema &SemaRef, const Expr *E,
13023 const PartialDiagnostic &PD) {
13024 E = E->IgnoreParenImpCasts();
13025
13026 const FunctionDecl *FD = nullptr;
13027
13028 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13029 if (!DRE->getDecl()->getType()->isReferenceType())
13030 return false;
13031 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13032 if (!M->getMemberDecl()->getType()->isReferenceType())
13033 return false;
13034 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13035 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13036 return false;
13037 FD = Call->getDirectCallee();
13038 } else {
13039 return false;
13040 }
13041
13042 SemaRef.Diag(E->getExprLoc(), PD);
13043
13044 // If possible, point to location of function.
13045 if (FD) {
13046 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13047 }
13048
13049 return true;
13050}
13051
13052// Returns true if the SourceLocation is expanded from any macro body.
13053// Returns false if the SourceLocation is invalid, is from not in a macro
13054// expansion, or is from expanded from a top-level macro argument.
13056 if (Loc.isInvalid())
13057 return false;
13058
13059 while (Loc.isMacroID()) {
13060 if (SM.isMacroBodyExpansion(Loc))
13061 return true;
13062 Loc = SM.getImmediateMacroCallerLoc(Loc);
13063 }
13064
13065 return false;
13066}
13067
13070 bool IsEqual, SourceRange Range) {
13071 if (!E)
13072 return;
13073
13074 // Don't warn inside macros.
13075 if (E->getExprLoc().isMacroID()) {
13077 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13079 return;
13080 }
13081 E = E->IgnoreImpCasts();
13082
13083 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13084
13085 if (isa<CXXThisExpr>(E)) {
13086 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13087 : diag::warn_this_bool_conversion;
13088 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13089 return;
13090 }
13091
13092 bool IsAddressOf = false;
13093
13094 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
13095 if (UO->getOpcode() != UO_AddrOf)
13096 return;
13097 IsAddressOf = true;
13098 E = UO->getSubExpr();
13099 }
13100
13101 if (IsAddressOf) {
13102 unsigned DiagID = IsCompare
13103 ? diag::warn_address_of_reference_null_compare
13104 : diag::warn_address_of_reference_bool_conversion;
13105 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13106 << IsEqual;
13107 if (CheckForReference(*this, E, PD)) {
13108 return;
13109 }
13110 }
13111
13112 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13113 bool IsParam = isa<NonNullAttr>(NonnullAttr);
13114 std::string Str;
13115 llvm::raw_string_ostream S(Str);
13116 E->printPretty(S, nullptr, getPrintingPolicy());
13117 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13118 : diag::warn_cast_nonnull_to_bool;
13119 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13120 << E->getSourceRange() << Range << IsEqual;
13121 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13122 };
13123
13124 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13125 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13126 if (auto *Callee = Call->getDirectCallee()) {
13127 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13128 ComplainAboutNonnullParamOrCall(A);
13129 return;
13130 }
13131 }
13132 }
13133
13134 // Complain if we are converting a lambda expression to a boolean value
13135 // outside of instantiation.
13136 if (!inTemplateInstantiation()) {
13137 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
13138 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
13139 MRecordDecl && MRecordDecl->isLambda()) {
13140 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
13141 << /*LambdaPointerConversionOperatorType=*/3
13142 << MRecordDecl->getSourceRange() << Range << IsEqual;
13143 return;
13144 }
13145 }
13146 }
13147
13148 // Expect to find a single Decl. Skip anything more complicated.
13149 ValueDecl *D = nullptr;
13150 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13151 D = R->getDecl();
13152 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13153 D = M->getMemberDecl();
13154 }
13155
13156 // Weak Decls can be null.
13157 if (!D || D->isWeak())
13158 return;
13159
13160 // Check for parameter decl with nonnull attribute
13161 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13162 if (getCurFunction() &&
13163 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13164 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13165 ComplainAboutNonnullParamOrCall(A);
13166 return;
13167 }
13168
13169 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13170 // Skip function template not specialized yet.
13172 return;
13173 auto ParamIter = llvm::find(FD->parameters(), PV);
13174 assert(ParamIter != FD->param_end());
13175 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13176
13177 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13178 if (!NonNull->args_size()) {
13179 ComplainAboutNonnullParamOrCall(NonNull);
13180 return;
13181 }
13182
13183 for (const ParamIdx &ArgNo : NonNull->args()) {
13184 if (ArgNo.getASTIndex() == ParamNo) {
13185 ComplainAboutNonnullParamOrCall(NonNull);
13186 return;
13187 }
13188 }
13189 }
13190 }
13191 }
13192 }
13193
13194 QualType T = D->getType();
13195 const bool IsArray = T->isArrayType();
13196 const bool IsFunction = T->isFunctionType();
13197
13198 // Address of function is used to silence the function warning.
13199 if (IsAddressOf && IsFunction) {
13200 return;
13201 }
13202
13203 // Found nothing.
13204 if (!IsAddressOf && !IsFunction && !IsArray)
13205 return;
13206
13207 // Pretty print the expression for the diagnostic.
13208 std::string Str;
13209 llvm::raw_string_ostream S(Str);
13210 E->printPretty(S, nullptr, getPrintingPolicy());
13211
13212 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13213 : diag::warn_impcast_pointer_to_bool;
13214 enum {
13215 AddressOf,
13216 FunctionPointer,
13217 ArrayPointer
13218 } DiagType;
13219 if (IsAddressOf)
13220 DiagType = AddressOf;
13221 else if (IsFunction)
13222 DiagType = FunctionPointer;
13223 else if (IsArray)
13224 DiagType = ArrayPointer;
13225 else
13226 llvm_unreachable("Could not determine diagnostic.");
13227 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13228 << Range << IsEqual;
13229
13230 if (!IsFunction)
13231 return;
13232
13233 // Suggest '&' to silence the function warning.
13234 Diag(E->getExprLoc(), diag::note_function_warning_silence)
13236
13237 // Check to see if '()' fixit should be emitted.
13238 QualType ReturnType;
13239 UnresolvedSet<4> NonTemplateOverloads;
13240 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13241 if (ReturnType.isNull())
13242 return;
13243
13244 if (IsCompare) {
13245 // There are two cases here. If there is null constant, the only suggest
13246 // for a pointer return type. If the null is 0, then suggest if the return
13247 // type is a pointer or an integer type.
13248 if (!ReturnType->isPointerType()) {
13249 if (NullKind == Expr::NPCK_ZeroExpression ||
13250 NullKind == Expr::NPCK_ZeroLiteral) {
13251 if (!ReturnType->isIntegerType())
13252 return;
13253 } else {
13254 return;
13255 }
13256 }
13257 } else { // !IsCompare
13258 // For function to bool, only suggest if the function pointer has bool
13259 // return type.
13260 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13261 return;
13262 }
13263 Diag(E->getExprLoc(), diag::note_function_to_function_call)
13265}
13266
13267void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13268 // Don't diagnose in unevaluated contexts.
13270 return;
13271
13272 // Don't diagnose for value- or type-dependent expressions.
13273 if (E->isTypeDependent() || E->isValueDependent())
13274 return;
13275
13276 // Check for array bounds violations in cases where the check isn't triggered
13277 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13278 // ArraySubscriptExpr is on the RHS of a variable initialization.
13279 CheckArrayAccess(E);
13280
13281 // This is not the right CC for (e.g.) a variable initialization.
13282 AnalyzeImplicitConversions(*this, E, CC);
13283}
13284
13285void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13286 ::CheckBoolLikeConversion(*this, E, CC);
13287}
13288
13289void Sema::CheckForIntOverflow (const Expr *E) {
13290 // Use a work list to deal with nested struct initializers.
13292
13293 do {
13294 const Expr *OriginalE = Exprs.pop_back_val();
13295 const Expr *E = OriginalE->IgnoreParenCasts();
13296
13297 if (isa<BinaryOperator, UnaryOperator>(E)) {
13299 continue;
13300 }
13301
13302 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
13303 Exprs.append(InitList->inits().begin(), InitList->inits().end());
13304 else if (isa<ObjCBoxedExpr>(OriginalE))
13306 else if (const auto *Call = dyn_cast<CallExpr>(E))
13307 Exprs.append(Call->arg_begin(), Call->arg_end());
13308 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
13309 Exprs.append(Message->arg_begin(), Message->arg_end());
13310 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
13311 Exprs.append(Construct->arg_begin(), Construct->arg_end());
13312 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
13313 Exprs.push_back(Temporary->getSubExpr());
13314 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
13315 Exprs.push_back(Array->getIdx());
13316 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
13317 Exprs.push_back(Compound->getInitializer());
13318 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
13319 New && New->isArray()) {
13320 if (auto ArraySize = New->getArraySize())
13321 Exprs.push_back(*ArraySize);
13322 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
13323 Exprs.push_back(MTE->getSubExpr());
13324 } while (!Exprs.empty());
13325}
13326
13327namespace {
13328
13329/// Visitor for expressions which looks for unsequenced operations on the
13330/// same object.
13331class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13333
13334 /// A tree of sequenced regions within an expression. Two regions are
13335 /// unsequenced if one is an ancestor or a descendent of the other. When we
13336 /// finish processing an expression with sequencing, such as a comma
13337 /// expression, we fold its tree nodes into its parent, since they are
13338 /// unsequenced with respect to nodes we will visit later.
13339 class SequenceTree {
13340 struct Value {
13341 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13342 unsigned Parent : 31;
13343 LLVM_PREFERRED_TYPE(bool)
13344 unsigned Merged : 1;
13345 };
13346 SmallVector<Value, 8> Values;
13347
13348 public:
13349 /// A region within an expression which may be sequenced with respect
13350 /// to some other region.
13351 class Seq {
13352 friend class SequenceTree;
13353
13354 unsigned Index;
13355
13356 explicit Seq(unsigned N) : Index(N) {}
13357
13358 public:
13359 Seq() : Index(0) {}
13360 };
13361
13362 SequenceTree() { Values.push_back(Value(0)); }
13363 Seq root() const { return Seq(0); }
13364
13365 /// Create a new sequence of operations, which is an unsequenced
13366 /// subset of \p Parent. This sequence of operations is sequenced with
13367 /// respect to other children of \p Parent.
13368 Seq allocate(Seq Parent) {
13369 Values.push_back(Value(Parent.Index));
13370 return Seq(Values.size() - 1);
13371 }
13372
13373 /// Merge a sequence of operations into its parent.
13374 void merge(Seq S) {
13375 Values[S.Index].Merged = true;
13376 }
13377
13378 /// Determine whether two operations are unsequenced. This operation
13379 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13380 /// should have been merged into its parent as appropriate.
13381 bool isUnsequenced(Seq Cur, Seq Old) {
13382 unsigned C = representative(Cur.Index);
13383 unsigned Target = representative(Old.Index);
13384 while (C >= Target) {
13385 if (C == Target)
13386 return true;
13387 C = Values[C].Parent;
13388 }
13389 return false;
13390 }
13391
13392 private:
13393 /// Pick a representative for a sequence.
13394 unsigned representative(unsigned K) {
13395 if (Values[K].Merged)
13396 // Perform path compression as we go.
13397 return Values[K].Parent = representative(Values[K].Parent);
13398 return K;
13399 }
13400 };
13401
13402 /// An object for which we can track unsequenced uses.
13403 using Object = const NamedDecl *;
13404
13405 /// Different flavors of object usage which we track. We only track the
13406 /// least-sequenced usage of each kind.
13407 enum UsageKind {
13408 /// A read of an object. Multiple unsequenced reads are OK.
13409 UK_Use,
13410
13411 /// A modification of an object which is sequenced before the value
13412 /// computation of the expression, such as ++n in C++.
13413 UK_ModAsValue,
13414
13415 /// A modification of an object which is not sequenced before the value
13416 /// computation of the expression, such as n++.
13417 UK_ModAsSideEffect,
13418
13419 UK_Count = UK_ModAsSideEffect + 1
13420 };
13421
13422 /// Bundle together a sequencing region and the expression corresponding
13423 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13424 struct Usage {
13425 const Expr *UsageExpr = nullptr;
13426 SequenceTree::Seq Seq;
13427
13428 Usage() = default;
13429 };
13430
13431 struct UsageInfo {
13432 Usage Uses[UK_Count];
13433
13434 /// Have we issued a diagnostic for this object already?
13435 bool Diagnosed = false;
13436
13437 UsageInfo();
13438 };
13439 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13440
13441 Sema &SemaRef;
13442
13443 /// Sequenced regions within the expression.
13444 SequenceTree Tree;
13445
13446 /// Declaration modifications and references which we have seen.
13447 UsageInfoMap UsageMap;
13448
13449 /// The region we are currently within.
13450 SequenceTree::Seq Region;
13451
13452 /// Filled in with declarations which were modified as a side-effect
13453 /// (that is, post-increment operations).
13454 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13455
13456 /// Expressions to check later. We defer checking these to reduce
13457 /// stack usage.
13459
13460 /// RAII object wrapping the visitation of a sequenced subexpression of an
13461 /// expression. At the end of this process, the side-effects of the evaluation
13462 /// become sequenced with respect to the value computation of the result, so
13463 /// we downgrade any UK_ModAsSideEffect within the evaluation to
13464 /// UK_ModAsValue.
13465 struct SequencedSubexpression {
13466 SequencedSubexpression(SequenceChecker &Self)
13467 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13468 Self.ModAsSideEffect = &ModAsSideEffect;
13469 }
13470
13471 ~SequencedSubexpression() {
13472 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13473 // Add a new usage with usage kind UK_ModAsValue, and then restore
13474 // the previous usage with UK_ModAsSideEffect (thus clearing it if
13475 // the previous one was empty).
13476 UsageInfo &UI = Self.UsageMap[M.first];
13477 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13478 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13479 SideEffectUsage = M.second;
13480 }
13481 Self.ModAsSideEffect = OldModAsSideEffect;
13482 }
13483
13484 SequenceChecker &Self;
13485 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13486 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13487 };
13488
13489 /// RAII object wrapping the visitation of a subexpression which we might
13490 /// choose to evaluate as a constant. If any subexpression is evaluated and
13491 /// found to be non-constant, this allows us to suppress the evaluation of
13492 /// the outer expression.
13493 class EvaluationTracker {
13494 public:
13495 EvaluationTracker(SequenceChecker &Self)
13496 : Self(Self), Prev(Self.EvalTracker) {
13497 Self.EvalTracker = this;
13498 }
13499
13500 ~EvaluationTracker() {
13501 Self.EvalTracker = Prev;
13502 if (Prev)
13503 Prev->EvalOK &= EvalOK;
13504 }
13505
13506 bool evaluate(const Expr *E, bool &Result) {
13507 if (!EvalOK || E->isValueDependent())
13508 return false;
13509 EvalOK = E->EvaluateAsBooleanCondition(
13510 Result, Self.SemaRef.Context,
13511 Self.SemaRef.isConstantEvaluatedContext());
13512 return EvalOK;
13513 }
13514
13515 private:
13516 SequenceChecker &Self;
13517 EvaluationTracker *Prev;
13518 bool EvalOK = true;
13519 } *EvalTracker = nullptr;
13520
13521 /// Find the object which is produced by the specified expression,
13522 /// if any.
13523 Object getObject(const Expr *E, bool Mod) const {
13524 E = E->IgnoreParenCasts();
13525 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13526 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13527 return getObject(UO->getSubExpr(), Mod);
13528 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13529 if (BO->getOpcode() == BO_Comma)
13530 return getObject(BO->getRHS(), Mod);
13531 if (Mod && BO->isAssignmentOp())
13532 return getObject(BO->getLHS(), Mod);
13533 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13534 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13535 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13536 return ME->getMemberDecl();
13537 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13538 // FIXME: If this is a reference, map through to its value.
13539 return DRE->getDecl();
13540 return nullptr;
13541 }
13542
13543 /// Note that an object \p O was modified or used by an expression
13544 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13545 /// the object \p O as obtained via the \p UsageMap.
13546 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13547 // Get the old usage for the given object and usage kind.
13548 Usage &U = UI.Uses[UK];
13549 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13550 // If we have a modification as side effect and are in a sequenced
13551 // subexpression, save the old Usage so that we can restore it later
13552 // in SequencedSubexpression::~SequencedSubexpression.
13553 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13554 ModAsSideEffect->push_back(std::make_pair(O, U));
13555 // Then record the new usage with the current sequencing region.
13556 U.UsageExpr = UsageExpr;
13557 U.Seq = Region;
13558 }
13559 }
13560
13561 /// Check whether a modification or use of an object \p O in an expression
13562 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13563 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13564 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13565 /// usage and false we are checking for a mod-use unsequenced usage.
13566 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13567 UsageKind OtherKind, bool IsModMod) {
13568 if (UI.Diagnosed)
13569 return;
13570
13571 const Usage &U = UI.Uses[OtherKind];
13572 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13573 return;
13574
13575 const Expr *Mod = U.UsageExpr;
13576 const Expr *ModOrUse = UsageExpr;
13577 if (OtherKind == UK_Use)
13578 std::swap(Mod, ModOrUse);
13579
13580 SemaRef.DiagRuntimeBehavior(
13581 Mod->getExprLoc(), {Mod, ModOrUse},
13582 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13583 : diag::warn_unsequenced_mod_use)
13584 << O << SourceRange(ModOrUse->getExprLoc()));
13585 UI.Diagnosed = true;
13586 }
13587
13588 // A note on note{Pre, Post}{Use, Mod}:
13589 //
13590 // (It helps to follow the algorithm with an expression such as
13591 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13592 // operations before C++17 and both are well-defined in C++17).
13593 //
13594 // When visiting a node which uses/modify an object we first call notePreUse
13595 // or notePreMod before visiting its sub-expression(s). At this point the
13596 // children of the current node have not yet been visited and so the eventual
13597 // uses/modifications resulting from the children of the current node have not
13598 // been recorded yet.
13599 //
13600 // We then visit the children of the current node. After that notePostUse or
13601 // notePostMod is called. These will 1) detect an unsequenced modification
13602 // as side effect (as in "k++ + k") and 2) add a new usage with the
13603 // appropriate usage kind.
13604 //
13605 // We also have to be careful that some operation sequences modification as
13606 // side effect as well (for example: || or ,). To account for this we wrap
13607 // the visitation of such a sub-expression (for example: the LHS of || or ,)
13608 // with SequencedSubexpression. SequencedSubexpression is an RAII object
13609 // which record usages which are modifications as side effect, and then
13610 // downgrade them (or more accurately restore the previous usage which was a
13611 // modification as side effect) when exiting the scope of the sequenced
13612 // subexpression.
13613
13614 void notePreUse(Object O, const Expr *UseExpr) {
13615 UsageInfo &UI = UsageMap[O];
13616 // Uses conflict with other modifications.
13617 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13618 }
13619
13620 void notePostUse(Object O, const Expr *UseExpr) {
13621 UsageInfo &UI = UsageMap[O];
13622 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13623 /*IsModMod=*/false);
13624 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13625 }
13626
13627 void notePreMod(Object O, const Expr *ModExpr) {
13628 UsageInfo &UI = UsageMap[O];
13629 // Modifications conflict with other modifications and with uses.
13630 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13631 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13632 }
13633
13634 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13635 UsageInfo &UI = UsageMap[O];
13636 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13637 /*IsModMod=*/true);
13638 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13639 }
13640
13641public:
13642 SequenceChecker(Sema &S, const Expr *E,
13644 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13645 Visit(E);
13646 // Silence a -Wunused-private-field since WorkList is now unused.
13647 // TODO: Evaluate if it can be used, and if not remove it.
13648 (void)this->WorkList;
13649 }
13650
13651 void VisitStmt(const Stmt *S) {
13652 // Skip all statements which aren't expressions for now.
13653 }
13654
13655 void VisitExpr(const Expr *E) {
13656 // By default, just recurse to evaluated subexpressions.
13657 Base::VisitStmt(E);
13658 }
13659
13660 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
13661 for (auto *Sub : CSE->children()) {
13662 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
13663 if (!ChildExpr)
13664 continue;
13665
13666 if (ChildExpr == CSE->getOperand())
13667 // Do not recurse over a CoroutineSuspendExpr's operand.
13668 // The operand is also a subexpression of getCommonExpr(), and
13669 // recursing into it directly could confuse object management
13670 // for the sake of sequence tracking.
13671 continue;
13672
13673 Visit(Sub);
13674 }
13675 }
13676
13677 void VisitCastExpr(const CastExpr *E) {
13678 Object O = Object();
13679 if (E->getCastKind() == CK_LValueToRValue)
13680 O = getObject(E->getSubExpr(), false);
13681
13682 if (O)
13683 notePreUse(O, E);
13684 VisitExpr(E);
13685 if (O)
13686 notePostUse(O, E);
13687 }
13688
13689 void VisitSequencedExpressions(const Expr *SequencedBefore,
13690 const Expr *SequencedAfter) {
13691 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13692 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13693 SequenceTree::Seq OldRegion = Region;
13694
13695 {
13696 SequencedSubexpression SeqBefore(*this);
13697 Region = BeforeRegion;
13698 Visit(SequencedBefore);
13699 }
13700
13701 Region = AfterRegion;
13702 Visit(SequencedAfter);
13703
13704 Region = OldRegion;
13705
13706 Tree.merge(BeforeRegion);
13707 Tree.merge(AfterRegion);
13708 }
13709
13710 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13711 // C++17 [expr.sub]p1:
13712 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13713 // expression E1 is sequenced before the expression E2.
13714 if (SemaRef.getLangOpts().CPlusPlus17)
13715 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13716 else {
13717 Visit(ASE->getLHS());
13718 Visit(ASE->getRHS());
13719 }
13720 }
13721
13722 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13723 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13724 void VisitBinPtrMem(const BinaryOperator *BO) {
13725 // C++17 [expr.mptr.oper]p4:
13726 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13727 // the expression E1 is sequenced before the expression E2.
13728 if (SemaRef.getLangOpts().CPlusPlus17)
13729 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13730 else {
13731 Visit(BO->getLHS());
13732 Visit(BO->getRHS());
13733 }
13734 }
13735
13736 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13737 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13738 void VisitBinShlShr(const BinaryOperator *BO) {
13739 // C++17 [expr.shift]p4:
13740 // The expression E1 is sequenced before the expression E2.
13741 if (SemaRef.getLangOpts().CPlusPlus17)
13742 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13743 else {
13744 Visit(BO->getLHS());
13745 Visit(BO->getRHS());
13746 }
13747 }
13748
13749 void VisitBinComma(const BinaryOperator *BO) {
13750 // C++11 [expr.comma]p1:
13751 // Every value computation and side effect associated with the left
13752 // expression is sequenced before every value computation and side
13753 // effect associated with the right expression.
13754 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13755 }
13756
13757 void VisitBinAssign(const BinaryOperator *BO) {
13758 SequenceTree::Seq RHSRegion;
13759 SequenceTree::Seq LHSRegion;
13760 if (SemaRef.getLangOpts().CPlusPlus17) {
13761 RHSRegion = Tree.allocate(Region);
13762 LHSRegion = Tree.allocate(Region);
13763 } else {
13764 RHSRegion = Region;
13765 LHSRegion = Region;
13766 }
13767 SequenceTree::Seq OldRegion = Region;
13768
13769 // C++11 [expr.ass]p1:
13770 // [...] the assignment is sequenced after the value computation
13771 // of the right and left operands, [...]
13772 //
13773 // so check it before inspecting the operands and update the
13774 // map afterwards.
13775 Object O = getObject(BO->getLHS(), /*Mod=*/true);
13776 if (O)
13777 notePreMod(O, BO);
13778
13779 if (SemaRef.getLangOpts().CPlusPlus17) {
13780 // C++17 [expr.ass]p1:
13781 // [...] The right operand is sequenced before the left operand. [...]
13782 {
13783 SequencedSubexpression SeqBefore(*this);
13784 Region = RHSRegion;
13785 Visit(BO->getRHS());
13786 }
13787
13788 Region = LHSRegion;
13789 Visit(BO->getLHS());
13790
13791 if (O && isa<CompoundAssignOperator>(BO))
13792 notePostUse(O, BO);
13793
13794 } else {
13795 // C++11 does not specify any sequencing between the LHS and RHS.
13796 Region = LHSRegion;
13797 Visit(BO->getLHS());
13798
13799 if (O && isa<CompoundAssignOperator>(BO))
13800 notePostUse(O, BO);
13801
13802 Region = RHSRegion;
13803 Visit(BO->getRHS());
13804 }
13805
13806 // C++11 [expr.ass]p1:
13807 // the assignment is sequenced [...] before the value computation of the
13808 // assignment expression.
13809 // C11 6.5.16/3 has no such rule.
13810 Region = OldRegion;
13811 if (O)
13812 notePostMod(O, BO,
13813 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13814 : UK_ModAsSideEffect);
13815 if (SemaRef.getLangOpts().CPlusPlus17) {
13816 Tree.merge(RHSRegion);
13817 Tree.merge(LHSRegion);
13818 }
13819 }
13820
13821 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13822 VisitBinAssign(CAO);
13823 }
13824
13825 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13826 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13827 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13828 Object O = getObject(UO->getSubExpr(), true);
13829 if (!O)
13830 return VisitExpr(UO);
13831
13832 notePreMod(O, UO);
13833 Visit(UO->getSubExpr());
13834 // C++11 [expr.pre.incr]p1:
13835 // the expression ++x is equivalent to x+=1
13836 notePostMod(O, UO,
13837 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13838 : UK_ModAsSideEffect);
13839 }
13840
13841 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13842 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13843 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13844 Object O = getObject(UO->getSubExpr(), true);
13845 if (!O)
13846 return VisitExpr(UO);
13847
13848 notePreMod(O, UO);
13849 Visit(UO->getSubExpr());
13850 notePostMod(O, UO, UK_ModAsSideEffect);
13851 }
13852
13853 void VisitBinLOr(const BinaryOperator *BO) {
13854 // C++11 [expr.log.or]p2:
13855 // If the second expression is evaluated, every value computation and
13856 // side effect associated with the first expression is sequenced before
13857 // every value computation and side effect associated with the
13858 // second expression.
13859 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13860 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13861 SequenceTree::Seq OldRegion = Region;
13862
13863 EvaluationTracker Eval(*this);
13864 {
13865 SequencedSubexpression Sequenced(*this);
13866 Region = LHSRegion;
13867 Visit(BO->getLHS());
13868 }
13869
13870 // C++11 [expr.log.or]p1:
13871 // [...] the second operand is not evaluated if the first operand
13872 // evaluates to true.
13873 bool EvalResult = false;
13874 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13875 bool ShouldVisitRHS = !EvalOK || !EvalResult;
13876 if (ShouldVisitRHS) {
13877 Region = RHSRegion;
13878 Visit(BO->getRHS());
13879 }
13880
13881 Region = OldRegion;
13882 Tree.merge(LHSRegion);
13883 Tree.merge(RHSRegion);
13884 }
13885
13886 void VisitBinLAnd(const BinaryOperator *BO) {
13887 // C++11 [expr.log.and]p2:
13888 // If the second expression is evaluated, every value computation and
13889 // side effect associated with the first expression is sequenced before
13890 // every value computation and side effect associated with the
13891 // second expression.
13892 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13893 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13894 SequenceTree::Seq OldRegion = Region;
13895
13896 EvaluationTracker Eval(*this);
13897 {
13898 SequencedSubexpression Sequenced(*this);
13899 Region = LHSRegion;
13900 Visit(BO->getLHS());
13901 }
13902
13903 // C++11 [expr.log.and]p1:
13904 // [...] the second operand is not evaluated if the first operand is false.
13905 bool EvalResult = false;
13906 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13907 bool ShouldVisitRHS = !EvalOK || EvalResult;
13908 if (ShouldVisitRHS) {
13909 Region = RHSRegion;
13910 Visit(BO->getRHS());
13911 }
13912
13913 Region = OldRegion;
13914 Tree.merge(LHSRegion);
13915 Tree.merge(RHSRegion);
13916 }
13917
13918 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13919 // C++11 [expr.cond]p1:
13920 // [...] Every value computation and side effect associated with the first
13921 // expression is sequenced before every value computation and side effect
13922 // associated with the second or third expression.
13923 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13924
13925 // No sequencing is specified between the true and false expression.
13926 // However since exactly one of both is going to be evaluated we can
13927 // consider them to be sequenced. This is needed to avoid warning on
13928 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13929 // both the true and false expressions because we can't evaluate x.
13930 // This will still allow us to detect an expression like (pre C++17)
13931 // "(x ? y += 1 : y += 2) = y".
13932 //
13933 // We don't wrap the visitation of the true and false expression with
13934 // SequencedSubexpression because we don't want to downgrade modifications
13935 // as side effect in the true and false expressions after the visition
13936 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13937 // not warn between the two "y++", but we should warn between the "y++"
13938 // and the "y".
13939 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13940 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13941 SequenceTree::Seq OldRegion = Region;
13942
13943 EvaluationTracker Eval(*this);
13944 {
13945 SequencedSubexpression Sequenced(*this);
13946 Region = ConditionRegion;
13947 Visit(CO->getCond());
13948 }
13949
13950 // C++11 [expr.cond]p1:
13951 // [...] The first expression is contextually converted to bool (Clause 4).
13952 // It is evaluated and if it is true, the result of the conditional
13953 // expression is the value of the second expression, otherwise that of the
13954 // third expression. Only one of the second and third expressions is
13955 // evaluated. [...]
13956 bool EvalResult = false;
13957 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13958 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
13959 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
13960 if (ShouldVisitTrueExpr) {
13961 Region = TrueRegion;
13962 Visit(CO->getTrueExpr());
13963 }
13964 if (ShouldVisitFalseExpr) {
13965 Region = FalseRegion;
13966 Visit(CO->getFalseExpr());
13967 }
13968
13969 Region = OldRegion;
13970 Tree.merge(ConditionRegion);
13971 Tree.merge(TrueRegion);
13972 Tree.merge(FalseRegion);
13973 }
13974
13975 void VisitCallExpr(const CallExpr *CE) {
13976 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13977
13978 if (CE->isUnevaluatedBuiltinCall(Context))
13979 return;
13980
13981 // C++11 [intro.execution]p15:
13982 // When calling a function [...], every value computation and side effect
13983 // associated with any argument expression, or with the postfix expression
13984 // designating the called function, is sequenced before execution of every
13985 // expression or statement in the body of the function [and thus before
13986 // the value computation of its result].
13987 SequencedSubexpression Sequenced(*this);
13988 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
13989 // C++17 [expr.call]p5
13990 // The postfix-expression is sequenced before each expression in the
13991 // expression-list and any default argument. [...]
13992 SequenceTree::Seq CalleeRegion;
13993 SequenceTree::Seq OtherRegion;
13994 if (SemaRef.getLangOpts().CPlusPlus17) {
13995 CalleeRegion = Tree.allocate(Region);
13996 OtherRegion = Tree.allocate(Region);
13997 } else {
13998 CalleeRegion = Region;
13999 OtherRegion = Region;
14000 }
14001 SequenceTree::Seq OldRegion = Region;
14002
14003 // Visit the callee expression first.
14004 Region = CalleeRegion;
14005 if (SemaRef.getLangOpts().CPlusPlus17) {
14006 SequencedSubexpression Sequenced(*this);
14007 Visit(CE->getCallee());
14008 } else {
14009 Visit(CE->getCallee());
14010 }
14011
14012 // Then visit the argument expressions.
14013 Region = OtherRegion;
14014 for (const Expr *Argument : CE->arguments())
14015 Visit(Argument);
14016
14017 Region = OldRegion;
14018 if (SemaRef.getLangOpts().CPlusPlus17) {
14019 Tree.merge(CalleeRegion);
14020 Tree.merge(OtherRegion);
14021 }
14022 });
14023 }
14024
14025 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14026 // C++17 [over.match.oper]p2:
14027 // [...] the operator notation is first transformed to the equivalent
14028 // function-call notation as summarized in Table 12 (where @ denotes one
14029 // of the operators covered in the specified subclause). However, the
14030 // operands are sequenced in the order prescribed for the built-in
14031 // operator (Clause 8).
14032 //
14033 // From the above only overloaded binary operators and overloaded call
14034 // operators have sequencing rules in C++17 that we need to handle
14035 // separately.
14036 if (!SemaRef.getLangOpts().CPlusPlus17 ||
14037 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14038 return VisitCallExpr(CXXOCE);
14039
14040 enum {
14041 NoSequencing,
14042 LHSBeforeRHS,
14043 RHSBeforeLHS,
14044 LHSBeforeRest
14045 } SequencingKind;
14046 switch (CXXOCE->getOperator()) {
14047 case OO_Equal:
14048 case OO_PlusEqual:
14049 case OO_MinusEqual:
14050 case OO_StarEqual:
14051 case OO_SlashEqual:
14052 case OO_PercentEqual:
14053 case OO_CaretEqual:
14054 case OO_AmpEqual:
14055 case OO_PipeEqual:
14056 case OO_LessLessEqual:
14057 case OO_GreaterGreaterEqual:
14058 SequencingKind = RHSBeforeLHS;
14059 break;
14060
14061 case OO_LessLess:
14062 case OO_GreaterGreater:
14063 case OO_AmpAmp:
14064 case OO_PipePipe:
14065 case OO_Comma:
14066 case OO_ArrowStar:
14067 case OO_Subscript:
14068 SequencingKind = LHSBeforeRHS;
14069 break;
14070
14071 case OO_Call:
14072 SequencingKind = LHSBeforeRest;
14073 break;
14074
14075 default:
14076 SequencingKind = NoSequencing;
14077 break;
14078 }
14079
14080 if (SequencingKind == NoSequencing)
14081 return VisitCallExpr(CXXOCE);
14082
14083 // This is a call, so all subexpressions are sequenced before the result.
14084 SequencedSubexpression Sequenced(*this);
14085
14086 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14087 assert(SemaRef.getLangOpts().CPlusPlus17 &&
14088 "Should only get there with C++17 and above!");
14089 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14090 "Should only get there with an overloaded binary operator"
14091 " or an overloaded call operator!");
14092
14093 if (SequencingKind == LHSBeforeRest) {
14094 assert(CXXOCE->getOperator() == OO_Call &&
14095 "We should only have an overloaded call operator here!");
14096
14097 // This is very similar to VisitCallExpr, except that we only have the
14098 // C++17 case. The postfix-expression is the first argument of the
14099 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14100 // are in the following arguments.
14101 //
14102 // Note that we intentionally do not visit the callee expression since
14103 // it is just a decayed reference to a function.
14104 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14105 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14106 SequenceTree::Seq OldRegion = Region;
14107
14108 assert(CXXOCE->getNumArgs() >= 1 &&
14109 "An overloaded call operator must have at least one argument"
14110 " for the postfix-expression!");
14111 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14112 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14113 CXXOCE->getNumArgs() - 1);
14114
14115 // Visit the postfix-expression first.
14116 {
14117 Region = PostfixExprRegion;
14118 SequencedSubexpression Sequenced(*this);
14119 Visit(PostfixExpr);
14120 }
14121
14122 // Then visit the argument expressions.
14123 Region = ArgsRegion;
14124 for (const Expr *Arg : Args)
14125 Visit(Arg);
14126
14127 Region = OldRegion;
14128 Tree.merge(PostfixExprRegion);
14129 Tree.merge(ArgsRegion);
14130 } else {
14131 assert(CXXOCE->getNumArgs() == 2 &&
14132 "Should only have two arguments here!");
14133 assert((SequencingKind == LHSBeforeRHS ||
14134 SequencingKind == RHSBeforeLHS) &&
14135 "Unexpected sequencing kind!");
14136
14137 // We do not visit the callee expression since it is just a decayed
14138 // reference to a function.
14139 const Expr *E1 = CXXOCE->getArg(0);
14140 const Expr *E2 = CXXOCE->getArg(1);
14141 if (SequencingKind == RHSBeforeLHS)
14142 std::swap(E1, E2);
14143
14144 return VisitSequencedExpressions(E1, E2);
14145 }
14146 });
14147 }
14148
14149 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14150 // This is a call, so all subexpressions are sequenced before the result.
14151 SequencedSubexpression Sequenced(*this);
14152
14153 if (!CCE->isListInitialization())
14154 return VisitExpr(CCE);
14155
14156 // In C++11, list initializations are sequenced.
14157 SequenceExpressionsInOrder(
14158 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
14159 }
14160
14161 void VisitInitListExpr(const InitListExpr *ILE) {
14162 if (!SemaRef.getLangOpts().CPlusPlus11)
14163 return VisitExpr(ILE);
14164
14165 // In C++11, list initializations are sequenced.
14166 SequenceExpressionsInOrder(ILE->inits());
14167 }
14168
14169 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
14170 // C++20 parenthesized list initializations are sequenced. See C++20
14171 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
14172 SequenceExpressionsInOrder(PLIE->getInitExprs());
14173 }
14174
14175private:
14176 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
14178 SequenceTree::Seq Parent = Region;
14179 for (const Expr *E : ExpressionList) {
14180 if (!E)
14181 continue;
14182 Region = Tree.allocate(Parent);
14183 Elts.push_back(Region);
14184 Visit(E);
14185 }
14186
14187 // Forget that the initializers are sequenced.
14188 Region = Parent;
14189 for (unsigned I = 0; I < Elts.size(); ++I)
14190 Tree.merge(Elts[I]);
14191 }
14192};
14193
14194SequenceChecker::UsageInfo::UsageInfo() = default;
14195
14196} // namespace
14197
14198void Sema::CheckUnsequencedOperations(const Expr *E) {
14200 WorkList.push_back(E);
14201 while (!WorkList.empty()) {
14202 const Expr *Item = WorkList.pop_back_val();
14203 SequenceChecker(*this, Item, WorkList);
14204 }
14205}
14206
14207void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14208 bool IsConstexpr) {
14210 IsConstexpr || isa<ConstantExpr>(E));
14211 CheckImplicitConversions(E, CheckLoc);
14213 CheckUnsequencedOperations(E);
14214 if (!IsConstexpr && !E->isValueDependent())
14215 CheckForIntOverflow(E);
14216}
14217
14218void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14219 FieldDecl *BitField,
14220 Expr *Init) {
14221 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14222}
14223
14226 if (!PType->isVariablyModifiedType())
14227 return;
14228 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14229 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14230 return;
14231 }
14232 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14233 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14234 return;
14235 }
14236 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14237 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14238 return;
14239 }
14240
14241 const ArrayType *AT = S.Context.getAsArrayType(PType);
14242 if (!AT)
14243 return;
14244
14247 return;
14248 }
14249
14250 S.Diag(Loc, diag::err_array_star_in_function_definition);
14251}
14252
14254 bool CheckParameterNames) {
14255 bool HasInvalidParm = false;
14256 for (ParmVarDecl *Param : Parameters) {
14257 assert(Param && "null in a parameter list");
14258 // C99 6.7.5.3p4: the parameters in a parameter type list in a
14259 // function declarator that is part of a function definition of
14260 // that function shall not have incomplete type.
14261 //
14262 // C++23 [dcl.fct.def.general]/p2
14263 // The type of a parameter [...] for a function definition
14264 // shall not be a (possibly cv-qualified) class type that is incomplete
14265 // or abstract within the function body unless the function is deleted.
14266 if (!Param->isInvalidDecl() &&
14267 (RequireCompleteType(Param->getLocation(), Param->getType(),
14268 diag::err_typecheck_decl_incomplete_type) ||
14269 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
14270 diag::err_abstract_type_in_decl,
14272 Param->setInvalidDecl();
14273 HasInvalidParm = true;
14274 }
14275
14276 // C99 6.9.1p5: If the declarator includes a parameter type list, the
14277 // declaration of each parameter shall include an identifier.
14278 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14279 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14280 // Diagnose this as an extension in C17 and earlier.
14281 if (!getLangOpts().C23)
14282 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
14283 }
14284
14285 // C99 6.7.5.3p12:
14286 // If the function declarator is not part of a definition of that
14287 // function, parameters may have incomplete type and may use the [*]
14288 // notation in their sequences of declarator specifiers to specify
14289 // variable length array types.
14290 QualType PType = Param->getOriginalType();
14291 // FIXME: This diagnostic should point the '[*]' if source-location
14292 // information is added for it.
14293 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14294
14295 // If the parameter is a c++ class type and it has to be destructed in the
14296 // callee function, declare the destructor so that it can be called by the
14297 // callee function. Do not perform any direct access check on the dtor here.
14298 if (!Param->isInvalidDecl()) {
14299 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14300 if (!ClassDecl->isInvalidDecl() &&
14301 !ClassDecl->hasIrrelevantDestructor() &&
14302 !ClassDecl->isDependentContext() &&
14303 ClassDecl->isParamDestroyedInCallee()) {
14305 MarkFunctionReferenced(Param->getLocation(), Destructor);
14306 DiagnoseUseOfDecl(Destructor, Param->getLocation());
14307 }
14308 }
14309 }
14310
14311 // Parameters with the pass_object_size attribute only need to be marked
14312 // constant at function definitions. Because we lack information about
14313 // whether we're on a declaration or definition when we're instantiating the
14314 // attribute, we need to check for constness here.
14315 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14316 if (!Param->getType().isConstQualified())
14317 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14318 << Attr->getSpelling() << 1;
14319
14320 // Check for parameter names shadowing fields from the class.
14321 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14322 // The owning context for the parameter should be the function, but we
14323 // want to see if this function's declaration context is a record.
14324 DeclContext *DC = Param->getDeclContext();
14325 if (DC && DC->isFunctionOrMethod()) {
14326 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14327 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14328 RD, /*DeclIsField*/ false);
14329 }
14330 }
14331
14332 if (!Param->isInvalidDecl() &&
14333 Param->getOriginalType()->isWebAssemblyTableType()) {
14334 Param->setInvalidDecl();
14335 HasInvalidParm = true;
14336 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
14337 }
14338 }
14339
14340 return HasInvalidParm;
14341}
14342
14343std::optional<std::pair<
14345 *E,
14347 &Ctx);
14348
14349/// Compute the alignment and offset of the base class object given the
14350/// derived-to-base cast expression and the alignment and offset of the derived
14351/// class object.
14352static std::pair<CharUnits, CharUnits>
14354 CharUnits BaseAlignment, CharUnits Offset,
14355 ASTContext &Ctx) {
14356 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14357 ++PathI) {
14358 const CXXBaseSpecifier *Base = *PathI;
14359 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14360 if (Base->isVirtual()) {
14361 // The complete object may have a lower alignment than the non-virtual
14362 // alignment of the base, in which case the base may be misaligned. Choose
14363 // the smaller of the non-virtual alignment and BaseAlignment, which is a
14364 // conservative lower bound of the complete object alignment.
14365 CharUnits NonVirtualAlignment =
14367 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14368 Offset = CharUnits::Zero();
14369 } else {
14370 const ASTRecordLayout &RL =
14371 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14372 Offset += RL.getBaseClassOffset(BaseDecl);
14373 }
14374 DerivedType = Base->getType();
14375 }
14376
14377 return std::make_pair(BaseAlignment, Offset);
14378}
14379
14380/// Compute the alignment and offset of a binary additive operator.
14381static std::optional<std::pair<CharUnits, CharUnits>>
14383 bool IsSub, ASTContext &Ctx) {
14384 QualType PointeeType = PtrE->getType()->getPointeeType();
14385
14386 if (!PointeeType->isConstantSizeType())
14387 return std::nullopt;
14388
14389 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14390
14391 if (!P)
14392 return std::nullopt;
14393
14394 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14395 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14396 CharUnits Offset = EltSize * IdxRes->getExtValue();
14397 if (IsSub)
14398 Offset = -Offset;
14399 return std::make_pair(P->first, P->second + Offset);
14400 }
14401
14402 // If the integer expression isn't a constant expression, compute the lower
14403 // bound of the alignment using the alignment and offset of the pointer
14404 // expression and the element size.
14405 return std::make_pair(
14406 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14407 CharUnits::Zero());
14408}
14409
14410/// This helper function takes an lvalue expression and returns the alignment of
14411/// a VarDecl and a constant offset from the VarDecl.
14412std::optional<std::pair<
14413 CharUnits,
14415 ASTContext &Ctx) {
14416 E = E->IgnoreParens();
14417 switch (E->getStmtClass()) {
14418 default:
14419 break;
14420 case Stmt::CStyleCastExprClass:
14421 case Stmt::CXXStaticCastExprClass:
14422 case Stmt::ImplicitCastExprClass: {
14423 auto *CE = cast<CastExpr>(E);
14424 const Expr *From = CE->getSubExpr();
14425 switch (CE->getCastKind()) {
14426 default:
14427 break;
14428 case CK_NoOp:
14429 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14430 case CK_UncheckedDerivedToBase:
14431 case CK_DerivedToBase: {
14432 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14433 if (!P)
14434 break;
14435 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14436 P->second, Ctx);
14437 }
14438 }
14439 break;
14440 }
14441 case Stmt::ArraySubscriptExprClass: {
14442 auto *ASE = cast<ArraySubscriptExpr>(E);
14444 false, Ctx);
14445 }
14446 case Stmt::DeclRefExprClass: {
14447 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14448 // FIXME: If VD is captured by copy or is an escaping __block variable,
14449 // use the alignment of VD's type.
14450 if (!VD->getType()->isReferenceType()) {
14451 // Dependent alignment cannot be resolved -> bail out.
14452 if (VD->hasDependentAlignment())
14453 break;
14454 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14455 }
14456 if (VD->hasInit())
14457 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14458 }
14459 break;
14460 }
14461 case Stmt::MemberExprClass: {
14462 auto *ME = cast<MemberExpr>(E);
14463 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14464 if (!FD || FD->getType()->isReferenceType() ||
14465 FD->getParent()->isInvalidDecl())
14466 break;
14467 std::optional<std::pair<CharUnits, CharUnits>> P;
14468 if (ME->isArrow())
14469 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14470 else
14471 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14472 if (!P)
14473 break;
14474 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14475 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14476 return std::make_pair(P->first,
14477 P->second + CharUnits::fromQuantity(Offset));
14478 }
14479 case Stmt::UnaryOperatorClass: {
14480 auto *UO = cast<UnaryOperator>(E);
14481 switch (UO->getOpcode()) {
14482 default:
14483 break;
14484 case UO_Deref:
14486 }
14487 break;
14488 }
14489 case Stmt::BinaryOperatorClass: {
14490 auto *BO = cast<BinaryOperator>(E);
14491 auto Opcode = BO->getOpcode();
14492 switch (Opcode) {
14493 default:
14494 break;
14495 case BO_Comma:
14497 }
14498 break;
14499 }
14500 }
14501 return std::nullopt;
14502}
14503
14504/// This helper function takes a pointer expression and returns the alignment of
14505/// a VarDecl and a constant offset from the VarDecl.
14506std::optional<std::pair<
14508 *E,
14510 &Ctx) {
14511 E = E->IgnoreParens();
14512 switch (E->getStmtClass()) {
14513 default:
14514 break;
14515 case Stmt::CStyleCastExprClass:
14516 case Stmt::CXXStaticCastExprClass:
14517 case Stmt::ImplicitCastExprClass: {
14518 auto *CE = cast<CastExpr>(E);
14519 const Expr *From = CE->getSubExpr();
14520 switch (CE->getCastKind()) {
14521 default:
14522 break;
14523 case CK_NoOp:
14524 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14525 case CK_ArrayToPointerDecay:
14526 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14527 case CK_UncheckedDerivedToBase:
14528 case CK_DerivedToBase: {
14529 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14530 if (!P)
14531 break;
14533 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14534 }
14535 }
14536 break;
14537 }
14538 case Stmt::CXXThisExprClass: {
14539 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14541 return std::make_pair(Alignment, CharUnits::Zero());
14542 }
14543 case Stmt::UnaryOperatorClass: {
14544 auto *UO = cast<UnaryOperator>(E);
14545 if (UO->getOpcode() == UO_AddrOf)
14547 break;
14548 }
14549 case Stmt::BinaryOperatorClass: {
14550 auto *BO = cast<BinaryOperator>(E);
14551 auto Opcode = BO->getOpcode();
14552 switch (Opcode) {
14553 default:
14554 break;
14555 case BO_Add:
14556 case BO_Sub: {
14557 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14558 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14559 std::swap(LHS, RHS);
14560 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14561 Ctx);
14562 }
14563 case BO_Comma:
14564 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14565 }
14566 break;
14567 }
14568 }
14569 return std::nullopt;
14570}
14571
14573 // See if we can compute the alignment of a VarDecl and an offset from it.
14574 std::optional<std::pair<CharUnits, CharUnits>> P =
14576
14577 if (P)
14578 return P->first.alignmentAtOffset(P->second);
14579
14580 // If that failed, return the type's alignment.
14582}
14583
14585 // This is actually a lot of work to potentially be doing on every
14586 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14587 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14588 return;
14589
14590 // Ignore dependent types.
14591 if (T->isDependentType() || Op->getType()->isDependentType())
14592 return;
14593
14594 // Require that the destination be a pointer type.
14595 const PointerType *DestPtr = T->getAs<PointerType>();
14596 if (!DestPtr) return;
14597
14598 // If the destination has alignment 1, we're done.
14599 QualType DestPointee = DestPtr->getPointeeType();
14600 if (DestPointee->isIncompleteType()) return;
14601 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14602 if (DestAlign.isOne()) return;
14603
14604 // Require that the source be a pointer type.
14605 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14606 if (!SrcPtr) return;
14607 QualType SrcPointee = SrcPtr->getPointeeType();
14608
14609 // Explicitly allow casts from cv void*. We already implicitly
14610 // allowed casts to cv void*, since they have alignment 1.
14611 // Also allow casts involving incomplete types, which implicitly
14612 // includes 'void'.
14613 if (SrcPointee->isIncompleteType()) return;
14614
14615 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14616
14617 if (SrcAlign >= DestAlign) return;
14618
14619 Diag(TRange.getBegin(), diag::warn_cast_align)
14620 << Op->getType() << T
14621 << static_cast<unsigned>(SrcAlign.getQuantity())
14622 << static_cast<unsigned>(DestAlign.getQuantity())
14623 << TRange << Op->getSourceRange();
14624}
14625
14626void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14627 const ArraySubscriptExpr *ASE,
14628 bool AllowOnePastEnd, bool IndexNegated) {
14629 // Already diagnosed by the constant evaluator.
14631 return;
14632
14633 IndexExpr = IndexExpr->IgnoreParenImpCasts();
14634 if (IndexExpr->isValueDependent())
14635 return;
14636
14637 const Type *EffectiveType =
14639 BaseExpr = BaseExpr->IgnoreParenCasts();
14640 const ConstantArrayType *ArrayTy =
14642
14644 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
14645
14646 const Type *BaseType =
14647 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14648 bool IsUnboundedArray =
14649 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
14650 Context, StrictFlexArraysLevel,
14651 /*IgnoreTemplateOrMacroSubstitution=*/true);
14652 if (EffectiveType->isDependentType() ||
14653 (!IsUnboundedArray && BaseType->isDependentType()))
14654 return;
14655
14658 return;
14659
14660 llvm::APSInt index = Result.Val.getInt();
14661 if (IndexNegated) {
14662 index.setIsUnsigned(false);
14663 index = -index;
14664 }
14665
14666 if (IsUnboundedArray) {
14667 if (EffectiveType->isFunctionType())
14668 return;
14669 if (index.isUnsigned() || !index.isNegative()) {
14670 const auto &ASTC = getASTContext();
14671 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
14672 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
14673 if (index.getBitWidth() < AddrBits)
14674 index = index.zext(AddrBits);
14675 std::optional<CharUnits> ElemCharUnits =
14676 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14677 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14678 // pointer) bounds-checking isn't meaningful.
14679 if (!ElemCharUnits || ElemCharUnits->isZero())
14680 return;
14681 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14682 // If index has more active bits than address space, we already know
14683 // we have a bounds violation to warn about. Otherwise, compute
14684 // address of (index + 1)th element, and warn about bounds violation
14685 // only if that address exceeds address space.
14686 if (index.getActiveBits() <= AddrBits) {
14687 bool Overflow;
14688 llvm::APInt Product(index);
14689 Product += 1;
14690 Product = Product.umul_ov(ElemBytes, Overflow);
14691 if (!Overflow && Product.getActiveBits() <= AddrBits)
14692 return;
14693 }
14694
14695 // Need to compute max possible elements in address space, since that
14696 // is included in diag message.
14697 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
14698 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
14699 MaxElems += 1;
14700 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
14701 MaxElems = MaxElems.udiv(ElemBytes);
14702
14703 unsigned DiagID =
14704 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
14705 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
14706
14707 // Diag message shows element size in bits and in "bytes" (platform-
14708 // dependent CharUnits)
14709 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14710 PDiag(DiagID)
14711 << toString(index, 10, true) << AddrBits
14712 << (unsigned)ASTC.toBits(*ElemCharUnits)
14713 << toString(ElemBytes, 10, false)
14714 << toString(MaxElems, 10, false)
14715 << (unsigned)MaxElems.getLimitedValue(~0U)
14716 << IndexExpr->getSourceRange());
14717
14718 const NamedDecl *ND = nullptr;
14719 // Try harder to find a NamedDecl to point at in the note.
14720 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14721 BaseExpr = ASE->getBase()->IgnoreParenCasts();
14722 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14723 ND = DRE->getDecl();
14724 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14725 ND = ME->getMemberDecl();
14726
14727 if (ND)
14728 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14729 PDiag(diag::note_array_declared_here) << ND);
14730 }
14731 return;
14732 }
14733
14734 if (index.isUnsigned() || !index.isNegative()) {
14735 // It is possible that the type of the base expression after
14736 // IgnoreParenCasts is incomplete, even though the type of the base
14737 // expression before IgnoreParenCasts is complete (see PR39746 for an
14738 // example). In this case we have no information about whether the array
14739 // access exceeds the array bounds. However we can still diagnose an array
14740 // access which precedes the array bounds.
14741 if (BaseType->isIncompleteType())
14742 return;
14743
14744 llvm::APInt size = ArrayTy->getSize();
14745
14746 if (BaseType != EffectiveType) {
14747 // Make sure we're comparing apples to apples when comparing index to
14748 // size.
14749 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14750 uint64_t array_typesize = Context.getTypeSize(BaseType);
14751
14752 // Handle ptrarith_typesize being zero, such as when casting to void*.
14753 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
14754 if (!ptrarith_typesize)
14755 ptrarith_typesize = Context.getCharWidth();
14756
14757 if (ptrarith_typesize != array_typesize) {
14758 // There's a cast to a different size type involved.
14759 uint64_t ratio = array_typesize / ptrarith_typesize;
14760
14761 // TODO: Be smarter about handling cases where array_typesize is not a
14762 // multiple of ptrarith_typesize.
14763 if (ptrarith_typesize * ratio == array_typesize)
14764 size *= llvm::APInt(size.getBitWidth(), ratio);
14765 }
14766 }
14767
14768 if (size.getBitWidth() > index.getBitWidth())
14769 index = index.zext(size.getBitWidth());
14770 else if (size.getBitWidth() < index.getBitWidth())
14771 size = size.zext(index.getBitWidth());
14772
14773 // For array subscripting the index must be less than size, but for pointer
14774 // arithmetic also allow the index (offset) to be equal to size since
14775 // computing the next address after the end of the array is legal and
14776 // commonly done e.g. in C++ iterators and range-based for loops.
14777 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14778 return;
14779
14780 // Suppress the warning if the subscript expression (as identified by the
14781 // ']' location) and the index expression are both from macro expansions
14782 // within a system header.
14783 if (ASE) {
14785 ASE->getRBracketLoc());
14786 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14787 SourceLocation IndexLoc =
14788 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14789 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14790 return;
14791 }
14792 }
14793
14794 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
14795 : diag::warn_ptr_arith_exceeds_bounds;
14796 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
14797 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
14798
14800 BaseExpr->getBeginLoc(), BaseExpr,
14801 PDiag(DiagID) << toString(index, 10, true) << ArrayTy->desugar()
14802 << CastMsg << CastMsgTy << IndexExpr->getSourceRange());
14803 } else {
14804 unsigned DiagID = diag::warn_array_index_precedes_bounds;
14805 if (!ASE) {
14806 DiagID = diag::warn_ptr_arith_precedes_bounds;
14807 if (index.isNegative()) index = -index;
14808 }
14809
14810 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14811 PDiag(DiagID) << toString(index, 10, true)
14812 << IndexExpr->getSourceRange());
14813 }
14814
14815 const NamedDecl *ND = nullptr;
14816 // Try harder to find a NamedDecl to point at in the note.
14817 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14818 BaseExpr = ASE->getBase()->IgnoreParenCasts();
14819 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14820 ND = DRE->getDecl();
14821 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14822 ND = ME->getMemberDecl();
14823
14824 if (ND)
14825 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14826 PDiag(diag::note_array_declared_here) << ND);
14827}
14828
14829void Sema::CheckArrayAccess(const Expr *expr) {
14830 int AllowOnePastEnd = 0;
14831 while (expr) {
14832 expr = expr->IgnoreParenImpCasts();
14833 switch (expr->getStmtClass()) {
14834 case Stmt::ArraySubscriptExprClass: {
14835 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
14836 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
14837 AllowOnePastEnd > 0);
14838 expr = ASE->getBase();
14839 break;
14840 }
14841 case Stmt::MemberExprClass: {
14842 expr = cast<MemberExpr>(expr)->getBase();
14843 break;
14844 }
14845 case Stmt::ArraySectionExprClass: {
14846 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
14847 // FIXME: We should probably be checking all of the elements to the
14848 // 'length' here as well.
14849 if (ASE->getLowerBound())
14850 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
14851 /*ASE=*/nullptr, AllowOnePastEnd > 0);
14852 return;
14853 }
14854 case Stmt::UnaryOperatorClass: {
14855 // Only unwrap the * and & unary operators
14856 const UnaryOperator *UO = cast<UnaryOperator>(expr);
14857 expr = UO->getSubExpr();
14858 switch (UO->getOpcode()) {
14859 case UO_AddrOf:
14860 AllowOnePastEnd++;
14861 break;
14862 case UO_Deref:
14863 AllowOnePastEnd--;
14864 break;
14865 default:
14866 return;
14867 }
14868 break;
14869 }
14870 case Stmt::ConditionalOperatorClass: {
14871 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
14872 if (const Expr *lhs = cond->getLHS())
14873 CheckArrayAccess(lhs);
14874 if (const Expr *rhs = cond->getRHS())
14875 CheckArrayAccess(rhs);
14876 return;
14877 }
14878 case Stmt::CXXOperatorCallExprClass: {
14879 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
14880 for (const auto *Arg : OCE->arguments())
14881 CheckArrayAccess(Arg);
14882 return;
14883 }
14884 default:
14885 return;
14886 }
14887 }
14888}
14889
14891 Expr *RHS, bool isProperty) {
14892 // Check if RHS is an Objective-C object literal, which also can get
14893 // immediately zapped in a weak reference. Note that we explicitly
14894 // allow ObjCStringLiterals, since those are designed to never really die.
14895 RHS = RHS->IgnoreParenImpCasts();
14896
14897 // This enum needs to match with the 'select' in
14898 // warn_objc_arc_literal_assign (off-by-1).
14900 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
14901 return false;
14902
14903 S.Diag(Loc, diag::warn_arc_literal_assign)
14904 << (unsigned) Kind
14905 << (isProperty ? 0 : 1)
14906 << RHS->getSourceRange();
14907
14908 return true;
14909}
14910
14913 Expr *RHS, bool isProperty) {
14914 // Strip off any implicit cast added to get to the one ARC-specific.
14915 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14916 if (cast->getCastKind() == CK_ARCConsumeObject) {
14917 S.Diag(Loc, diag::warn_arc_retained_assign)
14919 << (isProperty ? 0 : 1)
14920 << RHS->getSourceRange();
14921 return true;
14922 }
14923 RHS = cast->getSubExpr();
14924 }
14925
14926 if (LT == Qualifiers::OCL_Weak &&
14927 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
14928 return true;
14929
14930 return false;
14931}
14932
14934 QualType LHS, Expr *RHS) {
14936
14938 return false;
14939
14940 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
14941 return true;
14942
14943 return false;
14944}
14945
14947 Expr *LHS, Expr *RHS) {
14948 QualType LHSType;
14949 // PropertyRef on LHS type need be directly obtained from
14950 // its declaration as it has a PseudoType.
14952 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
14953 if (PRE && !PRE->isImplicitProperty()) {
14954 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14955 if (PD)
14956 LHSType = PD->getType();
14957 }
14958
14959 if (LHSType.isNull())
14960 LHSType = LHS->getType();
14961
14963
14964 if (LT == Qualifiers::OCL_Weak) {
14965 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
14967 }
14968
14969 if (checkUnsafeAssigns(Loc, LHSType, RHS))
14970 return;
14971
14972 // FIXME. Check for other life times.
14973 if (LT != Qualifiers::OCL_None)
14974 return;
14975
14976 if (PRE) {
14977 if (PRE->isImplicitProperty())
14978 return;
14979 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14980 if (!PD)
14981 return;
14982
14983 unsigned Attributes = PD->getPropertyAttributes();
14984 if (Attributes & ObjCPropertyAttribute::kind_assign) {
14985 // when 'assign' attribute was not explicitly specified
14986 // by user, ignore it and rely on property type itself
14987 // for lifetime info.
14988 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
14989 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
14990 LHSType->isObjCRetainableType())
14991 return;
14992
14993 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14994 if (cast->getCastKind() == CK_ARCConsumeObject) {
14995 Diag(Loc, diag::warn_arc_retained_property_assign)
14996 << RHS->getSourceRange();
14997 return;
14998 }
14999 RHS = cast->getSubExpr();
15000 }
15001 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15002 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15003 return;
15004 }
15005 }
15006}
15007
15008//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15009
15010static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15011 SourceLocation StmtLoc,
15012 const NullStmt *Body) {
15013 // Do not warn if the body is a macro that expands to nothing, e.g:
15014 //
15015 // #define CALL(x)
15016 // if (condition)
15017 // CALL(0);
15018 if (Body->hasLeadingEmptyMacro())
15019 return false;
15020
15021 // Get line numbers of statement and body.
15022 bool StmtLineInvalid;
15023 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15024 &StmtLineInvalid);
15025 if (StmtLineInvalid)
15026 return false;
15027
15028 bool BodyLineInvalid;
15029 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15030 &BodyLineInvalid);
15031 if (BodyLineInvalid)
15032 return false;
15033
15034 // Warn if null statement and body are on the same line.
15035 if (StmtLine != BodyLine)
15036 return false;
15037
15038 return true;
15039}
15040
15042 const Stmt *Body,
15043 unsigned DiagID) {
15044 // Since this is a syntactic check, don't emit diagnostic for template
15045 // instantiations, this just adds noise.
15047 return;
15048
15049 // The body should be a null statement.
15050 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15051 if (!NBody)
15052 return;
15053
15054 // Do the usual checks.
15055 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15056 return;
15057
15058 Diag(NBody->getSemiLoc(), DiagID);
15059 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15060}
15061
15063 const Stmt *PossibleBody) {
15064 assert(!CurrentInstantiationScope); // Ensured by caller
15065
15066 SourceLocation StmtLoc;
15067 const Stmt *Body;
15068 unsigned DiagID;
15069 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15070 StmtLoc = FS->getRParenLoc();
15071 Body = FS->getBody();
15072 DiagID = diag::warn_empty_for_body;
15073 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15074 StmtLoc = WS->getRParenLoc();
15075 Body = WS->getBody();
15076 DiagID = diag::warn_empty_while_body;
15077 } else
15078 return; // Neither `for' nor `while'.
15079
15080 // The body should be a null statement.
15081 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15082 if (!NBody)
15083 return;
15084
15085 // Skip expensive checks if diagnostic is disabled.
15086 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15087 return;
15088
15089 // Do the usual checks.
15090 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15091 return;
15092
15093 // `for(...);' and `while(...);' are popular idioms, so in order to keep
15094 // noise level low, emit diagnostics only if for/while is followed by a
15095 // CompoundStmt, e.g.:
15096 // for (int i = 0; i < n; i++);
15097 // {
15098 // a(i);
15099 // }
15100 // or if for/while is followed by a statement with more indentation
15101 // than for/while itself:
15102 // for (int i = 0; i < n; i++);
15103 // a(i);
15104 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15105 if (!ProbableTypo) {
15106 bool BodyColInvalid;
15107 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15108 PossibleBody->getBeginLoc(), &BodyColInvalid);
15109 if (BodyColInvalid)
15110 return;
15111
15112 bool StmtColInvalid;
15113 unsigned StmtCol =
15114 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15115 if (StmtColInvalid)
15116 return;
15117
15118 if (BodyCol > StmtCol)
15119 ProbableTypo = true;
15120 }
15121
15122 if (ProbableTypo) {
15123 Diag(NBody->getSemiLoc(), DiagID);
15124 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15125 }
15126}
15127
15128//===--- CHECK: Warn on self move with std::move. -------------------------===//
15129
15130void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15131 SourceLocation OpLoc) {
15132 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15133 return;
15134
15136 return;
15137
15138 // Strip parens and casts away.
15139 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15140 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15141
15142 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
15143 // which we can treat as an inlined std::move
15144 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
15145 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
15146 RHSExpr = CE->getArg(0);
15147 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
15148 CXXSCE && CXXSCE->isXValue())
15149 RHSExpr = CXXSCE->getSubExpr();
15150 else
15151 return;
15152
15153 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15154 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15155
15156 // Two DeclRefExpr's, check that the decls are the same.
15157 if (LHSDeclRef && RHSDeclRef) {
15158 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15159 return;
15160 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15161 RHSDeclRef->getDecl()->getCanonicalDecl())
15162 return;
15163
15164 auto D = Diag(OpLoc, diag::warn_self_move)
15165 << LHSExpr->getType() << LHSExpr->getSourceRange()
15166 << RHSExpr->getSourceRange();
15167 if (const FieldDecl *F =
15169 D << 1 << F
15170 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15171 else
15172 D << 0;
15173 return;
15174 }
15175
15176 // Member variables require a different approach to check for self moves.
15177 // MemberExpr's are the same if every nested MemberExpr refers to the same
15178 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15179 // the base Expr's are CXXThisExpr's.
15180 const Expr *LHSBase = LHSExpr;
15181 const Expr *RHSBase = RHSExpr;
15182 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15183 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15184 if (!LHSME || !RHSME)
15185 return;
15186
15187 while (LHSME && RHSME) {
15188 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15189 RHSME->getMemberDecl()->getCanonicalDecl())
15190 return;
15191
15192 LHSBase = LHSME->getBase();
15193 RHSBase = RHSME->getBase();
15194 LHSME = dyn_cast<MemberExpr>(LHSBase);
15195 RHSME = dyn_cast<MemberExpr>(RHSBase);
15196 }
15197
15198 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15199 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15200 if (LHSDeclRef && RHSDeclRef) {
15201 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15202 return;
15203 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15204 RHSDeclRef->getDecl()->getCanonicalDecl())
15205 return;
15206
15207 Diag(OpLoc, diag::warn_self_move)
15208 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15209 << RHSExpr->getSourceRange();
15210 return;
15211 }
15212
15213 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15214 Diag(OpLoc, diag::warn_self_move)
15215 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15216 << RHSExpr->getSourceRange();
15217}
15218
15219//===--- Layout compatibility ----------------------------------------------//
15220
15221static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
15222
15223/// Check if two enumeration types are layout-compatible.
15224static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
15225 const EnumDecl *ED2) {
15226 // C++11 [dcl.enum] p8:
15227 // Two enumeration types are layout-compatible if they have the same
15228 // underlying type.
15229 return ED1->isComplete() && ED2->isComplete() &&
15230 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15231}
15232
15233/// Check if two fields are layout-compatible.
15234/// Can be used on union members, which are exempt from alignment requirement
15235/// of common initial sequence.
15236static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
15237 const FieldDecl *Field2,
15238 bool AreUnionMembers = false) {
15239#ifndef NDEBUG
15240 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
15241 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
15242 assert(((Field1Parent->isStructureOrClassType() &&
15243 Field2Parent->isStructureOrClassType()) ||
15244 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
15245 "Can't evaluate layout compatibility between a struct field and a "
15246 "union field.");
15247 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
15248 (AreUnionMembers && Field1Parent->isUnionType())) &&
15249 "AreUnionMembers should be 'true' for union fields (only).");
15250#endif
15251
15252 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15253 return false;
15254
15255 if (Field1->isBitField() != Field2->isBitField())
15256 return false;
15257
15258 if (Field1->isBitField()) {
15259 // Make sure that the bit-fields are the same length.
15260 unsigned Bits1 = Field1->getBitWidthValue();
15261 unsigned Bits2 = Field2->getBitWidthValue();
15262
15263 if (Bits1 != Bits2)
15264 return false;
15265 }
15266
15267 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
15268 Field2->hasAttr<clang::NoUniqueAddressAttr>())
15269 return false;
15270
15271 if (!AreUnionMembers &&
15272 Field1->getMaxAlignment() != Field2->getMaxAlignment())
15273 return false;
15274
15275 return true;
15276}
15277
15278/// Check if two standard-layout structs are layout-compatible.
15279/// (C++11 [class.mem] p17)
15280static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
15281 const RecordDecl *RD2) {
15282 // Get to the class where the fields are declared
15283 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
15284 RD1 = D1CXX->getStandardLayoutBaseWithFields();
15285
15286 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
15287 RD2 = D2CXX->getStandardLayoutBaseWithFields();
15288
15289 // Check the fields.
15290 return llvm::equal(RD1->fields(), RD2->fields(),
15291 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
15292 return isLayoutCompatible(C, F1, F2);
15293 });
15294}
15295
15296/// Check if two standard-layout unions are layout-compatible.
15297/// (C++11 [class.mem] p18)
15298static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
15299 const RecordDecl *RD2) {
15300 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
15301 RD2->fields());
15302
15303 for (auto *Field1 : RD1->fields()) {
15304 auto I = UnmatchedFields.begin();
15305 auto E = UnmatchedFields.end();
15306
15307 for ( ; I != E; ++I) {
15308 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
15309 bool Result = UnmatchedFields.erase(*I);
15310 (void) Result;
15311 assert(Result);
15312 break;
15313 }
15314 }
15315 if (I == E)
15316 return false;
15317 }
15318
15319 return UnmatchedFields.empty();
15320}
15321
15322static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
15323 const RecordDecl *RD2) {
15324 if (RD1->isUnion() != RD2->isUnion())
15325 return false;
15326
15327 if (RD1->isUnion())
15328 return isLayoutCompatibleUnion(C, RD1, RD2);
15329 else
15330 return isLayoutCompatibleStruct(C, RD1, RD2);
15331}
15332
15333/// Check if two types are layout-compatible in C++11 sense.
15334static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
15335 if (T1.isNull() || T2.isNull())
15336 return false;
15337
15338 // C++20 [basic.types] p11:
15339 // Two types cv1 T1 and cv2 T2 are layout-compatible types
15340 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
15341 // or layout-compatible standard-layout class types (11.4).
15344
15345 if (C.hasSameType(T1, T2))
15346 return true;
15347
15348 const Type::TypeClass TC1 = T1->getTypeClass();
15349 const Type::TypeClass TC2 = T2->getTypeClass();
15350
15351 if (TC1 != TC2)
15352 return false;
15353
15354 if (TC1 == Type::Enum)
15355 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
15356 if (TC1 == Type::Record) {
15357 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15358 return false;
15359
15361 T2->castAsRecordDecl());
15362 }
15363
15364 return false;
15365}
15366
15368 return isLayoutCompatible(getASTContext(), T1, T2);
15369}
15370
15371//===-------------- Pointer interconvertibility ----------------------------//
15372
15374 const TypeSourceInfo *Derived) {
15375 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
15376 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
15377
15378 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
15379 getASTContext().hasSameType(BaseT, DerivedT))
15380 return true;
15381
15382 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
15383 return false;
15384
15385 // Per [basic.compound]/4.3, containing object has to be standard-layout.
15386 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
15387 return true;
15388
15389 return false;
15390}
15391
15392//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15393
15394/// Given a type tag expression find the type tag itself.
15395///
15396/// \param TypeExpr Type tag expression, as it appears in user's code.
15397///
15398/// \param VD Declaration of an identifier that appears in a type tag.
15399///
15400/// \param MagicValue Type tag magic value.
15401///
15402/// \param isConstantEvaluated whether the evalaution should be performed in
15403
15404/// constant context.
15405static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15406 const ValueDecl **VD, uint64_t *MagicValue,
15407 bool isConstantEvaluated) {
15408 while(true) {
15409 if (!TypeExpr)
15410 return false;
15411
15412 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15413
15414 switch (TypeExpr->getStmtClass()) {
15415 case Stmt::UnaryOperatorClass: {
15416 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15417 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15418 TypeExpr = UO->getSubExpr();
15419 continue;
15420 }
15421 return false;
15422 }
15423
15424 case Stmt::DeclRefExprClass: {
15425 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15426 *VD = DRE->getDecl();
15427 return true;
15428 }
15429
15430 case Stmt::IntegerLiteralClass: {
15431 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15432 llvm::APInt MagicValueAPInt = IL->getValue();
15433 if (MagicValueAPInt.getActiveBits() <= 64) {
15434 *MagicValue = MagicValueAPInt.getZExtValue();
15435 return true;
15436 } else
15437 return false;
15438 }
15439
15440 case Stmt::BinaryConditionalOperatorClass:
15441 case Stmt::ConditionalOperatorClass: {
15442 const AbstractConditionalOperator *ACO =
15443 cast<AbstractConditionalOperator>(TypeExpr);
15444 bool Result;
15445 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15446 isConstantEvaluated)) {
15447 if (Result)
15448 TypeExpr = ACO->getTrueExpr();
15449 else
15450 TypeExpr = ACO->getFalseExpr();
15451 continue;
15452 }
15453 return false;
15454 }
15455
15456 case Stmt::BinaryOperatorClass: {
15457 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15458 if (BO->getOpcode() == BO_Comma) {
15459 TypeExpr = BO->getRHS();
15460 continue;
15461 }
15462 return false;
15463 }
15464
15465 default:
15466 return false;
15467 }
15468 }
15469}
15470
15471/// Retrieve the C type corresponding to type tag TypeExpr.
15472///
15473/// \param TypeExpr Expression that specifies a type tag.
15474///
15475/// \param MagicValues Registered magic values.
15476///
15477/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15478/// kind.
15479///
15480/// \param TypeInfo Information about the corresponding C type.
15481///
15482/// \param isConstantEvaluated whether the evalaution should be performed in
15483/// constant context.
15484///
15485/// \returns true if the corresponding C type was found.
15487 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15488 const ASTContext &Ctx,
15489 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15490 *MagicValues,
15491 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15492 bool isConstantEvaluated) {
15493 FoundWrongKind = false;
15494
15495 // Variable declaration that has type_tag_for_datatype attribute.
15496 const ValueDecl *VD = nullptr;
15497
15498 uint64_t MagicValue;
15499
15500 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15501 return false;
15502
15503 if (VD) {
15504 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15505 if (I->getArgumentKind() != ArgumentKind) {
15506 FoundWrongKind = true;
15507 return false;
15508 }
15509 TypeInfo.Type = I->getMatchingCType();
15510 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15511 TypeInfo.MustBeNull = I->getMustBeNull();
15512 return true;
15513 }
15514 return false;
15515 }
15516
15517 if (!MagicValues)
15518 return false;
15519
15520 llvm::DenseMap<Sema::TypeTagMagicValue,
15521 Sema::TypeTagData>::const_iterator I =
15522 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15523 if (I == MagicValues->end())
15524 return false;
15525
15526 TypeInfo = I->second;
15527 return true;
15528}
15529
15531 uint64_t MagicValue, QualType Type,
15532 bool LayoutCompatible,
15533 bool MustBeNull) {
15534 if (!TypeTagForDatatypeMagicValues)
15535 TypeTagForDatatypeMagicValues.reset(
15536 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15537
15538 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15539 (*TypeTagForDatatypeMagicValues)[Magic] =
15540 TypeTagData(Type, LayoutCompatible, MustBeNull);
15541}
15542
15543static bool IsSameCharType(QualType T1, QualType T2) {
15544 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15545 if (!BT1)
15546 return false;
15547
15548 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15549 if (!BT2)
15550 return false;
15551
15552 BuiltinType::Kind T1Kind = BT1->getKind();
15553 BuiltinType::Kind T2Kind = BT2->getKind();
15554
15555 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
15556 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
15557 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15558 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15559}
15560
15561void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15562 const ArrayRef<const Expr *> ExprArgs,
15563 SourceLocation CallSiteLoc) {
15564 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15565 bool IsPointerAttr = Attr->getIsPointer();
15566
15567 // Retrieve the argument representing the 'type_tag'.
15568 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15569 if (TypeTagIdxAST >= ExprArgs.size()) {
15570 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15571 << 0 << Attr->getTypeTagIdx().getSourceIndex();
15572 return;
15573 }
15574 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15575 bool FoundWrongKind;
15576 TypeTagData TypeInfo;
15577 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15578 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15580 if (FoundWrongKind)
15581 Diag(TypeTagExpr->getExprLoc(),
15582 diag::warn_type_tag_for_datatype_wrong_kind)
15583 << TypeTagExpr->getSourceRange();
15584 return;
15585 }
15586
15587 // Retrieve the argument representing the 'arg_idx'.
15588 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15589 if (ArgumentIdxAST >= ExprArgs.size()) {
15590 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15591 << 1 << Attr->getArgumentIdx().getSourceIndex();
15592 return;
15593 }
15594 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15595 if (IsPointerAttr) {
15596 // Skip implicit cast of pointer to `void *' (as a function argument).
15597 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15598 if (ICE->getType()->isVoidPointerType() &&
15599 ICE->getCastKind() == CK_BitCast)
15600 ArgumentExpr = ICE->getSubExpr();
15601 }
15602 QualType ArgumentType = ArgumentExpr->getType();
15603
15604 // Passing a `void*' pointer shouldn't trigger a warning.
15605 if (IsPointerAttr && ArgumentType->isVoidPointerType())
15606 return;
15607
15608 if (TypeInfo.MustBeNull) {
15609 // Type tag with matching void type requires a null pointer.
15610 if (!ArgumentExpr->isNullPointerConstant(Context,
15612 Diag(ArgumentExpr->getExprLoc(),
15613 diag::warn_type_safety_null_pointer_required)
15614 << ArgumentKind->getName()
15615 << ArgumentExpr->getSourceRange()
15616 << TypeTagExpr->getSourceRange();
15617 }
15618 return;
15619 }
15620
15621 QualType RequiredType = TypeInfo.Type;
15622 if (IsPointerAttr)
15623 RequiredType = Context.getPointerType(RequiredType);
15624
15625 bool mismatch = false;
15626 if (!TypeInfo.LayoutCompatible) {
15627 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15628
15629 // C++11 [basic.fundamental] p1:
15630 // Plain char, signed char, and unsigned char are three distinct types.
15631 //
15632 // But we treat plain `char' as equivalent to `signed char' or `unsigned
15633 // char' depending on the current char signedness mode.
15634 if (mismatch)
15635 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15636 RequiredType->getPointeeType())) ||
15637 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15638 mismatch = false;
15639 } else
15640 if (IsPointerAttr)
15641 mismatch = !isLayoutCompatible(Context,
15642 ArgumentType->getPointeeType(),
15643 RequiredType->getPointeeType());
15644 else
15645 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15646
15647 if (mismatch)
15648 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15649 << ArgumentType << ArgumentKind
15650 << TypeInfo.LayoutCompatible << RequiredType
15651 << ArgumentExpr->getSourceRange()
15652 << TypeTagExpr->getSourceRange();
15653}
15654
15655void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15656 CharUnits Alignment) {
15657 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
15658 Alignment);
15659}
15660
15662 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
15663 const NamedDecl *ND = m.RD;
15664 if (ND->getName().empty()) {
15665 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15666 ND = TD;
15667 }
15668 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15669 << m.MD << ND << m.E->getSourceRange();
15670 }
15672}
15673
15675 E = E->IgnoreParens();
15676 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
15677 return;
15678 if (isa<UnaryOperator>(E) &&
15679 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15680 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15681 if (isa<MemberExpr>(Op)) {
15682 auto &MisalignedMembersForExpr =
15684 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
15685 if (MA != MisalignedMembersForExpr.end() &&
15686 (T->isDependentType() || T->isIntegerType() ||
15689 T->getPointeeType()) <= MA->Alignment))))
15690 MisalignedMembersForExpr.erase(MA);
15691 }
15692 }
15693}
15694
15696 Expr *E,
15697 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15698 Action) {
15699 const auto *ME = dyn_cast<MemberExpr>(E);
15700 if (!ME)
15701 return;
15702
15703 // No need to check expressions with an __unaligned-qualified type.
15705 return;
15706
15707 // For a chain of MemberExpr like "a.b.c.d" this list
15708 // will keep FieldDecl's like [d, c, b].
15709 SmallVector<FieldDecl *, 4> ReverseMemberChain;
15710 const MemberExpr *TopME = nullptr;
15711 bool AnyIsPacked = false;
15712 do {
15713 QualType BaseType = ME->getBase()->getType();
15714 if (BaseType->isDependentType())
15715 return;
15716 if (ME->isArrow())
15717 BaseType = BaseType->getPointeeType();
15718 auto *RD = BaseType->castAsRecordDecl();
15719 if (RD->isInvalidDecl())
15720 return;
15721
15722 ValueDecl *MD = ME->getMemberDecl();
15723 auto *FD = dyn_cast<FieldDecl>(MD);
15724 // We do not care about non-data members.
15725 if (!FD || FD->isInvalidDecl())
15726 return;
15727
15728 AnyIsPacked =
15729 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15730 ReverseMemberChain.push_back(FD);
15731
15732 TopME = ME;
15733 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15734 } while (ME);
15735 assert(TopME && "We did not compute a topmost MemberExpr!");
15736
15737 // Not the scope of this diagnostic.
15738 if (!AnyIsPacked)
15739 return;
15740
15741 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15742 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15743 // TODO: The innermost base of the member expression may be too complicated.
15744 // For now, just disregard these cases. This is left for future
15745 // improvement.
15746 if (!DRE && !isa<CXXThisExpr>(TopBase))
15747 return;
15748
15749 // Alignment expected by the whole expression.
15750 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15751
15752 // No need to do anything else with this case.
15753 if (ExpectedAlignment.isOne())
15754 return;
15755
15756 // Synthesize offset of the whole access.
15757 CharUnits Offset;
15758 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
15760
15761 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15762 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15763 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
15764
15765 // The base expression of the innermost MemberExpr may give
15766 // stronger guarantees than the class containing the member.
15767 if (DRE && !TopME->isArrow()) {
15768 const ValueDecl *VD = DRE->getDecl();
15769 if (!VD->getType()->isReferenceType())
15770 CompleteObjectAlignment =
15771 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15772 }
15773
15774 // Check if the synthesized offset fulfills the alignment.
15775 if (Offset % ExpectedAlignment != 0 ||
15776 // It may fulfill the offset it but the effective alignment may still be
15777 // lower than the expected expression alignment.
15778 CompleteObjectAlignment < ExpectedAlignment) {
15779 // If this happens, we want to determine a sensible culprit of this.
15780 // Intuitively, watching the chain of member expressions from right to
15781 // left, we start with the required alignment (as required by the field
15782 // type) but some packed attribute in that chain has reduced the alignment.
15783 // It may happen that another packed structure increases it again. But if
15784 // we are here such increase has not been enough. So pointing the first
15785 // FieldDecl that either is packed or else its RecordDecl is,
15786 // seems reasonable.
15787 FieldDecl *FD = nullptr;
15788 CharUnits Alignment;
15789 for (FieldDecl *FDI : ReverseMemberChain) {
15790 if (FDI->hasAttr<PackedAttr>() ||
15791 FDI->getParent()->hasAttr<PackedAttr>()) {
15792 FD = FDI;
15793 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
15796 break;
15797 }
15798 }
15799 assert(FD && "We did not find a packed FieldDecl!");
15800 Action(E, FD->getParent(), FD, Alignment);
15801 }
15802}
15803
15804void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15805 using namespace std::placeholders;
15806
15808 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15809 _2, _3, _4));
15810}
15811
15812// Performs a similar job to Sema::UsualUnaryConversions, but without any
15813// implicit promotion of integral/enumeration types.
15815 // First, convert to an r-value.
15817 if (Res.isInvalid())
15818 return ExprError();
15819
15820 // Promote floating-point types.
15821 return S.UsualUnaryFPConversions(Res.get());
15822}
15823
15825 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
15826 if (checkArgCount(TheCall, 1))
15827 return true;
15828
15829 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
15830 if (A.isInvalid())
15831 return true;
15832
15833 TheCall->setArg(0, A.get());
15834 QualType TyA = A.get()->getType();
15835
15836 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
15837 ArgTyRestr, 1))
15838 return true;
15839
15840 TheCall->setType(TyA);
15841 return false;
15842}
15843
15844bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
15845 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
15846 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
15847 TheCall->setType(*Res);
15848 return false;
15849 }
15850 return true;
15851}
15852
15854 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
15855 if (!Res)
15856 return true;
15857
15858 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
15859 TheCall->setType(VecTy0->getElementType());
15860 else
15861 TheCall->setType(*Res);
15862
15863 return false;
15864}
15865
15869 R = RHS->getEnumCoercedType(S.Context);
15870 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
15872 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
15873 << LHS->getSourceRange() << RHS->getSourceRange()
15874 << /*Arithmetic Between*/ 0 << L << R;
15875 }
15876 return false;
15877}
15878
15879/// Check if all arguments have the same type. If the types don't match, emit an
15880/// error message and return true. Otherwise return false.
15881///
15882/// For scalars we directly compare their unqualified types. But even if we
15883/// compare unqualified vector types, a difference in qualifiers in the element
15884/// types can make the vector types be considered not equal. For example,
15885/// vector of 4 'const float' values vs vector of 4 'float' values.
15886/// So we compare unqualified types of their elements and number of elements.
15888 ArrayRef<Expr *> Args) {
15889 assert(!Args.empty() && "Should have at least one argument.");
15890
15891 Expr *Arg0 = Args.front();
15892 QualType Ty0 = Arg0->getType();
15893
15894 auto EmitError = [&](Expr *ArgI) {
15895 SemaRef.Diag(Arg0->getBeginLoc(),
15896 diag::err_typecheck_call_different_arg_types)
15897 << Arg0->getType() << ArgI->getType();
15898 };
15899
15900 // Compare scalar types.
15901 if (!Ty0->isVectorType()) {
15902 for (Expr *ArgI : Args.drop_front())
15903 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
15904 EmitError(ArgI);
15905 return true;
15906 }
15907
15908 return false;
15909 }
15910
15911 // Compare vector types.
15912 const auto *Vec0 = Ty0->castAs<VectorType>();
15913 for (Expr *ArgI : Args.drop_front()) {
15914 const auto *VecI = ArgI->getType()->getAs<VectorType>();
15915 if (!VecI ||
15916 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
15917 VecI->getElementType()) ||
15918 Vec0->getNumElements() != VecI->getNumElements()) {
15919 EmitError(ArgI);
15920 return true;
15921 }
15922 }
15923
15924 return false;
15925}
15926
15927std::optional<QualType>
15929 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
15930 if (checkArgCount(TheCall, 2))
15931 return std::nullopt;
15932
15934 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
15935 return std::nullopt;
15936
15937 Expr *Args[2];
15938 for (int I = 0; I < 2; ++I) {
15939 ExprResult Converted =
15940 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
15941 if (Converted.isInvalid())
15942 return std::nullopt;
15943 Args[I] = Converted.get();
15944 }
15945
15946 SourceLocation LocA = Args[0]->getBeginLoc();
15947 QualType TyA = Args[0]->getType();
15948
15949 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
15950 return std::nullopt;
15951
15952 if (checkBuiltinVectorMathArgTypes(*this, Args))
15953 return std::nullopt;
15954
15955 TheCall->setArg(0, Args[0]);
15956 TheCall->setArg(1, Args[1]);
15957 return TyA;
15958}
15959
15961 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
15962 if (checkArgCount(TheCall, 3))
15963 return true;
15964
15965 SourceLocation Loc = TheCall->getExprLoc();
15966 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
15967 TheCall->getArg(1), Loc) ||
15968 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
15969 TheCall->getArg(2), Loc))
15970 return true;
15971
15972 Expr *Args[3];
15973 for (int I = 0; I < 3; ++I) {
15974 ExprResult Converted =
15975 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
15976 if (Converted.isInvalid())
15977 return true;
15978 Args[I] = Converted.get();
15979 }
15980
15981 int ArgOrdinal = 1;
15982 for (Expr *Arg : Args) {
15983 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
15984 ArgTyRestr, ArgOrdinal++))
15985 return true;
15986 }
15987
15988 if (checkBuiltinVectorMathArgTypes(*this, Args))
15989 return true;
15990
15991 for (int I = 0; I < 3; ++I)
15992 TheCall->setArg(I, Args[I]);
15993
15994 TheCall->setType(Args[0]->getType());
15995 return false;
15996}
15997
15998bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
15999 if (checkArgCount(TheCall, 1))
16000 return true;
16001
16002 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16003 if (A.isInvalid())
16004 return true;
16005
16006 TheCall->setArg(0, A.get());
16007 return false;
16008}
16009
16010bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
16011 if (checkArgCount(TheCall, 1))
16012 return true;
16013
16014 ExprResult Arg = TheCall->getArg(0);
16015 QualType TyArg = Arg.get()->getType();
16016
16017 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
16018 return Diag(TheCall->getArg(0)->getBeginLoc(),
16019 diag::err_builtin_invalid_arg_type)
16020 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
16021
16022 TheCall->setType(TyArg);
16023 return false;
16024}
16025
16026ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
16027 ExprResult CallResult) {
16028 if (checkArgCount(TheCall, 1))
16029 return ExprError();
16030
16031 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16032 if (MatrixArg.isInvalid())
16033 return MatrixArg;
16034 Expr *Matrix = MatrixArg.get();
16035
16036 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16037 if (!MType) {
16038 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16039 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
16040 << Matrix->getType();
16041 return ExprError();
16042 }
16043
16044 // Create returned matrix type by swapping rows and columns of the argument
16045 // matrix type.
16047 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16048
16049 // Change the return type to the type of the returned matrix.
16050 TheCall->setType(ResultType);
16051
16052 // Update call argument to use the possibly converted matrix argument.
16053 TheCall->setArg(0, Matrix);
16054 return CallResult;
16055}
16056
16057// Get and verify the matrix dimensions.
16058static std::optional<unsigned>
16060 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
16061 if (!Value) {
16062 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16063 << Name;
16064 return {};
16065 }
16066 uint64_t Dim = Value->getZExtValue();
16068 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16070 return {};
16071 }
16072 return Dim;
16073}
16074
16075ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16076 ExprResult CallResult) {
16077 if (!getLangOpts().MatrixTypes) {
16078 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16079 return ExprError();
16080 }
16081
16082 if (checkArgCount(TheCall, 4))
16083 return ExprError();
16084
16085 unsigned PtrArgIdx = 0;
16086 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16087 Expr *RowsExpr = TheCall->getArg(1);
16088 Expr *ColumnsExpr = TheCall->getArg(2);
16089 Expr *StrideExpr = TheCall->getArg(3);
16090
16091 bool ArgError = false;
16092
16093 // Check pointer argument.
16094 {
16096 if (PtrConv.isInvalid())
16097 return PtrConv;
16098 PtrExpr = PtrConv.get();
16099 TheCall->setArg(0, PtrExpr);
16100 if (PtrExpr->isTypeDependent()) {
16101 TheCall->setType(Context.DependentTy);
16102 return TheCall;
16103 }
16104 }
16105
16106 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16107 QualType ElementTy;
16108 if (!PtrTy) {
16109 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16110 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
16111 << PtrExpr->getType();
16112 ArgError = true;
16113 } else {
16114 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16115
16117 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16118 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
16119 << /* no fp */ 0 << PtrExpr->getType();
16120 ArgError = true;
16121 }
16122 }
16123
16124 // Apply default Lvalue conversions and convert the expression to size_t.
16125 auto ApplyArgumentConversions = [this](Expr *E) {
16127 if (Conv.isInvalid())
16128 return Conv;
16129
16130 return tryConvertExprToType(Conv.get(), Context.getSizeType());
16131 };
16132
16133 // Apply conversion to row and column expressions.
16134 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16135 if (!RowsConv.isInvalid()) {
16136 RowsExpr = RowsConv.get();
16137 TheCall->setArg(1, RowsExpr);
16138 } else
16139 RowsExpr = nullptr;
16140
16141 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16142 if (!ColumnsConv.isInvalid()) {
16143 ColumnsExpr = ColumnsConv.get();
16144 TheCall->setArg(2, ColumnsExpr);
16145 } else
16146 ColumnsExpr = nullptr;
16147
16148 // If any part of the result matrix type is still pending, just use
16149 // Context.DependentTy, until all parts are resolved.
16150 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16151 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16152 TheCall->setType(Context.DependentTy);
16153 return CallResult;
16154 }
16155
16156 // Check row and column dimensions.
16157 std::optional<unsigned> MaybeRows;
16158 if (RowsExpr)
16159 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16160
16161 std::optional<unsigned> MaybeColumns;
16162 if (ColumnsExpr)
16163 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16164
16165 // Check stride argument.
16166 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16167 if (StrideConv.isInvalid())
16168 return ExprError();
16169 StrideExpr = StrideConv.get();
16170 TheCall->setArg(3, StrideExpr);
16171
16172 if (MaybeRows) {
16173 if (std::optional<llvm::APSInt> Value =
16174 StrideExpr->getIntegerConstantExpr(Context)) {
16175 uint64_t Stride = Value->getZExtValue();
16176 if (Stride < *MaybeRows) {
16177 Diag(StrideExpr->getBeginLoc(),
16178 diag::err_builtin_matrix_stride_too_small);
16179 ArgError = true;
16180 }
16181 }
16182 }
16183
16184 if (ArgError || !MaybeRows || !MaybeColumns)
16185 return ExprError();
16186
16187 TheCall->setType(
16188 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16189 return CallResult;
16190}
16191
16192ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16193 ExprResult CallResult) {
16194 if (checkArgCount(TheCall, 3))
16195 return ExprError();
16196
16197 unsigned PtrArgIdx = 1;
16198 Expr *MatrixExpr = TheCall->getArg(0);
16199 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16200 Expr *StrideExpr = TheCall->getArg(2);
16201
16202 bool ArgError = false;
16203
16204 {
16205 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16206 if (MatrixConv.isInvalid())
16207 return MatrixConv;
16208 MatrixExpr = MatrixConv.get();
16209 TheCall->setArg(0, MatrixExpr);
16210 }
16211 if (MatrixExpr->isTypeDependent()) {
16212 TheCall->setType(Context.DependentTy);
16213 return TheCall;
16214 }
16215
16216 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16217 if (!MatrixTy) {
16218 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16219 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
16220 ArgError = true;
16221 }
16222
16223 {
16225 if (PtrConv.isInvalid())
16226 return PtrConv;
16227 PtrExpr = PtrConv.get();
16228 TheCall->setArg(1, PtrExpr);
16229 if (PtrExpr->isTypeDependent()) {
16230 TheCall->setType(Context.DependentTy);
16231 return TheCall;
16232 }
16233 }
16234
16235 // Check pointer argument.
16236 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16237 if (!PtrTy) {
16238 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16239 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
16240 << PtrExpr->getType();
16241 ArgError = true;
16242 } else {
16243 QualType ElementTy = PtrTy->getPointeeType();
16244 if (ElementTy.isConstQualified()) {
16245 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16246 ArgError = true;
16247 }
16248 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16249 if (MatrixTy &&
16250 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16251 Diag(PtrExpr->getBeginLoc(),
16252 diag::err_builtin_matrix_pointer_arg_mismatch)
16253 << ElementTy << MatrixTy->getElementType();
16254 ArgError = true;
16255 }
16256 }
16257
16258 // Apply default Lvalue conversions and convert the stride expression to
16259 // size_t.
16260 {
16261 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16262 if (StrideConv.isInvalid())
16263 return StrideConv;
16264
16265 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16266 if (StrideConv.isInvalid())
16267 return StrideConv;
16268 StrideExpr = StrideConv.get();
16269 TheCall->setArg(2, StrideExpr);
16270 }
16271
16272 // Check stride argument.
16273 if (MatrixTy) {
16274 if (std::optional<llvm::APSInt> Value =
16275 StrideExpr->getIntegerConstantExpr(Context)) {
16276 uint64_t Stride = Value->getZExtValue();
16277 if (Stride < MatrixTy->getNumRows()) {
16278 Diag(StrideExpr->getBeginLoc(),
16279 diag::err_builtin_matrix_stride_too_small);
16280 ArgError = true;
16281 }
16282 }
16283 }
16284
16285 if (ArgError)
16286 return ExprError();
16287
16288 return CallResult;
16289}
16290
16292 const NamedDecl *Callee) {
16293 // This warning does not make sense in code that has no runtime behavior.
16295 return;
16296
16297 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
16298
16299 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
16300 return;
16301
16302 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16303 // all TCBs the callee is a part of.
16304 llvm::StringSet<> CalleeTCBs;
16305 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
16306 CalleeTCBs.insert(A->getTCBName());
16307 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
16308 CalleeTCBs.insert(A->getTCBName());
16309
16310 // Go through the TCBs the caller is a part of and emit warnings if Caller
16311 // is in a TCB that the Callee is not.
16312 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
16313 StringRef CallerTCB = A->getTCBName();
16314 if (CalleeTCBs.count(CallerTCB) == 0) {
16315 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
16316 << Callee << CallerTCB;
16317 }
16318 }
16319}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3597
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.
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:630
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1192
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
unsigned Iter
Definition: HTMLLogger.cpp:153
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
#define SM(sm)
Definition: OffloadArch.cpp:16
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 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 builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall)
static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call)
static StringLiteralCheckType checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString, const Expr *E, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, bool InFunctionCall, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset, bool IgnoreStringsWithoutSpecifiers=false)
static bool IsSameFloatAfterCast(const llvm::APFloat &value, const llvm::fltSemantics &Src, const llvm::fltSemantics &Tgt)
Checks whether the given value, which currently has the given source semantics, has the same value wh...
static 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)
CFIUncheckedCalleeChange
@ Discarding
@ Adding
static QualType GetExprType(const Expr *E)
static CFIUncheckedCalleeChange AdjustingCFIUncheckedCallee(QualType From, QualType To)
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 bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant, Expr *Other, const llvm::APSInt &Value, bool RhsConstant)
static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex, bool ToBool)
static AbsoluteValueKind getAbsoluteValueKind(QualType T)
static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, const IdentifierInfo *FnName, SourceLocation FnLoc, SourceLocation RParenLoc)
Takes the expression passed to the size_t parameter of functions such as memcmp, strncat,...
static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall)
static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref, ArrayRef< EquatableFormatArgument > RefArgs, const StringLiteral *Fmt, ArrayRef< EquatableFormatArgument > FmtArgs, const Expr *FmtExpr, bool InFunctionCall)
static ExprResult BuiltinTriviallyRelocate(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 void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, bool inFunctionCall, VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, bool IgnoreStringsWithoutSpecifiers)
static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg, unsigned Pos)
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 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 bool isKnownToHaveUnsignedValue(const Expr *E)
static bool checkBuiltinVectorMathArgTypes(Sema &SemaRef, ArrayRef< Expr * > Args)
Check if all arguments have the same type.
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)
static ExprResult BuiltinMaskedStore(Sema &S, CallExpr *TheCall)
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 ExprResult BuiltinVectorMathConversions(Sema &S, Expr *E)
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 IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth)
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 bool IsEnumConstOrFromMacro(Sema &S, const 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 ExprResult BuiltinMaskedLoad(Sema &S, CallExpr *TheCall)
static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall, SourceLocation CC)
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 void CheckCommaOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool ExtraCheckForImplicitConversion, llvm::SmallVectorImpl< AnalyzeImplicitConversionsWorkItem > &WorkList)
static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T, SourceLocation CContext)
Diagnose an implicit cast from a floating point value to an integer value.
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 bool IsInfinityFunction(const FunctionDecl *FDecl)
static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType, QualType T, SourceLocation CContext, unsigned diag, bool PruneControlFlow=false)
Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
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 ExprResult GetVTablePointer(Sema &S, CallExpr *Call)
static bool requiresParensToAddCast(const Expr *E)
static bool HasEnumType(const Expr *E)
static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call)
static ExprResult BuiltinInvoke(Sema &S, CallExpr *TheCall)
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 void DiagnoseMixedUnicodeImplicitConversion(Sema &S, const Type *Source, const Type *Target, Expr *E, QualType T, SourceLocation CC)
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 checkBuiltinVerboseTrap(CallExpr *Call, Sema &S)
static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy, Sema::EltwiseBuiltinArgTyRestriction ArgTyRestr, int ArgOrdinal)
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 checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
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 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 BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall)
static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, ParmVarDecl **LastParam=nullptr)
This file declares semantic analysis for DirectX constructs.
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:753
SourceLocation Loc
Definition: SemaObjC.cpp:754
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 for SPIRV constructs.
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.
NestedNameSpecifier Specifier
std::string Label
__DEVICE__ int min(int __a, int __b)
__device__ int
__device__ __2f16 float __ockl_bool s
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
APSInt & getInt()
Definition: APValue.h:489
bool isVector() const
Definition: APValue.h:473
APSInt & getComplexIntImag()
Definition: APValue.h:527
bool isComplexInt() const
Definition: APValue.h:470
bool isFloat() const
Definition: APValue.h:468
bool isComplexFloat() const
Definition: APValue.h:471
APValue & getVectorElt(unsigned I)
Definition: APValue.h:563
unsigned getVectorLength() const
Definition: APValue.h:571
bool isLValue() const
Definition: APValue.h:472
bool isInt() const
Definition: APValue.h:467
APSInt & getComplexIntReal()
Definition: APValue.h:519
APFloat & getComplexFloatImag()
Definition: APValue.h:543
APFloat & getComplexFloatReal()
Definition: APValue.h:535
APFloat & getFloat()
Definition: APValue.h:503
bool isAddrLabelDiff() const
Definition: APValue.h:478
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:3056
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.
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:2851
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2867
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:1249
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:1250
IdentifierTable & Idents
Definition: ASTContext.h:740
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:742
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:1223
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:860
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 CharTy
Definition: ASTContext.h:1224
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CanQualType IntTy
Definition: ASTContext.h:1231
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:793
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:2898
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:2625
CanQualType BuiltinFnTy
Definition: ASTContext.h:1252
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1222
CanQualType UnsignedIntTy
Definition: ASTContext.h:1232
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
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:1232
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:1750
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.
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:859
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
CanQualType getNSIntegerType() const
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
@ GE_None
No error.
Definition: ASTContext.h:2536
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:2629
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:201
CharUnits getNonVirtualAlignment() const
getNonVirtualAlignment - Get the non-virtual alignment (in chars) of an object, which is the alignmen...
Definition: RecordLayout.h:219
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:250
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition: Expr.h:4289
Expr * getCond() const
getCond - Return the expression representing the condition for the ?: operator.
Definition: Expr.h:4467
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition: Expr.h:4473
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition: Expr.h:4479
PtrTy get() const
Definition: Ownership.h:171
bool isInvalid() const
Definition: Ownership.h:167
bool isUsable() const
Definition: Ownership.h:169
This class represents BOTH the OpenMP Array Section and OpenACC 'subarray', with a boolean differenti...
Definition: Expr.h:7092
Expr * getBase()
Get base of the array section.
Definition: Expr.h:7158
Expr * getLowerBound()
Get lower bound of array section.
Definition: Expr.h:7162
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2723
SourceLocation getRBracketLoc() const
Definition: Expr.h:2771
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition: Expr.h:2752
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: TypeBase.h:3738
ArraySizeModifier getSizeModifier() const
Definition: TypeBase.h:3752
QualType getElementType() const
Definition: TypeBase.h:3750
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition: Expr.h:6816
std::unique_ptr< AtomicScopeModel > getScopeModel() const
Get atomic scope model.
Definition: Expr.h:6966
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:6932
Attr - This represents one attribute.
Definition: Attr.h:44
const char * getSpelling() const
Type source information for an attributed type.
Definition: TypeLoc.h:1017
const T * getAttrAs()
Definition: TypeLoc.h:1047
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition: TypeLoc.h:1031
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: TypeBase.h:7180
TemplateDecl * getTypeConstraintConcept() const
Definition: TypeBase.h:7195
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3974
static bool isLogicalOp(Opcode Opc)
Definition: Expr.h:4107
Expr * getLHS() const
Definition: Expr.h:4024
SourceLocation getExprLoc() const
Definition: Expr.h:4015
Expr * getRHS() const
Definition: Expr.h:4026
bool isEqualityOp() const
Definition: Expr.h:4072
static bool isAdditiveOp(Opcode Opc)
Definition: Expr.h:4060
Opcode getOpcode() const
Definition: Expr.h:4019
A fixed int type of a specified bitwidth.
Definition: TypeBase.h:8195
Pointer to a block type.
Definition: TypeBase.h:3558
This class is used for builtin types like 'int'.
Definition: TypeBase.h:3182
bool isInteger() const
Definition: TypeBase.h:3243
bool isFloatingPoint() const
Definition: TypeBase.h:3255
bool isSignedInteger() const
Definition: TypeBase.h:3247
bool isUnsignedInteger() const
Definition: TypeBase.h:3251
Kind getKind() const
Definition: TypeBase.h:3230
std::string getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition: Builtins.cpp:85
bool isAuxBuiltinID(unsigned ID) const
Return true if the builtin ID belongs exclusively to the AuxTarget, and false if it belongs to both p...
Definition: Builtins.h:414
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:375
unsigned getAuxBuiltinID(unsigned ID) const
Return real builtin ID (i.e.
Definition: Builtins.h:420
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:264
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.cpp:80
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition: Expr.h:3905
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1549
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition: ExprCXX.h:1631
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition: ExprCXX.h:1689
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2869
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2129
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:84
SourceLocation getExprLoc() const LLVM_READONLY
Definition: ExprCXX.h:154
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition: ExprCXX.h:114
Represents a list-initialization with parenthesis.
Definition: ExprCXX.h:5135
MutableArrayRef< Expr * > getInitExprs()
Definition: ExprCXX.h:5175
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition: DeclCXX.h:1225
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1214
bool isDynamicClass() const
Definition: DeclCXX.h:574
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:73
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2879
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3083
SourceLocation getBeginLoc() const
Definition: Expr.h:3213
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:3096
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition: Expr.cpp:1588
arg_iterator arg_begin()
Definition: Expr.h:3136
arg_iterator arg_end()
Definition: Expr.h:3139
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3062
bool isCallToStdMove() const
Definition: Expr.cpp:3578
Expr * getCallee()
Definition: Expr.h:3026
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:3070
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition: Expr.h:3172
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:3073
arg_range arguments()
Definition: Expr.h:3131
SourceLocation getEndLoc() const
Definition: Expr.h:3232
SourceLocation getRParenLoc() const
Definition: Expr.h:3210
Decl * getCalleeDecl()
Definition: Expr.h:3056
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:1593
void setCallee(Expr *F)
Definition: Expr.h:3028
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:3612
path_iterator path_begin()
Definition: Expr.h:3682
CastKind getCastKind() const
Definition: Expr.h:3656
path_iterator path_end()
Definition: Expr.h:3683
Expr * getSubExpr()
Definition: Expr.h:3662
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: TypeBase.h:3293
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:4236
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4327
Expr * getLHS() const
Definition: Expr.h:4361
Expr * getRHS() const
Definition: Expr.h:4362
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition: TypeBase.h:3776
QualType desugar() const
Definition: TypeBase.h:3877
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: TypeBase.h:3832
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:346
Represents a concrete matrix type with constant number of rows and columns.
Definition: TypeBase.h:4389
static constexpr unsigned getMaxElementsPerDimension()
Returns the maximum number of elements per dimension.
Definition: TypeBase.h:4423
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition: TypeBase.h:4418
static ConvertVectorExpr * Create(const ASTContext &C, Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType, ExprValueKind VK, ExprObjectKind OK, SourceLocation BuiltinLoc, SourceLocation RParenLoc, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:5486
Represents an expression that might suspend coroutine execution; either a co_await or co_yield expres...
Definition: ExprCXX.h:5249
Expr * getOperand() const
Definition: ExprCXX.h:5318
child_range children()
Definition: ExprCXX.h:5348
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition: TypeBase.h:3454
DynamicCountPointerKind getKind() const
Definition: TypeBase.h:3484
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:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2109
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1358
bool isStdNamespace() const
Definition: DeclBase.cpp:1342
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2373
bool isFunctionOrMethod() const
Definition: DeclBase.h:2161
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1272
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:484
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition: Expr.h:1365
ValueDecl * getDecl()
Definition: Expr.h:1340
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition: Expr.h:1470
SourceLocation getBeginLoc() const
Definition: Expr.h:1351
SourceLocation getLocation() const
Definition: Expr.h:1348
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isInStdNamespace() const
Definition: DeclBase.cpp:427
T * getAttr() const
Definition: DeclBase.h:573
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition: DeclBase.cpp:538
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
Definition: DeclBase.cpp:1199
bool isInvalidDecl() const
Definition: DeclBase.h:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:559
SourceLocation getLocation() const
Definition: DeclBase.h:439
DeclContext * getDeclContext()
Definition: DeclBase.h:448
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:431
bool hasAttr() const
Definition: DeclBase.h:577
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:978
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:427
The name of a declaration.
std::string getAsString() const
Retrieve the human-readable string for this name.
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1988
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:808
RAII class that determines when any errors have occurred between the time the instance was created an...
Definition: Diagnostic.h:1076
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Definition: Diagnostic.h:1088
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:231
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:950
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3416
Represents an enum.
Definition: Decl.h:4000
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4223
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4164
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: TypeBase.h:6522
This represents one expression.
Definition: Expr.h:112
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:674
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition: Expr.h:671
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3078
void setType(QualType t)
Definition: Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:444
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:194
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:3073
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3061
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition: Expr.h:246
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:3069
bool isFlexibleArrayMemberLike(const 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:202
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...
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:284
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4164
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:833
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:837
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:3065
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:3624
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:223
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:3053
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition: Expr.h:804
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition: Expr.h:813
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:816
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition: Expr.h:806
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:4001
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition: Expr.cpp:262
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition: Expr.h:461
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:273
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition: Expr.h:464
QualType getType() const
Definition: Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:523
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:222
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:133
void EvaluateForOverflow(const ASTContext &Ctx) const
ExtVectorType - Extended vector type.
Definition: TypeBase.h:4283
Represents a member of a struct/union/class.
Definition: Decl.h:3153
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3256
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4689
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3389
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition: Decl.h:3269
const FieldDecl * findCountedByField() const
Find the FieldDecl specified in a FAM's "counted_by" attribute.
Definition: Decl.cpp:4792
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:78
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:139
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:128
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:102
llvm::APFloat getValue() const
Definition: Expr.h:1668
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition: Stmt.h:2891
Represents a function declaration or definition.
Definition: Decl.h:1999
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition: Decl.cpp:4490
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2790
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3699
param_iterator param_end()
Definition: Decl.h:2780
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3802
QualType getReturnType() const
Definition: Decl.h:2838
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2767
param_iterator param_begin()
Definition: Decl.h:2779
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3125
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4266
bool isStatic() const
Definition: Decl.h:2922
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:4081
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:4067
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3763
Represents a prototype with parameter type info, e.g.
Definition: TypeBase.h:5282
unsigned getNumParams() const
Definition: TypeBase.h:5560
QualType getParamType(unsigned i) const
Definition: TypeBase.h:5562
bool isVariadic() const
Whether this function prototype is variadic.
Definition: TypeBase.h:5686
ExtProtoInfo getExtProtoInfo() const
Definition: TypeBase.h:5571
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: TypeBase.h:5681
ArrayRef< QualType > getParamTypes() const
Definition: TypeBase.h:5567
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: TypeBase.h:4478
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition: TypeBase.h:4787
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition: TypeBase.h:4783
QualType getReturnType() const
Definition: TypeBase.h:4818
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:3789
Describes an C or C++ initializer list.
Definition: Expr.h:5235
ArrayRef< Expr * > inits()
Definition: Expr.h:5285
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:971
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:434
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:1020
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:1056
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:1103
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:848
Represents the results of name lookup.
Definition: Lookup.h:147
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:569
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:636
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: TypeBase.h:4374
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3300
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3383
Expr * getBase() const
Definition: Expr.h:3377
bool isArrow() const
Definition: Expr.h:3484
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: TypeBase.h:3669
This represents a decl that may have a name.
Definition: Decl.h:273
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:294
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:300
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:339
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1206
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1930
Represent a C++ namespace.
Definition: Decl.h:591
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition: Stmt.h:1694
bool hasLeadingEmptyMacro() const
Definition: Stmt.h:1708
SourceLocation getSemiLoc() const
Definition: Stmt.h:1705
Represents an ObjC class declaration.
Definition: DeclObjC.h:1154
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:731
QualType getType() const
Definition: DeclObjC.h:804
ObjCPropertyAttribute::Kind getPropertyAttributesAsWritten() const
Definition: DeclObjC.h:827
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition: DeclObjC.h:815
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition: ExprObjC.h:616
ObjCPropertyDecl * getExplicitProperty() const
Definition: ExprObjC.h:705
bool isImplicitProperty() const
Definition: ExprObjC.h:702
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:52
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1180
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:256
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2184
Represents a parameter to a function.
Definition: Decl.h:1789
Pointer-authentication qualifiers.
Definition: TypeBase.h:152
bool isAddressDiscriminated() const
Definition: TypeBase.h:265
@ MaxDiscriminator
The maximum supported pointer-authentication discriminator.
Definition: TypeBase.h:232
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: TypeBase.h:3346
QualType getPointeeType() const
Definition: TypeBase.h:3356
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6692
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition: Expr.cpp:5032
A (possibly-)qualified type.
Definition: TypeBase.h:937
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2871
PointerAuthQualifier getPointerAuth() const
Definition: TypeBase.h:1453
PrimitiveDefaultInitializeKind
Definition: TypeBase.h:1463
QualType withoutLocalFastQualifiers() const
Definition: TypeBase.h:1214
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: TypeBase.h:8343
LangAS getAddressSpace() const
Return the address space of this type.
Definition: TypeBase.h:8469
bool isConstant(const ASTContext &Ctx) const
Definition: TypeBase.h:1097
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: TypeBase.h:8383
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: TypeBase.h:1438
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
Definition: TypeBase.h:8395
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: TypeBase.h:8437
void removeLocalVolatile()
Definition: TypeBase.h:8459
QualType withCVRQualifiers(unsigned CVR) const
Definition: TypeBase.h:1179
void removeLocalConst()
Definition: TypeBase.h:8451
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: TypeBase.h:8416
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: TypeBase.h:8464
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: TypeBase.h:8389
bool hasNonTrivialObjCLifetime() const
Definition: TypeBase.h:1442
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition: TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: TypeBase.h:367
bool hasUnaligned() const
Definition: TypeBase.h:511
Represents a struct/union/class.
Definition: Decl.h:4305
bool isNonTrivialToPrimitiveCopy() const
Definition: Decl.h:4391
field_range fields() const
Definition: Decl.h:4508
RecordDecl * getMostRecentDecl()
Definition: Decl.h:4331
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition: Decl.h:4383
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: TypeBase.h:6502
RecordDecl * getOriginalDecl() const
Definition: TypeBase.h:6509
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:1012
@ 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:1093
bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaBPF.cpp:105
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:111
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:61
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:33
bool CheckDirectXBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaDirectX.cpp:18
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:2356
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
void adornBoolConversionDiagWithTernaryFixit(const Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder)
Definition: SemaObjC.cpp:2312
bool isSignedCharBool(QualType Ty)
Definition: SemaObjC.cpp:2307
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:2270
void checkDictionaryLiteral(QualType TargetType, ObjCDictionaryLiteral *DictionaryLiteral)
Check an Objective-C dictionary literal being converted to the given target type.
Definition: SemaObjC.cpp:2381
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:95
void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg)
Definition: SemaPPC.cpp:30
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc)
Definition: SemaPPC.cpp:262
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaRISCV.cpp:554
bool CheckSPIRVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaSPIRV.cpp:183
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaSystemZ.cpp:24
bool CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaWasm.cpp:283
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaX86.cpp:543
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:850
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:14886
bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const
Returns true if From is a function or pointer to a function with the cfi_unchecked_callee attribute b...
SemaAMDGPU & AMDGPU()
Definition: Sema.h:1413
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:12930
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:1113
std::optional< QualType > BuiltinVectorMath(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::None)
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Unary Operators. 'Tok' is the token for the operator.
Definition: SemaExpr.cpp:16078
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
Definition: Sema.cpp:2639
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9281
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:9289
@ LookupAnyName
Look up any declaration with any name.
Definition: Sema.h:9326
bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount)
Checks that a call expression's argument count is at most the desired number.
bool checkPointerAuthDiscriminatorArg(Expr *Arg, PointerAuthDiscArgKind Kind, unsigned &IntVal)
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.
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
Definition: SemaExpr.cpp:5786
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:1642
void CheckFloatComparison(SourceLocation Loc, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
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...
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition: Sema.h:6882
bool CheckFormatStringsCompatible(FormatStringType FST, const StringLiteral *AuthoritativeFormatString, const StringLiteral *TestedFormatString, const Expr *FunctionCallArg=nullptr)
Verify that two format strings (as understood by attribute(format) and attribute(format_matches) are ...
bool IsCXXTriviallyRelocatableType(QualType T)
Determines if a type is trivially relocatable according to the C++26 rules.
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:2042
SemaHexagon & Hexagon()
Definition: Sema.h:1453
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:1647
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition: SemaExpr.cpp:827
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
SemaX86 & X86()
Definition: Sema.h:1543
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
Definition: SemaExpr.cpp:1052
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
Definition: SemaExpr.cpp:5075
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:14492
ASTContext & Context
Definition: Sema.h:1276
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:915
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:1483
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:748
ASTContext & getASTContext() const
Definition: Sema.h:918
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:16034
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:756
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition: Sema.h:2582
bool BuiltinVectorToScalarMath(CallExpr *TheCall)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:1184
bool AddingCFIUncheckedCallee(QualType From, QualType To) const
Returns true if From is a function or pointer to a function without the cfi_unchecked_callee attribut...
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:2694
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:83
bool IsLayoutCompatible(QualType T1, QualType T2) const
const LangOptions & getLangOpts() const
Definition: Sema.h:911
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
Definition: SemaType.cpp:9230
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:1428
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:6572
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
SemaDirectX & DirectX()
Definition: Sema.h:1443
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:1274
static const uint64_t MaximumAlignment
Definition: Sema.h:1207
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:946
SemaHLSL & HLSL()
Definition: Sema.h:1448
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition: Sema.h:1468
SemaRISCV & RISCV()
Definition: Sema.h:1513
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.
EltwiseBuiltinArgTyRestriction
Definition: Sema.h:2760
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:6915
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition: Sema.cpp:1659
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op)
Definition: SemaCast.cpp:3441
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:1307
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:2662
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition: Sema.h:15233
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:2294
ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl)
The main callback when the parser finds something like expression .
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:633
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:1411
bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount)
Checks that a call expression's argument count is at least the desired number.
SemaOpenCL & OpenCL()
Definition: Sema.h:1493
FormatArgumentPassingKind
Definition: Sema.h:2592
@ FAPK_Elsewhere
Definition: Sema.h:2596
@ FAPK_Fixed
Definition: Sema.h:2593
@ FAPK_Variadic
Definition: Sema.h:2594
@ FAPK_VAList
Definition: Sema.h:2595
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:8122
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:21312
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:13785
SourceManager & getSourceManager() const
Definition: Sema.h:916
static FormatStringType GetFormatStringType(StringRef FormatFlavor)
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount, unsigned MaxArgCount)
Checks that a call expression's argument count is in the desired range.
bool ValidateFormatString(FormatStringType FST, const StringLiteral *Str)
Verify that one format string (as understood by attribute(format)) is self-consistent; for instance,...
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 PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::None)
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20591
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:218
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Binary Operators. 'Tok' is the token for the operator.
Definition: SemaExpr.cpp:15535
bool isConstantEvaluatedContext() const
Definition: Sema.h:2584
bool BuiltinElementwiseTernaryMath(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::FloatTy)
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:12987
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
SemaPPC & PPC()
Definition: Sema.h:1503
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9241
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:1239
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx, unsigned FirstArg, FormatStringInfo *FSI)
Given a function and its FormatAttr or FormatMatchesAttr info, attempts to populate the FomatStringIn...
SemaSystemZ & SystemZ()
Definition: Sema.h:1533
SourceManager & SourceMgr
Definition: Sema.h:1279
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition: SemaExpr.cpp:777
DiagnosticsEngine & Diags
Definition: Sema.h:1278
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9874
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:1007
SemaNVPTX & NVPTX()
Definition: Sema.h:1478
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:627
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:18397
@ AbstractParamType
Definition: Sema.h:6187
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...
SemaSPIRV & SPIRV()
Definition: Sema.h:1518
ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder=AtomicArgumentOrder::API)
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6520
SemaLoongArch & LoongArch()
Definition: Sema.h:1458
@ 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:1538
SemaARM & ARM()
Definition: Sema.h:1418
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
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:4579
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:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:358
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:295
StmtClass getStmtClass() const
Definition: Stmt.h:1483
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:334
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:346
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1801
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1975
bool isUTF8() const
Definition: Expr.h:1920
bool isWide() const
Definition: Expr.h:1919
bool isPascal() const
Definition: Expr.h:1924
unsigned getLength() const
Definition: Expr.h:1911
StringLiteralKind getKind() const
Definition: Expr.h:1914
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:1322
bool isUTF32() const
Definition: Expr.h:1922
unsigned getByteLength() const
Definition: Expr.h:1910
StringRef getString() const
Definition: Expr.h:1869
bool isUTF16() const
Definition: Expr.h:1921
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.h:1976
bool isOrdinary() const
Definition: Expr.h:1918
unsigned getCharByteWidth() const
Definition: Expr.h:1912
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3825
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3805
bool isUnion() const
Definition: Decl.h:3915
Exposes information about the current target.
Definition: TargetInfo.h:226
virtual bool validatePointerAuthKey(const llvm::APSInt &value) const
Determine whether the given pointer-authentication key is valid.
Definition: TargetInfo.cpp:968
virtual bool supportsCpuSupports() const
Definition: TargetInfo.h:1557
virtual bool validateCpuIs(StringRef Name) const
Definition: TargetInfo.h:1573
virtual bool supportsCpuInit() const
Definition: TargetInfo.h:1559
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1288
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:1015
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
Definition: TargetInfo.cpp:293
IntType getSizeType() const
Definition: TargetInfo.h:385
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1563
virtual bool supportsCpuIs() const
Definition: TargetInfo.h:1558
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:804
virtual bool checkArithmeticFenceSupported() const
Controls if __arithmetic_fence is supported in the targeted backend.
Definition: TargetInfo.h:1712
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1526
virtual bool hasSjLjLowering() const
Controls if __builtin_longjmp / __builtin_setjmp can be lowered to llvm.eh.sjlj.longjmp / llvm....
Definition: TargetInfo.h:1767
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
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:396
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:154
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2843
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:193
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition: TypeBase.h:6193
A container of type source information.
Definition: TypeBase.h:8314
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:272
QualType getType() const
Return the type wrapped by this type source info.
Definition: TypeBase.h:8325
The base class of the type hierarchy.
Definition: TypeBase.h:1833
bool isBlockPointerType() const
Definition: TypeBase.h:8600
bool isVoidType() const
Definition: TypeBase.h:8936
bool isBooleanType() const
Definition: TypeBase.h:9066
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2229
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: TypeBase.h:9116
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:787
bool isIncompleteArrayType() const
Definition: TypeBase.h:8687
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2209
bool isFloat16Type() const
Definition: TypeBase.h:8945
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2277
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2119
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.h:26
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: TypeBase.h:9096
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.h:41
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:2070
bool isVoidPointerType() const
Definition: Type.cpp:712
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2430
bool isArrayType() const
Definition: TypeBase.h:8679
bool isCharType() const
Definition: Type.cpp:2136
bool isFunctionPointerType() const
Definition: TypeBase.h:8647
bool isPointerType() const
Definition: TypeBase.h:8580
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: TypeBase.h:8980
const T * castAs() const
Member-template castAs<specific type>.
Definition: TypeBase.h:9226
bool isReferenceType() const
Definition: TypeBase.h:8604
bool isEnumeralType() const
Definition: TypeBase.h:8711
bool isScalarType() const
Definition: TypeBase.h:9038
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition: Type.cpp:1909
bool isVariableArrayType() const
Definition: TypeBase.h:8691
bool isChar8Type() const
Definition: Type.cpp:2152
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2612
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2107
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: TypeBase.h:9054
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2295
bool isExtVectorType() const
Definition: TypeBase.h:8723
bool isExtVectorBoolType() const
Definition: TypeBase.h:8727
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2651
bool isBitIntType() const
Definition: TypeBase.h:8845
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: TypeBase.h:8905
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: TypeBase.h:8703
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: TypeBase.h:2800
RecordDecl * castAsRecordDecl() const
Definition: Type.h:48
bool isChar16Type() const
Definition: Type.cpp:2158
bool isAnyComplexType() const
Definition: TypeBase.h:8715
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: TypeBase.h:8992
bool isHalfType() const
Definition: TypeBase.h:8940
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2247
QualType getCanonicalTypeInternal() const
Definition: TypeBase.h:3137
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2562
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: TypeBase.h:9109
bool isMemberPointerType() const
Definition: TypeBase.h:8661
bool isAtomicType() const
Definition: TypeBase.h:8762
bool isFunctionProtoType() const
Definition: TypeBase.h:2619
bool isChar32Type() const
Definition: Type.cpp:2164
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition: Type.cpp:3079
EnumDecl * castAsEnumDecl() const
Definition: Type.h:59
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: TypeBase.h:2818
bool isUnscopedEnumerationType() const
Definition: Type.cpp:2129
bool isObjCObjectType() const
Definition: TypeBase.h:8753
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: TypeBase.h:9212
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: TypeBase.h:9072
bool isObjectType() const
Determine whether this type is an object type.
Definition: TypeBase.h:2528
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition: Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2440
bool isFunctionType() const
Definition: TypeBase.h:8576
bool isObjCObjectPointerType() const
Definition: TypeBase.h:8749
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition: Type.cpp:2316
bool isStructureOrClassType() const
Definition: Type.cpp:706
bool isVectorType() const
Definition: TypeBase.h:8719
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2324
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition: TypeBase.h:2939
bool isFloatingType() const
Definition: Type.cpp:2308
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:2257
bool isAnyPointerType() const
Definition: TypeBase.h:8588
TypeClass getTypeClass() const
Definition: TypeBase.h:2403
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: TypeBase.h:2429
const T * getAs() const
Member-template getAs<specific type>'.
Definition: TypeBase.h:9159
bool isNullPtrType() const
Definition: TypeBase.h:8973
bool isRecordType() const
Definition: TypeBase.h:8707
bool isObjCRetainableType() const
Definition: Type.cpp:5336
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:5066
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2574
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition: Type.cpp:2639
bool isUnicodeCharacterType() const
Definition: Type.cpp:2192
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3555
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2627
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2246
Expr * getSubExpr() const
Definition: Expr.h:2287
Opcode getOpcode() const
Definition: Expr.h:2282
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:2364
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:998
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition: DeclSpec.h:1086
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:3393
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:711
QualType getType() const
Definition: Decl.h:722
Represents a variable declaration or definition.
Definition: Decl.h:925
Represents a GCC generic vector type.
Definition: TypeBase.h:4191
unsigned getNumElements() const
Definition: TypeBase.h:4206
WhileStmt - This represents a 'while' stmt.
Definition: Stmt.h:2700
MatchKind
How well a given conversion specifier matches its argument.
Definition: FormatString.h:271
@ 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
Represents the length modifier in a format string in scanf/printf.
Definition: FormatString.h:65
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
#define bool
Definition: gpuintrin.h:32
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition: larchintrin.h:181
Definition: SPIR.cpp:35
Definition: SPIR.cpp:47
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
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition: Types.cpp:216
@ 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:1282
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1260
bool LE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1274
bool Cast(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2490
bool EQ(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1228
bool GE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1289
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
@ Match
This is not an overload because the signature exactly matches an existing declaration.
@ CPlusPlus
Definition: LangStandard.h:55
Expr * IgnoreElidableImplicitConstructorSingleStep(Expr *E)
Definition: IgnoreExpr.h:125
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
VariadicCallType
Definition: Sema.h:511
@ Arithmetic
An arithmetic operation.
@ Comparison
A comparison.
@ 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
@ Success
Annotation was successful.
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
PointerAuthDiscArgKind
Definition: Sema.h:592
std::string FormatUTFCodeUnitAsCodepoint(unsigned Value, QualType T)
BinaryOperatorKind
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition: Specifiers.h:124
@ SC_Register
Definition: Specifiers.h:257
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
SemaARM::ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD)
Definition: SemaARM.cpp:545
@ 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:265
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
FormatStringType
Definition: Sema.h:496
CastKind
CastKind - The kind of operation required for a conversion.
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:251
BuiltinCountedByRefKind
Definition: Sema.h:519
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:1765
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
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:327
@ None
The alignment was not explicit in code.
@ None
No keyword precedes the qualified type name.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Other
Other implicit parameter.
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:645
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:647
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:633
Extra information about a function prototype.
Definition: TypeBase.h:5367
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:12947
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition: Sema.h:13045
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition: Sema.h:6776
FormatArgumentPassingKind ArgPassingKind
Definition: Sema.h:2604
#define log2(__x)
Definition: tgmath.h:970