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 TheCall->setType(Context.getComplexType(Real->getType()));
5555 return false;
5556}
5557
5558/// BuiltinShuffleVector - Handle __builtin_shufflevector.
5559// This is declared to take (...), so we have to check everything.
5561 if (TheCall->getNumArgs() < 2)
5562 return ExprError(Diag(TheCall->getEndLoc(),
5563 diag::err_typecheck_call_too_few_args_at_least)
5564 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5565 << /*is non object*/ 0 << TheCall->getSourceRange());
5566
5567 // Determine which of the following types of shufflevector we're checking:
5568 // 1) unary, vector mask: (lhs, mask)
5569 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5570 QualType resType = TheCall->getArg(0)->getType();
5571 unsigned numElements = 0;
5572
5573 if (!TheCall->getArg(0)->isTypeDependent() &&
5574 !TheCall->getArg(1)->isTypeDependent()) {
5575 QualType LHSType = TheCall->getArg(0)->getType();
5576 QualType RHSType = TheCall->getArg(1)->getType();
5577
5578 if (!LHSType->isVectorType() || !RHSType->isVectorType())
5579 return ExprError(
5580 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5581 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ false
5582 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5583 TheCall->getArg(1)->getEndLoc()));
5584
5585 numElements = LHSType->castAs<VectorType>()->getNumElements();
5586 unsigned numResElements = TheCall->getNumArgs() - 2;
5587
5588 // Check to see if we have a call with 2 vector arguments, the unary shuffle
5589 // with mask. If so, verify that RHS is an integer vector type with the
5590 // same number of elts as lhs.
5591 if (TheCall->getNumArgs() == 2) {
5592 if (!RHSType->hasIntegerRepresentation() ||
5593 RHSType->castAs<VectorType>()->getNumElements() != numElements)
5594 return ExprError(Diag(TheCall->getBeginLoc(),
5595 diag::err_vec_builtin_incompatible_vector)
5596 << TheCall->getDirectCallee()
5597 << /*isMorethantwoArgs*/ false
5598 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5599 TheCall->getArg(1)->getEndLoc()));
5600 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5601 return ExprError(Diag(TheCall->getBeginLoc(),
5602 diag::err_vec_builtin_incompatible_vector)
5603 << TheCall->getDirectCallee()
5604 << /*isMorethantwoArgs*/ false
5605 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5606 TheCall->getArg(1)->getEndLoc()));
5607 } else if (numElements != numResElements) {
5608 QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5609 resType = resType->isExtVectorType()
5610 ? Context.getExtVectorType(eltType, numResElements)
5611 : Context.getVectorType(eltType, numResElements,
5613 }
5614 }
5615
5616 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5617 Expr *Arg = TheCall->getArg(i);
5618 if (Arg->isTypeDependent() || Arg->isValueDependent())
5619 continue;
5620
5621 std::optional<llvm::APSInt> Result;
5622 if (!(Result = Arg->getIntegerConstantExpr(Context)))
5623 return ExprError(Diag(TheCall->getBeginLoc(),
5624 diag::err_shufflevector_nonconstant_argument)
5625 << Arg->getSourceRange());
5626
5627 // Allow -1 which will be translated to undef in the IR.
5628 if (Result->isSigned() && Result->isAllOnes())
5629 ;
5630 else if (Result->getActiveBits() > 64 ||
5631 Result->getZExtValue() >= numElements * 2)
5632 return ExprError(Diag(TheCall->getBeginLoc(),
5633 diag::err_shufflevector_argument_too_large)
5634 << Arg->getSourceRange());
5635
5636 TheCall->setArg(i, ConstantExpr::Create(Context, Arg, APValue(*Result)));
5637 }
5638
5639 SmallVector<Expr *> exprs;
5640 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5641 exprs.push_back(TheCall->getArg(i));
5642 TheCall->setArg(i, nullptr);
5643 }
5644
5645 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5646 TheCall->getCallee()->getBeginLoc(),
5647 TheCall->getRParenLoc());
5648}
5649
5651 SourceLocation BuiltinLoc,
5652 SourceLocation RParenLoc) {
5655 QualType DstTy = TInfo->getType();
5656 QualType SrcTy = E->getType();
5657
5658 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5659 return ExprError(Diag(BuiltinLoc,
5660 diag::err_convertvector_non_vector)
5661 << E->getSourceRange());
5662 if (!DstTy->isVectorType() && !DstTy->isDependentType())
5663 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
5664 << "second"
5665 << "__builtin_convertvector");
5666
5667 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5668 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5669 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5670 if (SrcElts != DstElts)
5671 return ExprError(Diag(BuiltinLoc,
5672 diag::err_convertvector_incompatible_vector)
5673 << E->getSourceRange());
5674 }
5675
5676 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
5677 RParenLoc, CurFPFeatureOverrides());
5678}
5679
5680bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
5681 unsigned NumArgs = TheCall->getNumArgs();
5682
5683 if (NumArgs > 3)
5684 return Diag(TheCall->getEndLoc(),
5685 diag::err_typecheck_call_too_many_args_at_most)
5686 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
5687 << TheCall->getSourceRange();
5688
5689 // Argument 0 is checked for us and the remaining arguments must be
5690 // constant integers.
5691 for (unsigned i = 1; i != NumArgs; ++i)
5692 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5693 return true;
5694
5695 return false;
5696}
5697
5698bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
5700 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
5701 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5702 if (checkArgCount(TheCall, 1))
5703 return true;
5704 Expr *Arg = TheCall->getArg(0);
5705 if (Arg->isInstantiationDependent())
5706 return false;
5707
5708 QualType ArgTy = Arg->getType();
5709 if (!ArgTy->hasFloatingRepresentation())
5710 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
5711 << ArgTy;
5712 if (Arg->isLValue()) {
5713 ExprResult FirstArg = DefaultLvalueConversion(Arg);
5714 TheCall->setArg(0, FirstArg.get());
5715 }
5716 TheCall->setType(TheCall->getArg(0)->getType());
5717 return false;
5718}
5719
5720bool Sema::BuiltinAssume(CallExpr *TheCall) {
5721 Expr *Arg = TheCall->getArg(0);
5722 if (Arg->isInstantiationDependent()) return false;
5723
5724 if (Arg->HasSideEffects(Context))
5725 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5726 << Arg->getSourceRange()
5727 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5728
5729 return false;
5730}
5731
5732bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
5733 // The alignment must be a constant integer.
5734 Expr *Arg = TheCall->getArg(1);
5735
5736 // We can't check the value of a dependent argument.
5737 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5738 if (const auto *UE =
5739 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5740 if (UE->getKind() == UETT_AlignOf ||
5741 UE->getKind() == UETT_PreferredAlignOf)
5742 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5743 << Arg->getSourceRange();
5744
5745 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5746
5747 if (!Result.isPowerOf2())
5748 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5749 << Arg->getSourceRange();
5750
5751 if (Result < Context.getCharWidth())
5752 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5754
5755 if (Result > std::numeric_limits<int32_t>::max())
5756 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5757 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5758 }
5759
5760 return false;
5761}
5762
5763bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
5764 if (checkArgCountRange(TheCall, 2, 3))
5765 return true;
5766
5767 unsigned NumArgs = TheCall->getNumArgs();
5768 Expr *FirstArg = TheCall->getArg(0);
5769
5770 {
5771 ExprResult FirstArgResult =
5773 if (!FirstArgResult.get()->getType()->isPointerType()) {
5774 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
5775 << TheCall->getSourceRange();
5776 return true;
5777 }
5778 TheCall->setArg(0, FirstArgResult.get());
5779 }
5780
5781 // The alignment must be a constant integer.
5782 Expr *SecondArg = TheCall->getArg(1);
5783
5784 // We can't check the value of a dependent argument.
5785 if (!SecondArg->isValueDependent()) {
5786 llvm::APSInt Result;
5787 if (BuiltinConstantArg(TheCall, 1, Result))
5788 return true;
5789
5790 if (!Result.isPowerOf2())
5791 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5792 << SecondArg->getSourceRange();
5793
5795 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
5796 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
5797 }
5798
5799 if (NumArgs > 2) {
5800 Expr *ThirdArg = TheCall->getArg(2);
5801 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
5802 return true;
5803 TheCall->setArg(2, ThirdArg);
5804 }
5805
5806 return false;
5807}
5808
5809bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
5810 unsigned BuiltinID =
5811 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5812 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5813
5814 unsigned NumArgs = TheCall->getNumArgs();
5815 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5816 if (NumArgs < NumRequiredArgs) {
5817 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5818 << 0 /* function call */ << NumRequiredArgs << NumArgs
5819 << /*is non object*/ 0 << TheCall->getSourceRange();
5820 }
5821 if (NumArgs >= NumRequiredArgs + 0x100) {
5822 return Diag(TheCall->getEndLoc(),
5823 diag::err_typecheck_call_too_many_args_at_most)
5824 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5825 << /*is non object*/ 0 << TheCall->getSourceRange();
5826 }
5827 unsigned i = 0;
5828
5829 // For formatting call, check buffer arg.
5830 if (!IsSizeCall) {
5831 ExprResult Arg(TheCall->getArg(i));
5833 Context, Context.VoidPtrTy, false);
5834 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5835 if (Arg.isInvalid())
5836 return true;
5837 TheCall->setArg(i, Arg.get());
5838 i++;
5839 }
5840
5841 // Check string literal arg.
5842 unsigned FormatIdx = i;
5843 {
5844 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5845 if (Arg.isInvalid())
5846 return true;
5847 TheCall->setArg(i, Arg.get());
5848 i++;
5849 }
5850
5851 // Make sure variadic args are scalar.
5852 unsigned FirstDataArg = i;
5853 while (i < NumArgs) {
5855 TheCall->getArg(i), VariadicCallType::Function, nullptr);
5856 if (Arg.isInvalid())
5857 return true;
5858 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5859 if (ArgSize.getQuantity() >= 0x100) {
5860 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
5861 << i << (int)ArgSize.getQuantity() << 0xff
5862 << TheCall->getSourceRange();
5863 }
5864 TheCall->setArg(i, Arg.get());
5865 i++;
5866 }
5867
5868 // Check formatting specifiers. NOTE: We're only doing this for the non-size
5869 // call to avoid duplicate diagnostics.
5870 if (!IsSizeCall) {
5871 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5872 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5873 bool Success = CheckFormatArguments(
5874 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
5876 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
5877 if (!Success)
5878 return true;
5879 }
5880
5881 if (IsSizeCall) {
5882 TheCall->setType(Context.getSizeType());
5883 } else {
5884 TheCall->setType(Context.VoidPtrTy);
5885 }
5886 return false;
5887}
5888
5889bool Sema::BuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5890 llvm::APSInt &Result) {
5891 Expr *Arg = TheCall->getArg(ArgNum);
5892 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5893 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5894
5895 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
5896
5897 std::optional<llvm::APSInt> R;
5898 if (!(R = Arg->getIntegerConstantExpr(Context)))
5899 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
5900 << FDecl->getDeclName() << Arg->getSourceRange();
5901 Result = *R;
5902 return false;
5903}
5904
5905bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
5906 int High, bool RangeIsError) {
5908 return false;
5909 llvm::APSInt Result;
5910
5911 // We can't check the value of a dependent argument.
5912 Expr *Arg = TheCall->getArg(ArgNum);
5913 if (Arg->isTypeDependent() || Arg->isValueDependent())
5914 return false;
5915
5916 // Check constant-ness first.
5917 if (BuiltinConstantArg(TheCall, ArgNum, Result))
5918 return true;
5919
5920 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
5921 if (RangeIsError)
5922 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
5923 << toString(Result, 10) << Low << High << Arg->getSourceRange();
5924 else
5925 // Defer the warning until we know if the code will be emitted so that
5926 // dead code can ignore this.
5927 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
5928 PDiag(diag::warn_argument_invalid_range)
5929 << toString(Result, 10) << Low << High
5930 << Arg->getSourceRange());
5931 }
5932
5933 return false;
5934}
5935
5937 unsigned Num) {
5938 llvm::APSInt Result;
5939
5940 // We can't check the value of a dependent argument.
5941 Expr *Arg = TheCall->getArg(ArgNum);
5942 if (Arg->isTypeDependent() || Arg->isValueDependent())
5943 return false;
5944
5945 // Check constant-ness first.
5946 if (BuiltinConstantArg(TheCall, ArgNum, Result))
5947 return true;
5948
5949 if (Result.getSExtValue() % Num != 0)
5950 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
5951 << Num << Arg->getSourceRange();
5952
5953 return false;
5954}
5955
5956bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
5957 llvm::APSInt Result;
5958
5959 // We can't check the value of a dependent argument.
5960 Expr *Arg = TheCall->getArg(ArgNum);
5961 if (Arg->isTypeDependent() || Arg->isValueDependent())
5962 return false;
5963
5964 // Check constant-ness first.
5965 if (BuiltinConstantArg(TheCall, ArgNum, Result))
5966 return true;
5967
5968 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
5969 // and only if x is a power of 2.
5970 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
5971 return false;
5972
5973 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
5974 << Arg->getSourceRange();
5975}
5976
5977static bool IsShiftedByte(llvm::APSInt Value) {
5978 if (Value.isNegative())
5979 return false;
5980
5981 // Check if it's a shifted byte, by shifting it down
5982 while (true) {
5983 // If the value fits in the bottom byte, the check passes.
5984 if (Value < 0x100)
5985 return true;
5986
5987 // Otherwise, if the value has _any_ bits in the bottom byte, the check
5988 // fails.
5989 if ((Value & 0xFF) != 0)
5990 return false;
5991
5992 // If the bottom 8 bits are all 0, but something above that is nonzero,
5993 // then shifting the value right by 8 bits won't affect whether it's a
5994 // shifted byte or not. So do that, and go round again.
5995 Value >>= 8;
5996 }
5997}
5998
6000 unsigned ArgBits) {
6001 llvm::APSInt Result;
6002
6003 // We can't check the value of a dependent argument.
6004 Expr *Arg = TheCall->getArg(ArgNum);
6005 if (Arg->isTypeDependent() || Arg->isValueDependent())
6006 return false;
6007
6008 // Check constant-ness first.
6009 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6010 return true;
6011
6012 // Truncate to the given size.
6013 Result = Result.getLoBits(ArgBits);
6014 Result.setIsUnsigned(true);
6015
6016 if (IsShiftedByte(Result))
6017 return false;
6018
6019 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6020 << Arg->getSourceRange();
6021}
6022
6024 unsigned ArgBits) {
6025 llvm::APSInt Result;
6026
6027 // We can't check the value of a dependent argument.
6028 Expr *Arg = TheCall->getArg(ArgNum);
6029 if (Arg->isTypeDependent() || Arg->isValueDependent())
6030 return false;
6031
6032 // Check constant-ness first.
6033 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6034 return true;
6035
6036 // Truncate to the given size.
6037 Result = Result.getLoBits(ArgBits);
6038 Result.setIsUnsigned(true);
6039
6040 // Check to see if it's in either of the required forms.
6041 if (IsShiftedByte(Result) ||
6042 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6043 return false;
6044
6045 return Diag(TheCall->getBeginLoc(),
6046 diag::err_argument_not_shifted_byte_or_xxff)
6047 << Arg->getSourceRange();
6048}
6049
6050bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6052 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6053 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6054
6055 Expr *Arg = TheCall->getArg(1);
6056 llvm::APSInt Result;
6057
6058 // TODO: This is less than ideal. Overload this to take a value.
6059 if (BuiltinConstantArg(TheCall, 1, Result))
6060 return true;
6061
6062 if (Result != 1)
6063 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6064 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6065
6066 return false;
6067}
6068
6069bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6071 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6072 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6073 return false;
6074}
6075
6076bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
6077 if (checkArgCount(TheCall, 1))
6078 return true;
6079
6080 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
6081 if (ArgRes.isInvalid())
6082 return true;
6083
6084 // For simplicity, we support only limited expressions for the argument.
6085 // Specifically a pointer to a flexible array member:'ptr->array'. This
6086 // allows us to reject arguments with complex casting, which really shouldn't
6087 // be a huge problem.
6088 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
6089 if (!isa<PointerType>(Arg->getType()) && !Arg->getType()->isArrayType())
6090 return Diag(Arg->getBeginLoc(),
6091 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
6092 << Arg->getSourceRange();
6093
6094 if (Arg->HasSideEffects(Context))
6095 return Diag(Arg->getBeginLoc(),
6096 diag::err_builtin_counted_by_ref_has_side_effects)
6097 << Arg->getSourceRange();
6098
6099 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
6100 if (!ME->isFlexibleArrayMemberLike(
6101 Context, getLangOpts().getStrictFlexArraysLevel()))
6102 return Diag(Arg->getBeginLoc(),
6103 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
6104 << Arg->getSourceRange();
6105
6106 if (auto *CATy =
6107 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
6108 CATy && CATy->getKind() == CountAttributedType::CountedBy) {
6109 const auto *FAMDecl = cast<FieldDecl>(ME->getMemberDecl());
6110 if (const FieldDecl *CountFD = FAMDecl->findCountedByField()) {
6111 TheCall->setType(Context.getPointerType(CountFD->getType()));
6112 return false;
6113 }
6114 }
6115 } else {
6116 return Diag(Arg->getBeginLoc(),
6117 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
6118 << Arg->getSourceRange();
6119 }
6120
6122 return false;
6123}
6124
6125/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
6126/// It allows leaking and modification of bounds safety information.
6127bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
6129 const CallExpr *CE =
6130 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
6131 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
6132 return false;
6133
6134 switch (K) {
6137 Diag(E->getExprLoc(),
6138 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6139 << 0 << E->getSourceRange();
6140 break;
6142 Diag(E->getExprLoc(),
6143 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6144 << 1 << E->getSourceRange();
6145 break;
6147 Diag(E->getExprLoc(),
6148 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6149 << 2 << E->getSourceRange();
6150 break;
6152 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6153 << 0 << E->getSourceRange();
6154 break;
6156 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6157 << 1 << E->getSourceRange();
6158 break;
6159 }
6160
6161 return true;
6162}
6163
6164namespace {
6165
6166class UncoveredArgHandler {
6167 enum { Unknown = -1, AllCovered = -2 };
6168
6169 signed FirstUncoveredArg = Unknown;
6170 SmallVector<const Expr *, 4> DiagnosticExprs;
6171
6172public:
6173 UncoveredArgHandler() = default;
6174
6175 bool hasUncoveredArg() const {
6176 return (FirstUncoveredArg >= 0);
6177 }
6178
6179 unsigned getUncoveredArg() const {
6180 assert(hasUncoveredArg() && "no uncovered argument");
6181 return FirstUncoveredArg;
6182 }
6183
6184 void setAllCovered() {
6185 // A string has been found with all arguments covered, so clear out
6186 // the diagnostics.
6187 DiagnosticExprs.clear();
6188 FirstUncoveredArg = AllCovered;
6189 }
6190
6191 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6192 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6193
6194 // Don't update if a previous string covers all arguments.
6195 if (FirstUncoveredArg == AllCovered)
6196 return;
6197
6198 // UncoveredArgHandler tracks the highest uncovered argument index
6199 // and with it all the strings that match this index.
6200 if (NewFirstUncoveredArg == FirstUncoveredArg)
6201 DiagnosticExprs.push_back(StrExpr);
6202 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6203 DiagnosticExprs.clear();
6204 DiagnosticExprs.push_back(StrExpr);
6205 FirstUncoveredArg = NewFirstUncoveredArg;
6206 }
6207 }
6208
6209 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6210};
6211
6212enum StringLiteralCheckType {
6213 SLCT_NotALiteral,
6214 SLCT_UncheckedLiteral,
6215 SLCT_CheckedLiteral
6216};
6217
6218} // namespace
6219
6220static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6221 BinaryOperatorKind BinOpKind,
6222 bool AddendIsRight) {
6223 unsigned BitWidth = Offset.getBitWidth();
6224 unsigned AddendBitWidth = Addend.getBitWidth();
6225 // There might be negative interim results.
6226 if (Addend.isUnsigned()) {
6227 Addend = Addend.zext(++AddendBitWidth);
6228 Addend.setIsSigned(true);
6229 }
6230 // Adjust the bit width of the APSInts.
6231 if (AddendBitWidth > BitWidth) {
6232 Offset = Offset.sext(AddendBitWidth);
6233 BitWidth = AddendBitWidth;
6234 } else if (BitWidth > AddendBitWidth) {
6235 Addend = Addend.sext(BitWidth);
6236 }
6237
6238 bool Ov = false;
6239 llvm::APSInt ResOffset = Offset;
6240 if (BinOpKind == BO_Add)
6241 ResOffset = Offset.sadd_ov(Addend, Ov);
6242 else {
6243 assert(AddendIsRight && BinOpKind == BO_Sub &&
6244 "operator must be add or sub with addend on the right");
6245 ResOffset = Offset.ssub_ov(Addend, Ov);
6246 }
6247
6248 // We add an offset to a pointer here so we should support an offset as big as
6249 // possible.
6250 if (Ov) {
6251 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6252 "index (intermediate) result too big");
6253 Offset = Offset.sext(2 * BitWidth);
6254 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6255 return;
6256 }
6257
6258 Offset = ResOffset;
6259}
6260
6261namespace {
6262
6263// This is a wrapper class around StringLiteral to support offsetted string
6264// literals as format strings. It takes the offset into account when returning
6265// the string and its length or the source locations to display notes correctly.
6266class FormatStringLiteral {
6267 const StringLiteral *FExpr;
6268 int64_t Offset;
6269
6270public:
6271 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6272 : FExpr(fexpr), Offset(Offset) {}
6273
6274 const StringLiteral *getFormatString() const { return FExpr; }
6275
6276 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
6277
6278 unsigned getByteLength() const {
6279 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6280 }
6281
6282 unsigned getLength() const { return FExpr->getLength() - Offset; }
6283 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6284
6285 StringLiteralKind getKind() const { return FExpr->getKind(); }
6286
6287 QualType getType() const { return FExpr->getType(); }
6288
6289 bool isAscii() const { return FExpr->isOrdinary(); }
6290 bool isWide() const { return FExpr->isWide(); }
6291 bool isUTF8() const { return FExpr->isUTF8(); }
6292 bool isUTF16() const { return FExpr->isUTF16(); }
6293 bool isUTF32() const { return FExpr->isUTF32(); }
6294 bool isPascal() const { return FExpr->isPascal(); }
6295
6296 SourceLocation getLocationOfByte(
6297 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6298 const TargetInfo &Target, unsigned *StartToken = nullptr,
6299 unsigned *StartTokenByteOffset = nullptr) const {
6300 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6301 StartToken, StartTokenByteOffset);
6302 }
6303
6304 SourceLocation getBeginLoc() const LLVM_READONLY {
6305 return FExpr->getBeginLoc().getLocWithOffset(Offset);
6306 }
6307
6308 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6309};
6310
6311} // namespace
6312
6313static void CheckFormatString(
6314 Sema &S, const FormatStringLiteral *FExpr,
6315 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
6317 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6318 bool inFunctionCall, VariadicCallType CallType,
6319 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6320 bool IgnoreStringsWithoutSpecifiers);
6321
6322static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
6323 const Expr *E);
6324
6325// Determine if an expression is a string literal or constant string.
6326// If this function returns false on the arguments to a function expecting a
6327// format string, we will usually need to emit a warning.
6328// True string literals are then checked by CheckFormatString.
6329static StringLiteralCheckType checkFormatStringExpr(
6330 Sema &S, const StringLiteral *ReferenceFormatString, const Expr *E,
6332 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6333 VariadicCallType CallType, bool InFunctionCall,
6334 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6335 llvm::APSInt Offset, bool IgnoreStringsWithoutSpecifiers = false) {
6337 return SLCT_NotALiteral;
6338tryAgain:
6339 assert(Offset.isSigned() && "invalid offset");
6340
6341 if (E->isTypeDependent() || E->isValueDependent())
6342 return SLCT_NotALiteral;
6343
6344 E = E->IgnoreParenCasts();
6345
6347 // Technically -Wformat-nonliteral does not warn about this case.
6348 // The behavior of printf and friends in this case is implementation
6349 // dependent. Ideally if the format string cannot be null then
6350 // it should have a 'nonnull' attribute in the function prototype.
6351 return SLCT_UncheckedLiteral;
6352
6353 switch (E->getStmtClass()) {
6354 case Stmt::InitListExprClass:
6355 // Handle expressions like {"foobar"}.
6356 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
6357 return checkFormatStringExpr(
6358 S, ReferenceFormatString, SLE, Args, APK, format_idx, firstDataArg,
6359 Type, CallType, /*InFunctionCall*/ false, CheckedVarArgs,
6360 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6361 }
6362 return SLCT_NotALiteral;
6363 case Stmt::BinaryConditionalOperatorClass:
6364 case Stmt::ConditionalOperatorClass: {
6365 // The expression is a literal if both sub-expressions were, and it was
6366 // completely checked only if both sub-expressions were checked.
6368 cast<AbstractConditionalOperator>(E);
6369
6370 // Determine whether it is necessary to check both sub-expressions, for
6371 // example, because the condition expression is a constant that can be
6372 // evaluated at compile time.
6373 bool CheckLeft = true, CheckRight = true;
6374
6375 bool Cond;
6376 if (C->getCond()->EvaluateAsBooleanCondition(
6377 Cond, S.getASTContext(), S.isConstantEvaluatedContext())) {
6378 if (Cond)
6379 CheckRight = false;
6380 else
6381 CheckLeft = false;
6382 }
6383
6384 // We need to maintain the offsets for the right and the left hand side
6385 // separately to check if every possible indexed expression is a valid
6386 // string literal. They might have different offsets for different string
6387 // literals in the end.
6388 StringLiteralCheckType Left;
6389 if (!CheckLeft)
6390 Left = SLCT_UncheckedLiteral;
6391 else {
6392 Left = checkFormatStringExpr(
6393 S, ReferenceFormatString, C->getTrueExpr(), Args, APK, format_idx,
6394 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6395 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6396 if (Left == SLCT_NotALiteral || !CheckRight) {
6397 return Left;
6398 }
6399 }
6400
6401 StringLiteralCheckType Right = checkFormatStringExpr(
6402 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
6403 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6404 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6405
6406 return (CheckLeft && Left < Right) ? Left : Right;
6407 }
6408
6409 case Stmt::ImplicitCastExprClass:
6410 E = cast<ImplicitCastExpr>(E)->getSubExpr();
6411 goto tryAgain;
6412
6413 case Stmt::OpaqueValueExprClass:
6414 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6415 E = src;
6416 goto tryAgain;
6417 }
6418 return SLCT_NotALiteral;
6419
6420 case Stmt::PredefinedExprClass:
6421 // While __func__, etc., are technically not string literals, they
6422 // cannot contain format specifiers and thus are not a security
6423 // liability.
6424 return SLCT_UncheckedLiteral;
6425
6426 case Stmt::DeclRefExprClass: {
6427 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6428
6429 // As an exception, do not flag errors for variables binding to
6430 // const string literals.
6431 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6432 bool isConstant = false;
6433 QualType T = DR->getType();
6434
6435 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6436 isConstant = AT->getElementType().isConstant(S.Context);
6437 } else if (const PointerType *PT = T->getAs<PointerType>()) {
6438 isConstant = T.isConstant(S.Context) &&
6440 } else if (T->isObjCObjectPointerType()) {
6441 // In ObjC, there is usually no "const ObjectPointer" type,
6442 // so don't check if the pointee type is constant.
6443 isConstant = T.isConstant(S.Context);
6444 }
6445
6446 if (isConstant) {
6447 if (const Expr *Init = VD->getAnyInitializer()) {
6448 // Look through initializers like const char c[] = { "foo" }
6449 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6450 if (InitList->isStringLiteralInit())
6451 Init = InitList->getInit(0)->IgnoreParenImpCasts();
6452 }
6453 return checkFormatStringExpr(
6454 S, ReferenceFormatString, Init, Args, APK, format_idx,
6455 firstDataArg, Type, CallType,
6456 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg, Offset);
6457 }
6458 }
6459
6460 // When the format argument is an argument of this function, and this
6461 // function also has the format attribute, there are several interactions
6462 // for which there shouldn't be a warning. For instance, when calling
6463 // v*printf from a function that has the printf format attribute, we
6464 // should not emit a warning about using `fmt`, even though it's not
6465 // constant, because the arguments have already been checked for the
6466 // caller of `logmessage`:
6467 //
6468 // __attribute__((format(printf, 1, 2)))
6469 // void logmessage(char const *fmt, ...) {
6470 // va_list ap;
6471 // va_start(ap, fmt);
6472 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
6473 // ...
6474 // }
6475 //
6476 // Another interaction that we need to support is using a format string
6477 // specified by the format_matches attribute:
6478 //
6479 // __attribute__((format_matches(printf, 1, "%s %d")))
6480 // void logmessage(char const *fmt, const char *a, int b) {
6481 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
6482 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
6483 // ...
6484 // }
6485 //
6486 // Yet another interaction that we need to support is calling a variadic
6487 // format function from a format function that has fixed arguments. For
6488 // instance:
6489 //
6490 // __attribute__((format(printf, 1, 2)))
6491 // void logstring(char const *fmt, char const *str) {
6492 // printf(fmt, str); /* do not emit a warning about "fmt" */
6493 // }
6494 //
6495 // Same (and perhaps more relatably) for the variadic template case:
6496 //
6497 // template<typename... Args>
6498 // __attribute__((format(printf, 1, 2)))
6499 // void log(const char *fmt, Args&&... args) {
6500 // printf(fmt, forward<Args>(args)...);
6501 // /* do not emit a warning about "fmt" */
6502 // }
6503 //
6504 // Due to implementation difficulty, we only check the format, not the
6505 // format arguments, in all cases.
6506 //
6507 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
6508 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
6509 for (const auto *PVFormatMatches :
6510 D->specific_attrs<FormatMatchesAttr>()) {
6511 Sema::FormatStringInfo CalleeFSI;
6512 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
6513 0, &CalleeFSI))
6514 continue;
6515 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
6516 // If using the wrong type of format string, emit a diagnostic
6517 // here and stop checking to avoid irrelevant diagnostics.
6518 if (Type != S.GetFormatStringType(PVFormatMatches)) {
6519 S.Diag(Args[format_idx]->getBeginLoc(),
6520 diag::warn_format_string_type_incompatible)
6521 << PVFormatMatches->getType()->getName()
6523 if (!InFunctionCall) {
6524 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
6525 diag::note_format_string_defined);
6526 }
6527 return SLCT_UncheckedLiteral;
6528 }
6529 return checkFormatStringExpr(
6530 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
6531 Args, APK, format_idx, firstDataArg, Type, CallType,
6532 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
6533 Offset, IgnoreStringsWithoutSpecifiers);
6534 }
6535 }
6536
6537 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
6538 Sema::FormatStringInfo CallerFSI;
6539 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
6540 PVFormat->getFirstArg(), &CallerFSI))
6541 continue;
6542 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
6543 // We also check if the formats are compatible.
6544 // We can't pass a 'scanf' string to a 'printf' function.
6545 if (Type != S.GetFormatStringType(PVFormat)) {
6546 S.Diag(Args[format_idx]->getBeginLoc(),
6547 diag::warn_format_string_type_incompatible)
6548 << PVFormat->getType()->getName()
6550 if (!InFunctionCall) {
6551 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
6552 }
6553 return SLCT_UncheckedLiteral;
6554 }
6555 // Lastly, check that argument passing kinds transition in a
6556 // way that makes sense:
6557 // from a caller with FAPK_VAList, allow FAPK_VAList
6558 // from a caller with FAPK_Fixed, allow FAPK_Fixed
6559 // from a caller with FAPK_Fixed, allow FAPK_Variadic
6560 // from a caller with FAPK_Variadic, allow FAPK_VAList
6561 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
6566 return SLCT_UncheckedLiteral;
6567 }
6568 }
6569 }
6570 }
6571 }
6572 }
6573
6574 return SLCT_NotALiteral;
6575 }
6576
6577 case Stmt::CallExprClass:
6578 case Stmt::CXXMemberCallExprClass: {
6579 const CallExpr *CE = cast<CallExpr>(E);
6580 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6581 bool IsFirst = true;
6582 StringLiteralCheckType CommonResult;
6583 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6584 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6585 StringLiteralCheckType Result = checkFormatStringExpr(
6586 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
6587 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
6588 Offset, IgnoreStringsWithoutSpecifiers);
6589 if (IsFirst) {
6590 CommonResult = Result;
6591 IsFirst = false;
6592 }
6593 }
6594 if (!IsFirst)
6595 return CommonResult;
6596
6597 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6598 unsigned BuiltinID = FD->getBuiltinID();
6599 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6600 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6601 const Expr *Arg = CE->getArg(0);
6602 return checkFormatStringExpr(
6603 S, ReferenceFormatString, Arg, Args, APK, format_idx,
6604 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6605 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6606 }
6607 }
6608 }
6609 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
6610 return checkFormatStringExpr(
6611 S, ReferenceFormatString, SLE, Args, APK, format_idx, firstDataArg,
6612 Type, CallType, /*InFunctionCall*/ false, CheckedVarArgs,
6613 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6614 return SLCT_NotALiteral;
6615 }
6616 case Stmt::ObjCMessageExprClass: {
6617 const auto *ME = cast<ObjCMessageExpr>(E);
6618 if (const auto *MD = ME->getMethodDecl()) {
6619 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6620 // As a special case heuristic, if we're using the method -[NSBundle
6621 // localizedStringForKey:value:table:], ignore any key strings that lack
6622 // format specifiers. The idea is that if the key doesn't have any
6623 // format specifiers then its probably just a key to map to the
6624 // localized strings. If it does have format specifiers though, then its
6625 // likely that the text of the key is the format string in the
6626 // programmer's language, and should be checked.
6627 const ObjCInterfaceDecl *IFace;
6628 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6629 IFace->getIdentifier()->isStr("NSBundle") &&
6630 MD->getSelector().isKeywordSelector(
6631 {"localizedStringForKey", "value", "table"})) {
6632 IgnoreStringsWithoutSpecifiers = true;
6633 }
6634
6635 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6636 return checkFormatStringExpr(
6637 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
6638 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
6639 Offset, IgnoreStringsWithoutSpecifiers);
6640 }
6641 }
6642
6643 return SLCT_NotALiteral;
6644 }
6645 case Stmt::ObjCStringLiteralClass:
6646 case Stmt::StringLiteralClass: {
6647 const StringLiteral *StrE = nullptr;
6648
6649 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6650 StrE = ObjCFExpr->getString();
6651 else
6652 StrE = cast<StringLiteral>(E);
6653
6654 if (StrE) {
6655 if (Offset.isNegative() || Offset > StrE->getLength()) {
6656 // TODO: It would be better to have an explicit warning for out of
6657 // bounds literals.
6658 return SLCT_NotALiteral;
6659 }
6660 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6661 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
6662 format_idx, firstDataArg, Type, InFunctionCall,
6663 CallType, CheckedVarArgs, UncoveredArg,
6664 IgnoreStringsWithoutSpecifiers);
6665 return SLCT_CheckedLiteral;
6666 }
6667
6668 return SLCT_NotALiteral;
6669 }
6670 case Stmt::BinaryOperatorClass: {
6671 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6672
6673 // A string literal + an int offset is still a string literal.
6674 if (BinOp->isAdditiveOp()) {
6675 Expr::EvalResult LResult, RResult;
6676
6677 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6678 LResult, S.Context, Expr::SE_NoSideEffects,
6680 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6681 RResult, S.Context, Expr::SE_NoSideEffects,
6683
6684 if (LIsInt != RIsInt) {
6685 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6686
6687 if (LIsInt) {
6688 if (BinOpKind == BO_Add) {
6689 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6690 E = BinOp->getRHS();
6691 goto tryAgain;
6692 }
6693 } else {
6694 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6695 E = BinOp->getLHS();
6696 goto tryAgain;
6697 }
6698 }
6699 }
6700
6701 return SLCT_NotALiteral;
6702 }
6703 case Stmt::UnaryOperatorClass: {
6704 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6705 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6706 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6707 Expr::EvalResult IndexResult;
6708 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6711 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6712 /*RHS is int*/ true);
6713 E = ASE->getBase();
6714 goto tryAgain;
6715 }
6716 }
6717
6718 return SLCT_NotALiteral;
6719 }
6720
6721 default:
6722 return SLCT_NotALiteral;
6723 }
6724}
6725
6726// If this expression can be evaluated at compile-time,
6727// check if the result is a StringLiteral and return it
6728// otherwise return nullptr
6730 const Expr *E) {
6732 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
6733 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
6734 if (isa_and_nonnull<StringLiteral>(LVE))
6735 return LVE;
6736 }
6737 return nullptr;
6738}
6739
6741 switch (FST) {
6743 return "scanf";
6745 return "printf";
6747 return "NSString";
6749 return "strftime";
6751 return "strfmon";
6753 return "kprintf";
6755 return "freebsd_kprintf";
6757 return "os_log";
6758 default:
6759 return "<unknown>";
6760 }
6761}
6762
6764 return llvm::StringSwitch<FormatStringType>(Flavor)
6765 .Case("scanf", FormatStringType::Scanf)
6766 .Cases("printf", "printf0", "syslog", FormatStringType::Printf)
6767 .Cases("NSString", "CFString", FormatStringType::NSString)
6768 .Case("strftime", FormatStringType::Strftime)
6769 .Case("strfmon", FormatStringType::Strfmon)
6770 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err",
6772 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
6773 .Case("os_trace", FormatStringType::OSLog)
6774 .Case("os_log", FormatStringType::OSLog)
6775 .Default(FormatStringType::Unknown);
6776}
6777
6779 return GetFormatStringType(Format->getType()->getName());
6780}
6781
6782FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
6783 return GetFormatStringType(Format->getType()->getName());
6784}
6785
6786bool Sema::CheckFormatArguments(const FormatAttr *Format,
6787 ArrayRef<const Expr *> Args, bool IsCXXMember,
6790 llvm::SmallBitVector &CheckedVarArgs) {
6791 FormatStringInfo FSI;
6792 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
6793 IsCXXMember,
6794 CallType != VariadicCallType::DoesNotApply, &FSI))
6795 return CheckFormatArguments(
6796 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
6797 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
6798 return false;
6799}
6800
6801bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
6802 ArrayRef<const Expr *> Args, bool IsCXXMember,
6805 llvm::SmallBitVector &CheckedVarArgs) {
6806 FormatStringInfo FSI;
6807 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
6808 &FSI)) {
6809 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
6810 return CheckFormatArguments(Args, FSI.ArgPassingKind,
6811 Format->getFormatString(), FSI.FormatIdx,
6812 FSI.FirstDataArg, GetFormatStringType(Format),
6813 CallType, Loc, Range, CheckedVarArgs);
6814 }
6815 return false;
6816}
6817
6818bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6820 const StringLiteral *ReferenceFormatString,
6821 unsigned format_idx, unsigned firstDataArg,
6825 llvm::SmallBitVector &CheckedVarArgs) {
6826 // CHECK: printf/scanf-like function is called with no format string.
6827 if (format_idx >= Args.size()) {
6828 Diag(Loc, diag::warn_missing_format_string) << Range;
6829 return false;
6830 }
6831
6832 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6833
6834 // CHECK: format string is not a string literal.
6835 //
6836 // Dynamically generated format strings are difficult to
6837 // automatically vet at compile time. Requiring that format strings
6838 // are string literals: (1) permits the checking of format strings by
6839 // the compiler and thereby (2) can practically remove the source of
6840 // many format string exploits.
6841
6842 // Format string can be either ObjC string (e.g. @"%d") or
6843 // C string (e.g. "%d")
6844 // ObjC string uses the same format specifiers as C string, so we can use
6845 // the same format string checking logic for both ObjC and C strings.
6846 UncoveredArgHandler UncoveredArg;
6847 StringLiteralCheckType CT = checkFormatStringExpr(
6848 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
6849 firstDataArg, Type, CallType,
6850 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
6851 /*no string offset*/ llvm::APSInt(64, false) = 0);
6852
6853 // Generate a diagnostic where an uncovered argument is detected.
6854 if (UncoveredArg.hasUncoveredArg()) {
6855 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6856 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6857 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6858 }
6859
6860 if (CT != SLCT_NotALiteral)
6861 // Literal format string found, check done!
6862 return CT == SLCT_CheckedLiteral;
6863
6864 // Strftime is particular as it always uses a single 'time' argument,
6865 // so it is safe to pass a non-literal string.
6867 return false;
6868
6869 // Do not emit diag when the string param is a macro expansion and the
6870 // format is either NSString or CFString. This is a hack to prevent
6871 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6872 // which are usually used in place of NS and CF string literals.
6873 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
6875 SourceMgr.isInSystemMacro(FormatLoc))
6876 return false;
6877
6878 // If there are no arguments specified, warn with -Wformat-security, otherwise
6879 // warn only with -Wformat-nonliteral.
6880 if (Args.size() == firstDataArg) {
6881 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6882 << OrigFormatExpr->getSourceRange();
6883 switch (Type) {
6884 default:
6885 break;
6890 Diag(FormatLoc, diag::note_format_security_fixit)
6891 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
6892 break;
6894 Diag(FormatLoc, diag::note_format_security_fixit)
6895 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
6896 break;
6897 }
6898 } else {
6899 Diag(FormatLoc, diag::warn_format_nonliteral)
6900 << OrigFormatExpr->getSourceRange();
6901 }
6902 return false;
6903}
6904
6905namespace {
6906
6907class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6908protected:
6909 Sema &S;
6910 const FormatStringLiteral *FExpr;
6911 const Expr *OrigFormatExpr;
6912 const FormatStringType FSType;
6913 const unsigned FirstDataArg;
6914 const unsigned NumDataArgs;
6915 const char *Beg; // Start of format string.
6916 const Sema::FormatArgumentPassingKind ArgPassingKind;
6918 unsigned FormatIdx;
6919 llvm::SmallBitVector CoveredArgs;
6920 bool usesPositionalArgs = false;
6921 bool atFirstArg = true;
6922 bool inFunctionCall;
6923 VariadicCallType CallType;
6924 llvm::SmallBitVector &CheckedVarArgs;
6925 UncoveredArgHandler &UncoveredArg;
6926
6927public:
6928 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
6929 const Expr *origFormatExpr, const FormatStringType type,
6930 unsigned firstDataArg, unsigned numDataArgs,
6931 const char *beg, Sema::FormatArgumentPassingKind APK,
6932 ArrayRef<const Expr *> Args, unsigned formatIdx,
6933 bool inFunctionCall, VariadicCallType callType,
6934 llvm::SmallBitVector &CheckedVarArgs,
6935 UncoveredArgHandler &UncoveredArg)
6936 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
6937 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
6938 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
6939 inFunctionCall(inFunctionCall), CallType(callType),
6940 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
6941 CoveredArgs.resize(numDataArgs);
6942 CoveredArgs.reset();
6943 }
6944
6945 bool HasFormatArguments() const {
6946 return ArgPassingKind == Sema::FAPK_Fixed ||
6947 ArgPassingKind == Sema::FAPK_Variadic;
6948 }
6949
6950 void DoneProcessing();
6951
6952 void HandleIncompleteSpecifier(const char *startSpecifier,
6953 unsigned specifierLen) override;
6954
6955 void HandleInvalidLengthModifier(
6958 const char *startSpecifier, unsigned specifierLen,
6959 unsigned DiagID);
6960
6961 void HandleNonStandardLengthModifier(
6963 const char *startSpecifier, unsigned specifierLen);
6964
6965 void HandleNonStandardConversionSpecifier(
6967 const char *startSpecifier, unsigned specifierLen);
6968
6969 void HandlePosition(const char *startPos, unsigned posLen) override;
6970
6971 void HandleInvalidPosition(const char *startSpecifier,
6972 unsigned specifierLen,
6974
6975 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
6976
6977 void HandleNullChar(const char *nullCharacter) override;
6978
6979 template <typename Range>
6980 static void
6981 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
6982 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
6983 bool IsStringLocation, Range StringRange,
6984 ArrayRef<FixItHint> Fixit = {});
6985
6986protected:
6987 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
6988 const char *startSpec,
6989 unsigned specifierLen,
6990 const char *csStart, unsigned csLen);
6991
6992 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
6993 const char *startSpec,
6994 unsigned specifierLen);
6995
6996 SourceRange getFormatStringRange();
6997 CharSourceRange getSpecifierRange(const char *startSpecifier,
6998 unsigned specifierLen);
6999 SourceLocation getLocationOfByte(const char *x);
7000
7001 const Expr *getDataArg(unsigned i) const;
7002
7003 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7005 const char *startSpecifier, unsigned specifierLen,
7006 unsigned argIndex);
7007
7008 template <typename Range>
7009 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7010 bool IsStringLocation, Range StringRange,
7011 ArrayRef<FixItHint> Fixit = {});
7012};
7013
7014} // namespace
7015
7016SourceRange CheckFormatHandler::getFormatStringRange() {
7017 return OrigFormatExpr->getSourceRange();
7018}
7019
7020CharSourceRange CheckFormatHandler::
7021getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7022 SourceLocation Start = getLocationOfByte(startSpecifier);
7023 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
7024
7025 // Advance the end SourceLocation by one due to half-open ranges.
7026 End = End.getLocWithOffset(1);
7027
7028 return CharSourceRange::getCharRange(Start, End);
7029}
7030
7031SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7032 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7034}
7035
7036void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7037 unsigned specifierLen){
7038 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7039 getLocationOfByte(startSpecifier),
7040 /*IsStringLocation*/true,
7041 getSpecifierRange(startSpecifier, specifierLen));
7042}
7043
7044void CheckFormatHandler::HandleInvalidLengthModifier(
7047 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7048 using namespace analyze_format_string;
7049
7050 const LengthModifier &LM = FS.getLengthModifier();
7051 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7052
7053 // See if we know how to fix this length modifier.
7054 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7055 if (FixedLM) {
7056 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7057 getLocationOfByte(LM.getStart()),
7058 /*IsStringLocation*/true,
7059 getSpecifierRange(startSpecifier, specifierLen));
7060
7061 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7062 << FixedLM->toString()
7063 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7064
7065 } else {
7066 FixItHint Hint;
7067 if (DiagID == diag::warn_format_nonsensical_length)
7068 Hint = FixItHint::CreateRemoval(LMRange);
7069
7070 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7071 getLocationOfByte(LM.getStart()),
7072 /*IsStringLocation*/true,
7073 getSpecifierRange(startSpecifier, specifierLen),
7074 Hint);
7075 }
7076}
7077
7078void CheckFormatHandler::HandleNonStandardLengthModifier(
7080 const char *startSpecifier, unsigned specifierLen) {
7081 using namespace analyze_format_string;
7082
7083 const LengthModifier &LM = FS.getLengthModifier();
7084 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7085
7086 // See if we know how to fix this length modifier.
7087 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7088 if (FixedLM) {
7089 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7090 << LM.toString() << 0,
7091 getLocationOfByte(LM.getStart()),
7092 /*IsStringLocation*/true,
7093 getSpecifierRange(startSpecifier, specifierLen));
7094
7095 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7096 << FixedLM->toString()
7097 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7098
7099 } else {
7100 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7101 << LM.toString() << 0,
7102 getLocationOfByte(LM.getStart()),
7103 /*IsStringLocation*/true,
7104 getSpecifierRange(startSpecifier, specifierLen));
7105 }
7106}
7107
7108void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7110 const char *startSpecifier, unsigned specifierLen) {
7111 using namespace analyze_format_string;
7112
7113 // See if we know how to fix this conversion specifier.
7114 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7115 if (FixedCS) {
7116 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7117 << CS.toString() << /*conversion specifier*/1,
7118 getLocationOfByte(CS.getStart()),
7119 /*IsStringLocation*/true,
7120 getSpecifierRange(startSpecifier, specifierLen));
7121
7122 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7123 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7124 << FixedCS->toString()
7125 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7126 } else {
7127 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7128 << CS.toString() << /*conversion specifier*/1,
7129 getLocationOfByte(CS.getStart()),
7130 /*IsStringLocation*/true,
7131 getSpecifierRange(startSpecifier, specifierLen));
7132 }
7133}
7134
7135void CheckFormatHandler::HandlePosition(const char *startPos,
7136 unsigned posLen) {
7137 if (!S.getDiagnostics().isIgnored(
7138 diag::warn_format_non_standard_positional_arg, SourceLocation()))
7139 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7140 getLocationOfByte(startPos),
7141 /*IsStringLocation*/ true,
7142 getSpecifierRange(startPos, posLen));
7143}
7144
7145void CheckFormatHandler::HandleInvalidPosition(
7146 const char *startSpecifier, unsigned specifierLen,
7148 if (!S.getDiagnostics().isIgnored(
7149 diag::warn_format_invalid_positional_specifier, SourceLocation()))
7150 EmitFormatDiagnostic(
7151 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
7152 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
7153 getSpecifierRange(startSpecifier, specifierLen));
7154}
7155
7156void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7157 unsigned posLen) {
7158 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
7159 SourceLocation()))
7160 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7161 getLocationOfByte(startPos),
7162 /*IsStringLocation*/ true,
7163 getSpecifierRange(startPos, posLen));
7164}
7165
7166void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7167 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7168 // The presence of a null character is likely an error.
7169 EmitFormatDiagnostic(
7170 S.PDiag(diag::warn_printf_format_string_contains_null_char),
7171 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7172 getFormatStringRange());
7173 }
7174}
7175
7176// Note that this may return NULL if there was an error parsing or building
7177// one of the argument expressions.
7178const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7179 return Args[FirstDataArg + i];
7180}
7181
7182void CheckFormatHandler::DoneProcessing() {
7183 // Does the number of data arguments exceed the number of
7184 // format conversions in the format string?
7185 if (HasFormatArguments()) {
7186 // Find any arguments that weren't covered.
7187 CoveredArgs.flip();
7188 signed notCoveredArg = CoveredArgs.find_first();
7189 if (notCoveredArg >= 0) {
7190 assert((unsigned)notCoveredArg < NumDataArgs);
7191 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7192 } else {
7193 UncoveredArg.setAllCovered();
7194 }
7195 }
7196}
7197
7198void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7199 const Expr *ArgExpr) {
7200 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
7201 "Invalid state");
7202
7203 if (!ArgExpr)
7204 return;
7205
7206 SourceLocation Loc = ArgExpr->getBeginLoc();
7207
7209 return;
7210
7211 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7212 for (auto E : DiagnosticExprs)
7213 PDiag << E->getSourceRange();
7214
7215 CheckFormatHandler::EmitFormatDiagnostic(
7216 S, IsFunctionCall, DiagnosticExprs[0],
7217 PDiag, Loc, /*IsStringLocation*/false,
7218 DiagnosticExprs[0]->getSourceRange());
7219}
7220
7221bool
7222CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7224 const char *startSpec,
7225 unsigned specifierLen,
7226 const char *csStart,
7227 unsigned csLen) {
7228 bool keepGoing = true;
7229 if (argIndex < NumDataArgs) {
7230 // Consider the argument coverered, even though the specifier doesn't
7231 // make sense.
7232 CoveredArgs.set(argIndex);
7233 }
7234 else {
7235 // If argIndex exceeds the number of data arguments we
7236 // don't issue a warning because that is just a cascade of warnings (and
7237 // they may have intended '%%' anyway). We don't want to continue processing
7238 // the format string after this point, however, as we will like just get
7239 // gibberish when trying to match arguments.
7240 keepGoing = false;
7241 }
7242
7243 StringRef Specifier(csStart, csLen);
7244
7245 // If the specifier in non-printable, it could be the first byte of a UTF-8
7246 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7247 // hex value.
7248 std::string CodePointStr;
7249 if (!llvm::sys::locale::isPrint(*csStart)) {
7250 llvm::UTF32 CodePoint;
7251 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7252 const llvm::UTF8 *E =
7253 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7254 llvm::ConversionResult Result =
7255 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7256
7257 if (Result != llvm::conversionOK) {
7258 unsigned char FirstChar = *csStart;
7259 CodePoint = (llvm::UTF32)FirstChar;
7260 }
7261
7262 llvm::raw_string_ostream OS(CodePointStr);
7263 if (CodePoint < 256)
7264 OS << "\\x" << llvm::format("%02x", CodePoint);
7265 else if (CodePoint <= 0xFFFF)
7266 OS << "\\u" << llvm::format("%04x", CodePoint);
7267 else
7268 OS << "\\U" << llvm::format("%08x", CodePoint);
7269 Specifier = CodePointStr;
7270 }
7271
7272 EmitFormatDiagnostic(
7273 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7274 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7275
7276 return keepGoing;
7277}
7278
7279void
7280CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7281 const char *startSpec,
7282 unsigned specifierLen) {
7283 EmitFormatDiagnostic(
7284 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7285 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7286}
7287
7288bool
7289CheckFormatHandler::CheckNumArgs(
7292 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7293
7294 if (HasFormatArguments() && argIndex >= NumDataArgs) {
7295 PartialDiagnostic PDiag = FS.usesPositionalArg()
7296 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7297 << (argIndex+1) << NumDataArgs)
7298 : S.PDiag(diag::warn_printf_insufficient_data_args);
7299 EmitFormatDiagnostic(
7300 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7301 getSpecifierRange(startSpecifier, specifierLen));
7302
7303 // Since more arguments than conversion tokens are given, by extension
7304 // all arguments are covered, so mark this as so.
7305 UncoveredArg.setAllCovered();
7306 return false;
7307 }
7308 return true;
7309}
7310
7311template<typename Range>
7312void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7314 bool IsStringLocation,
7315 Range StringRange,
7316 ArrayRef<FixItHint> FixIt) {
7317 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7318 Loc, IsStringLocation, StringRange, FixIt);
7319}
7320
7321/// If the format string is not within the function call, emit a note
7322/// so that the function call and string are in diagnostic messages.
7323///
7324/// \param InFunctionCall if true, the format string is within the function
7325/// call and only one diagnostic message will be produced. Otherwise, an
7326/// extra note will be emitted pointing to location of the format string.
7327///
7328/// \param ArgumentExpr the expression that is passed as the format string
7329/// argument in the function call. Used for getting locations when two
7330/// diagnostics are emitted.
7331///
7332/// \param PDiag the callee should already have provided any strings for the
7333/// diagnostic message. This function only adds locations and fixits
7334/// to diagnostics.
7335///
7336/// \param Loc primary location for diagnostic. If two diagnostics are
7337/// required, one will be at Loc and a new SourceLocation will be created for
7338/// the other one.
7339///
7340/// \param IsStringLocation if true, Loc points to the format string should be
7341/// used for the note. Otherwise, Loc points to the argument list and will
7342/// be used with PDiag.
7343///
7344/// \param StringRange some or all of the string to highlight. This is
7345/// templated so it can accept either a CharSourceRange or a SourceRange.
7346///
7347/// \param FixIt optional fix it hint for the format string.
7348template <typename Range>
7349void CheckFormatHandler::EmitFormatDiagnostic(
7350 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7351 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7352 Range StringRange, ArrayRef<FixItHint> FixIt) {
7353 if (InFunctionCall) {
7354 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7355 D << StringRange;
7356 D << FixIt;
7357 } else {
7358 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7359 << ArgumentExpr->getSourceRange();
7360
7362 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7363 diag::note_format_string_defined);
7364
7365 Note << StringRange;
7366 Note << FixIt;
7367 }
7368}
7369
7370//===--- CHECK: Printf format string checking -----------------------------===//
7371
7372namespace {
7373
7374class CheckPrintfHandler : public CheckFormatHandler {
7375public:
7376 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7377 const Expr *origFormatExpr, const FormatStringType type,
7378 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
7379 const char *beg, Sema::FormatArgumentPassingKind APK,
7380 ArrayRef<const Expr *> Args, unsigned formatIdx,
7381 bool inFunctionCall, VariadicCallType CallType,
7382 llvm::SmallBitVector &CheckedVarArgs,
7383 UncoveredArgHandler &UncoveredArg)
7384 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7385 numDataArgs, beg, APK, Args, formatIdx,
7386 inFunctionCall, CallType, CheckedVarArgs,
7387 UncoveredArg) {}
7388
7389 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
7390
7391 /// Returns true if '%@' specifiers are allowed in the format string.
7392 bool allowsObjCArg() const {
7393 return FSType == FormatStringType::NSString ||
7394 FSType == FormatStringType::OSLog ||
7395 FSType == FormatStringType::OSTrace;
7396 }
7397
7398 bool HandleInvalidPrintfConversionSpecifier(
7400 const char *startSpecifier,
7401 unsigned specifierLen) override;
7402
7403 void handleInvalidMaskType(StringRef MaskType) override;
7404
7405 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7406 const char *startSpecifier, unsigned specifierLen,
7407 const TargetInfo &Target) override;
7408 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7409 const char *StartSpecifier,
7410 unsigned SpecifierLen,
7411 const Expr *E);
7412
7413 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7414 const char *startSpecifier, unsigned specifierLen);
7415 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7417 unsigned type,
7418 const char *startSpecifier, unsigned specifierLen);
7419 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7420 const analyze_printf::OptionalFlag &flag,
7421 const char *startSpecifier, unsigned specifierLen);
7422 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7423 const analyze_printf::OptionalFlag &ignoredFlag,
7424 const analyze_printf::OptionalFlag &flag,
7425 const char *startSpecifier, unsigned specifierLen);
7426 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7427 const Expr *E);
7428
7429 void HandleEmptyObjCModifierFlag(const char *startFlag,
7430 unsigned flagLen) override;
7431
7432 void HandleInvalidObjCModifierFlag(const char *startFlag,
7433 unsigned flagLen) override;
7434
7435 void
7436 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7437 const char *flagsEnd,
7438 const char *conversionPosition) override;
7439};
7440
7441/// Keeps around the information needed to verify that two specifiers are
7442/// compatible.
7443class EquatableFormatArgument {
7444public:
7445 enum SpecifierSensitivity : unsigned {
7446 SS_None,
7447 SS_Private,
7448 SS_Public,
7449 SS_Sensitive
7450 };
7451
7452 enum FormatArgumentRole : unsigned {
7453 FAR_Data,
7454 FAR_FieldWidth,
7455 FAR_Precision,
7456 FAR_Auxiliary, // FreeBSD kernel %b and %D
7457 };
7458
7459private:
7462 StringRef SpecifierLetter;
7464 SourceLocation ElementLoc;
7465 FormatArgumentRole Role : 2;
7466 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
7467 unsigned Position : 14;
7468 unsigned ModifierFor : 14; // not set for FAR_Data
7469
7470 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
7471 bool InFunctionCall) const;
7472
7473public:
7474 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
7476 StringRef SpecifierLetter,
7478 FormatArgumentRole Role,
7479 SpecifierSensitivity Sensitivity, unsigned Position,
7480 unsigned ModifierFor)
7481 : ArgType(ArgType), LengthMod(LengthMod),
7482 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
7483 Role(Role), Sensitivity(Sensitivity), Position(Position),
7484 ModifierFor(ModifierFor) {}
7485
7486 unsigned getPosition() const { return Position; }
7487 SourceLocation getSourceLocation() const { return ElementLoc; }
7488 CharSourceRange getSourceRange() const { return Range; }
7489 analyze_format_string::LengthModifier getLengthModifier() const {
7490 return analyze_format_string::LengthModifier(nullptr, LengthMod);
7491 }
7492 void setModifierFor(unsigned V) { ModifierFor = V; }
7493
7494 std::string buildFormatSpecifier() const {
7495 std::string result;
7496 llvm::raw_string_ostream(result)
7497 << getLengthModifier().toString() << SpecifierLetter;
7498 return result;
7499 }
7500
7501 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
7502 const Expr *FmtExpr, bool InFunctionCall) const;
7503};
7504
7505/// Turns format strings into lists of EquatableSpecifier objects.
7506class DecomposePrintfHandler : public CheckPrintfHandler {
7508 bool HadError;
7509
7510 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7511 const Expr *origFormatExpr,
7512 const FormatStringType type, unsigned firstDataArg,
7513 unsigned numDataArgs, bool isObjC, const char *beg,
7515 ArrayRef<const Expr *> Args, unsigned formatIdx,
7516 bool inFunctionCall, VariadicCallType CallType,
7517 llvm::SmallBitVector &CheckedVarArgs,
7518 UncoveredArgHandler &UncoveredArg,
7520 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7521 numDataArgs, isObjC, beg, APK, Args, formatIdx,
7522 inFunctionCall, CallType, CheckedVarArgs,
7523 UncoveredArg),
7524 Specs(Specs), HadError(false) {}
7525
7526public:
7527 static bool
7528 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
7529 FormatStringType type, bool IsObjC, bool InFunctionCall,
7531
7532 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7533 const char *startSpecifier,
7534 unsigned specifierLen,
7535 const TargetInfo &Target) override;
7536};
7537
7538} // namespace
7539
7540bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7541 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
7542 unsigned specifierLen) {
7544 FS.getConversionSpecifier();
7545
7546 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7547 getLocationOfByte(CS.getStart()),
7548 startSpecifier, specifierLen,
7549 CS.getStart(), CS.getLength());
7550}
7551
7552void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7553 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7554}
7555
7556bool CheckPrintfHandler::HandleAmount(
7557 const analyze_format_string::OptionalAmount &Amt, unsigned k,
7558 const char *startSpecifier, unsigned specifierLen) {
7559 if (Amt.hasDataArgument()) {
7560 if (HasFormatArguments()) {
7561 unsigned argIndex = Amt.getArgIndex();
7562 if (argIndex >= NumDataArgs) {
7563 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7564 << k,
7565 getLocationOfByte(Amt.getStart()),
7566 /*IsStringLocation*/ true,
7567 getSpecifierRange(startSpecifier, specifierLen));
7568 // Don't do any more checking. We will just emit
7569 // spurious errors.
7570 return false;
7571 }
7572
7573 // Type check the data argument. It should be an 'int'.
7574 // Although not in conformance with C99, we also allow the argument to be
7575 // an 'unsigned int' as that is a reasonably safe case. GCC also
7576 // doesn't emit a warning for that case.
7577 CoveredArgs.set(argIndex);
7578 const Expr *Arg = getDataArg(argIndex);
7579 if (!Arg)
7580 return false;
7581
7582 QualType T = Arg->getType();
7583
7584 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7585 assert(AT.isValid());
7586
7587 if (!AT.matchesType(S.Context, T)) {
7588 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7590 << T << Arg->getSourceRange(),
7591 getLocationOfByte(Amt.getStart()),
7592 /*IsStringLocation*/true,
7593 getSpecifierRange(startSpecifier, specifierLen));
7594 // Don't do any more checking. We will just emit
7595 // spurious errors.
7596 return false;
7597 }
7598 }
7599 }
7600 return true;
7601}
7602
7603void CheckPrintfHandler::HandleInvalidAmount(
7606 unsigned type,
7607 const char *startSpecifier,
7608 unsigned specifierLen) {
7610 FS.getConversionSpecifier();
7611
7612 FixItHint fixit =
7614 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7615 Amt.getConstantLength()))
7616 : FixItHint();
7617
7618 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7619 << type << CS.toString(),
7620 getLocationOfByte(Amt.getStart()),
7621 /*IsStringLocation*/true,
7622 getSpecifierRange(startSpecifier, specifierLen),
7623 fixit);
7624}
7625
7626void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7627 const analyze_printf::OptionalFlag &flag,
7628 const char *startSpecifier,
7629 unsigned specifierLen) {
7630 // Warn about pointless flag with a fixit removal.
7632 FS.getConversionSpecifier();
7633 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7634 << flag.toString() << CS.toString(),
7635 getLocationOfByte(flag.getPosition()),
7636 /*IsStringLocation*/true,
7637 getSpecifierRange(startSpecifier, specifierLen),
7639 getSpecifierRange(flag.getPosition(), 1)));
7640}
7641
7642void CheckPrintfHandler::HandleIgnoredFlag(
7644 const analyze_printf::OptionalFlag &ignoredFlag,
7645 const analyze_printf::OptionalFlag &flag,
7646 const char *startSpecifier,
7647 unsigned specifierLen) {
7648 // Warn about ignored flag with a fixit removal.
7649 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7650 << ignoredFlag.toString() << flag.toString(),
7651 getLocationOfByte(ignoredFlag.getPosition()),
7652 /*IsStringLocation*/true,
7653 getSpecifierRange(startSpecifier, specifierLen),
7655 getSpecifierRange(ignoredFlag.getPosition(), 1)));
7656}
7657
7658void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7659 unsigned flagLen) {
7660 // Warn about an empty flag.
7661 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7662 getLocationOfByte(startFlag),
7663 /*IsStringLocation*/true,
7664 getSpecifierRange(startFlag, flagLen));
7665}
7666
7667void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7668 unsigned flagLen) {
7669 // Warn about an invalid flag.
7670 auto Range = getSpecifierRange(startFlag, flagLen);
7671 StringRef flag(startFlag, flagLen);
7672 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7673 getLocationOfByte(startFlag),
7674 /*IsStringLocation*/true,
7676}
7677
7678void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7679 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7680 // Warn about using '[...]' without a '@' conversion.
7681 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7682 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7683 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7684 getLocationOfByte(conversionPosition),
7685 /*IsStringLocation*/ true, Range,
7687}
7688
7689void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
7690 const Expr *FmtExpr,
7691 bool InFunctionCall) const {
7692 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
7693 ElementLoc, true, Range);
7694}
7695
7696bool EquatableFormatArgument::VerifyCompatible(
7697 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
7698 bool InFunctionCall) const {
7700 if (Role != Other.Role) {
7701 // diagnose and stop
7702 EmitDiagnostic(
7703 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
7704 FmtExpr, InFunctionCall);
7705 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
7706 return false;
7707 }
7708
7709 if (Role != FAR_Data) {
7710 if (ModifierFor != Other.ModifierFor) {
7711 // diagnose and stop
7712 EmitDiagnostic(S,
7713 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
7714 << (ModifierFor + 1) << (Other.ModifierFor + 1),
7715 FmtExpr, InFunctionCall);
7716 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
7717 return false;
7718 }
7719 return true;
7720 }
7721
7722 bool HadError = false;
7723 if (Sensitivity != Other.Sensitivity) {
7724 // diagnose and continue
7725 EmitDiagnostic(S,
7726 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
7727 << Sensitivity << Other.Sensitivity,
7728 FmtExpr, InFunctionCall);
7729 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7730 << 0 << Other.Range;
7731 }
7732
7733 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
7734 case MK::Match:
7735 break;
7736
7737 case MK::MatchPromotion:
7738 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
7739 // MatchPromotion is treated as a failure by format_matches.
7740 case MK::NoMatch:
7741 case MK::NoMatchTypeConfusion:
7742 case MK::NoMatchPromotionTypeConfusion:
7743 EmitDiagnostic(S,
7744 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
7745 << buildFormatSpecifier()
7746 << Other.buildFormatSpecifier(),
7747 FmtExpr, InFunctionCall);
7748 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7749 << 0 << Other.Range;
7750 break;
7751
7752 case MK::NoMatchPedantic:
7753 EmitDiagnostic(S,
7754 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
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::NoMatchSignedness:
7763 EmitDiagnostic(S,
7764 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
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 return !HadError;
7773}
7774
7775bool DecomposePrintfHandler::GetSpecifiers(
7776 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
7777 FormatStringType Type, bool IsObjC, bool InFunctionCall,
7779 StringRef Data = FSL->getString();
7780 const char *Str = Data.data();
7781 llvm::SmallBitVector BV;
7782 UncoveredArgHandler UA;
7783 const Expr *PrintfArgs[] = {FSL->getFormatString()};
7784 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
7785 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
7786 InFunctionCall, VariadicCallType::DoesNotApply, BV,
7787 UA, Args);
7788
7790 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
7792 H.DoneProcessing();
7793 if (H.HadError)
7794 return false;
7795
7796 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
7797 const EquatableFormatArgument &B) {
7798 return A.getPosition() < B.getPosition();
7799 });
7800 return true;
7801}
7802
7803bool DecomposePrintfHandler::HandlePrintfSpecifier(
7804 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
7805 unsigned specifierLen, const TargetInfo &Target) {
7806 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
7807 specifierLen, Target)) {
7808 HadError = true;
7809 return false;
7810 }
7811
7812 // Do not add any specifiers to the list for %%. This is possibly incorrect
7813 // if using a precision/width with a data argument, but that combination is
7814 // meaningless and we wouldn't know which format to attach the
7815 // precision/width to.
7816 const auto &CS = FS.getConversionSpecifier();
7818 return true;
7819
7820 // have to patch these to have the right ModifierFor if they are used
7821 const unsigned Unset = ~0;
7822 unsigned FieldWidthIndex = Unset;
7823 unsigned PrecisionIndex = Unset;
7824
7825 // field width?
7826 const auto &FieldWidth = FS.getFieldWidth();
7827 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
7828 FieldWidthIndex = Specs.size();
7829 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
7830 getLocationOfByte(FieldWidth.getStart()),
7832 FieldWidth.getArgType(S.Context),
7833 EquatableFormatArgument::FAR_FieldWidth,
7834 EquatableFormatArgument::SS_None,
7835 FieldWidth.usesPositionalArg()
7836 ? FieldWidth.getPositionalArgIndex() - 1
7837 : FieldWidthIndex,
7838 0);
7839 }
7840 // precision?
7841 const auto &Precision = FS.getPrecision();
7842 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
7843 PrecisionIndex = Specs.size();
7844 Specs.emplace_back(
7845 getSpecifierRange(startSpecifier, specifierLen),
7846 getLocationOfByte(Precision.getStart()),
7848 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
7849 EquatableFormatArgument::SS_None,
7850 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
7851 : PrecisionIndex,
7852 0);
7853 }
7854
7855 // this specifier
7856 unsigned SpecIndex =
7857 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
7858 if (FieldWidthIndex != Unset)
7859 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
7860 if (PrecisionIndex != Unset)
7861 Specs[PrecisionIndex].setModifierFor(SpecIndex);
7862
7863 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
7864 if (FS.isPrivate())
7865 Sensitivity = EquatableFormatArgument::SS_Private;
7866 else if (FS.isPublic())
7867 Sensitivity = EquatableFormatArgument::SS_Public;
7868 else if (FS.isSensitive())
7869 Sensitivity = EquatableFormatArgument::SS_Sensitive;
7870 else
7871 Sensitivity = EquatableFormatArgument::SS_None;
7872
7873 Specs.emplace_back(
7874 getSpecifierRange(startSpecifier, specifierLen),
7875 getLocationOfByte(CS.getStart()), FS.getLengthModifier().getKind(),
7876 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
7877 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
7878
7879 // auxiliary argument?
7882 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
7883 getLocationOfByte(CS.getStart()),
7885 CS.getCharacters(),
7887 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
7888 SpecIndex + 1, SpecIndex);
7889 }
7890 return true;
7891}
7892
7893// Determines if the specified is a C++ class or struct containing
7894// a member with the specified name and kind (e.g. a CXXMethodDecl named
7895// "c_str()").
7896template<typename MemberKind>
7898CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7899 auto *RD = Ty->getAsCXXRecordDecl();
7901
7902 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
7903 return Results;
7904
7905 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7908
7909 // We just need to include all members of the right kind turned up by the
7910 // filter, at this point.
7911 if (S.LookupQualifiedName(R, RD))
7912 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7913 NamedDecl *decl = (*I)->getUnderlyingDecl();
7914 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7915 Results.insert(FK);
7916 }
7917 return Results;
7918}
7919
7920/// Check if we could call '.c_str()' on an object.
7921///
7922/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7923/// allow the call, or if it would be ambiguous).
7925 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7926
7927 MethodSet Results =
7928 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7929 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7930 MI != ME; ++MI)
7931 if ((*MI)->getMinRequiredArguments() == 0)
7932 return true;
7933 return false;
7934}
7935
7936// Check if a (w)string was passed when a (w)char* was needed, and offer a
7937// better diagnostic if so. AT is assumed to be valid.
7938// Returns true when a c_str() conversion method is found.
7939bool CheckPrintfHandler::checkForCStrMembers(
7940 const analyze_printf::ArgType &AT, const Expr *E) {
7941 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7942
7943 MethodSet Results =
7944 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7945
7946 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7947 MI != ME; ++MI) {
7948 const CXXMethodDecl *Method = *MI;
7949 if (Method->getMinRequiredArguments() == 0 &&
7950 AT.matchesType(S.Context, Method->getReturnType())) {
7951 // FIXME: Suggest parens if the expression needs them.
7953 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7954 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7955 return true;
7956 }
7957 }
7958
7959 return false;
7960}
7961
7962bool CheckPrintfHandler::HandlePrintfSpecifier(
7963 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
7964 unsigned specifierLen, const TargetInfo &Target) {
7965 using namespace analyze_format_string;
7966 using namespace analyze_printf;
7967
7968 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7969
7970 if (FS.consumesDataArgument()) {
7971 if (atFirstArg) {
7972 atFirstArg = false;
7973 usesPositionalArgs = FS.usesPositionalArg();
7974 }
7975 else if (usesPositionalArgs != FS.usesPositionalArg()) {
7976 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7977 startSpecifier, specifierLen);
7978 return false;
7979 }
7980 }
7981
7982 // First check if the field width, precision, and conversion specifier
7983 // have matching data arguments.
7984 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7985 startSpecifier, specifierLen)) {
7986 return false;
7987 }
7988
7989 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7990 startSpecifier, specifierLen)) {
7991 return false;
7992 }
7993
7994 if (!CS.consumesDataArgument()) {
7995 // FIXME: Technically specifying a precision or field width here
7996 // makes no sense. Worth issuing a warning at some point.
7997 return true;
7998 }
7999
8000 // Consume the argument.
8001 unsigned argIndex = FS.getArgIndex();
8002 if (argIndex < NumDataArgs) {
8003 // The check to see if the argIndex is valid will come later.
8004 // We set the bit here because we may exit early from this
8005 // function if we encounter some other error.
8006 CoveredArgs.set(argIndex);
8007 }
8008
8009 // FreeBSD kernel extensions.
8010 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8011 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8012 // We need at least two arguments.
8013 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8014 return false;
8015
8016 if (HasFormatArguments()) {
8017 // Claim the second argument.
8018 CoveredArgs.set(argIndex + 1);
8019
8020 // Type check the first argument (int for %b, pointer for %D)
8021 const Expr *Ex = getDataArg(argIndex);
8022 const analyze_printf::ArgType &AT =
8023 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
8024 ? ArgType(S.Context.IntTy)
8025 : ArgType::CPointerTy;
8026 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8027 EmitFormatDiagnostic(
8028 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8029 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8030 << false << Ex->getSourceRange(),
8031 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8032 getSpecifierRange(startSpecifier, specifierLen));
8033
8034 // Type check the second argument (char * for both %b and %D)
8035 Ex = getDataArg(argIndex + 1);
8036 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8037 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8038 EmitFormatDiagnostic(
8039 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8040 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8041 << false << Ex->getSourceRange(),
8042 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8043 getSpecifierRange(startSpecifier, specifierLen));
8044 }
8045 return true;
8046 }
8047
8048 // Check for using an Objective-C specific conversion specifier
8049 // in a non-ObjC literal.
8050 if (!allowsObjCArg() && CS.isObjCArg()) {
8051 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8052 specifierLen);
8053 }
8054
8055 // %P can only be used with os_log.
8056 if (FSType != FormatStringType::OSLog &&
8057 CS.getKind() == ConversionSpecifier::PArg) {
8058 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8059 specifierLen);
8060 }
8061
8062 // %n is not allowed with os_log.
8063 if (FSType == FormatStringType::OSLog &&
8064 CS.getKind() == ConversionSpecifier::nArg) {
8065 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8066 getLocationOfByte(CS.getStart()),
8067 /*IsStringLocation*/ false,
8068 getSpecifierRange(startSpecifier, specifierLen));
8069
8070 return true;
8071 }
8072
8073 // Only scalars are allowed for os_trace.
8074 if (FSType == FormatStringType::OSTrace &&
8075 (CS.getKind() == ConversionSpecifier::PArg ||
8076 CS.getKind() == ConversionSpecifier::sArg ||
8077 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8078 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8079 specifierLen);
8080 }
8081
8082 // Check for use of public/private annotation outside of os_log().
8083 if (FSType != FormatStringType::OSLog) {
8084 if (FS.isPublic().isSet()) {
8085 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8086 << "public",
8087 getLocationOfByte(FS.isPublic().getPosition()),
8088 /*IsStringLocation*/ false,
8089 getSpecifierRange(startSpecifier, specifierLen));
8090 }
8091 if (FS.isPrivate().isSet()) {
8092 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8093 << "private",
8094 getLocationOfByte(FS.isPrivate().getPosition()),
8095 /*IsStringLocation*/ false,
8096 getSpecifierRange(startSpecifier, specifierLen));
8097 }
8098 }
8099
8100 const llvm::Triple &Triple = Target.getTriple();
8101 if (CS.getKind() == ConversionSpecifier::nArg &&
8102 (Triple.isAndroid() || Triple.isOSFuchsia())) {
8103 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
8104 getLocationOfByte(CS.getStart()),
8105 /*IsStringLocation*/ false,
8106 getSpecifierRange(startSpecifier, specifierLen));
8107 }
8108
8109 // Check for invalid use of field width
8110 if (!FS.hasValidFieldWidth()) {
8111 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8112 startSpecifier, specifierLen);
8113 }
8114
8115 // Check for invalid use of precision
8116 if (!FS.hasValidPrecision()) {
8117 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8118 startSpecifier, specifierLen);
8119 }
8120
8121 // Precision is mandatory for %P specifier.
8122 if (CS.getKind() == ConversionSpecifier::PArg &&
8123 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8124 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8125 getLocationOfByte(startSpecifier),
8126 /*IsStringLocation*/ false,
8127 getSpecifierRange(startSpecifier, specifierLen));
8128 }
8129
8130 // Check each flag does not conflict with any other component.
8131 if (!FS.hasValidThousandsGroupingPrefix())
8132 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8133 if (!FS.hasValidLeadingZeros())
8134 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8135 if (!FS.hasValidPlusPrefix())
8136 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8137 if (!FS.hasValidSpacePrefix())
8138 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8139 if (!FS.hasValidAlternativeForm())
8140 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8141 if (!FS.hasValidLeftJustified())
8142 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8143
8144 // Check that flags are not ignored by another flag
8145 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8146 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8147 startSpecifier, specifierLen);
8148 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8149 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8150 startSpecifier, specifierLen);
8151
8152 // Check the length modifier is valid with the given conversion specifier.
8153 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8154 S.getLangOpts()))
8155 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8156 diag::warn_format_nonsensical_length);
8157 else if (!FS.hasStandardLengthModifier())
8158 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8159 else if (!FS.hasStandardLengthConversionCombination())
8160 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8161 diag::warn_format_non_standard_conversion_spec);
8162
8163 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8164 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8165
8166 // The remaining checks depend on the data arguments.
8167 if (!HasFormatArguments())
8168 return true;
8169
8170 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8171 return false;
8172
8173 const Expr *Arg = getDataArg(argIndex);
8174 if (!Arg)
8175 return true;
8176
8177 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8178}
8179
8180static bool requiresParensToAddCast(const Expr *E) {
8181 // FIXME: We should have a general way to reason about operator
8182 // precedence and whether parens are actually needed here.
8183 // Take care of a few common cases where they aren't.
8184 const Expr *Inside = E->IgnoreImpCasts();
8185 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8186 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8187
8188 switch (Inside->getStmtClass()) {
8189 case Stmt::ArraySubscriptExprClass:
8190 case Stmt::CallExprClass:
8191 case Stmt::CharacterLiteralClass:
8192 case Stmt::CXXBoolLiteralExprClass:
8193 case Stmt::DeclRefExprClass:
8194 case Stmt::FloatingLiteralClass:
8195 case Stmt::IntegerLiteralClass:
8196 case Stmt::MemberExprClass:
8197 case Stmt::ObjCArrayLiteralClass:
8198 case Stmt::ObjCBoolLiteralExprClass:
8199 case Stmt::ObjCBoxedExprClass:
8200 case Stmt::ObjCDictionaryLiteralClass:
8201 case Stmt::ObjCEncodeExprClass:
8202 case Stmt::ObjCIvarRefExprClass:
8203 case Stmt::ObjCMessageExprClass:
8204 case Stmt::ObjCPropertyRefExprClass:
8205 case Stmt::ObjCStringLiteralClass:
8206 case Stmt::ObjCSubscriptRefExprClass:
8207 case Stmt::ParenExprClass:
8208 case Stmt::StringLiteralClass:
8209 case Stmt::UnaryOperatorClass:
8210 return false;
8211 default:
8212 return true;
8213 }
8214}
8215
8216static std::pair<QualType, StringRef>
8218 QualType IntendedTy,
8219 const Expr *E) {
8220 // Use a 'while' to peel off layers of typedefs.
8221 QualType TyTy = IntendedTy;
8222 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8223 StringRef Name = UserTy->getDecl()->getName();
8224 QualType CastTy = llvm::StringSwitch<QualType>(Name)
8225 .Case("CFIndex", Context.getNSIntegerType())
8226 .Case("NSInteger", Context.getNSIntegerType())
8227 .Case("NSUInteger", Context.getNSUIntegerType())
8228 .Case("SInt32", Context.IntTy)
8229 .Case("UInt32", Context.UnsignedIntTy)
8230 .Default(QualType());
8231
8232 if (!CastTy.isNull())
8233 return std::make_pair(CastTy, Name);
8234
8235 TyTy = UserTy->desugar();
8236 }
8237
8238 // Strip parens if necessary.
8239 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8240 return shouldNotPrintDirectly(Context,
8241 PE->getSubExpr()->getType(),
8242 PE->getSubExpr());
8243
8244 // If this is a conditional expression, then its result type is constructed
8245 // via usual arithmetic conversions and thus there might be no necessary
8246 // typedef sugar there. Recurse to operands to check for NSInteger &
8247 // Co. usage condition.
8248 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8249 QualType TrueTy, FalseTy;
8250 StringRef TrueName, FalseName;
8251
8252 std::tie(TrueTy, TrueName) =
8253 shouldNotPrintDirectly(Context,
8254 CO->getTrueExpr()->getType(),
8255 CO->getTrueExpr());
8256 std::tie(FalseTy, FalseName) =
8257 shouldNotPrintDirectly(Context,
8258 CO->getFalseExpr()->getType(),
8259 CO->getFalseExpr());
8260
8261 if (TrueTy == FalseTy)
8262 return std::make_pair(TrueTy, TrueName);
8263 else if (TrueTy.isNull())
8264 return std::make_pair(FalseTy, FalseName);
8265 else if (FalseTy.isNull())
8266 return std::make_pair(TrueTy, TrueName);
8267 }
8268
8269 return std::make_pair(QualType(), StringRef());
8270}
8271
8272/// Return true if \p ICE is an implicit argument promotion of an arithmetic
8273/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8274/// type do not count.
8275static bool
8277 QualType From = ICE->getSubExpr()->getType();
8278 QualType To = ICE->getType();
8279 // It's an integer promotion if the destination type is the promoted
8280 // source type.
8281 if (ICE->getCastKind() == CK_IntegralCast &&
8283 S.Context.getPromotedIntegerType(From) == To)
8284 return true;
8285 // Look through vector types, since we do default argument promotion for
8286 // those in OpenCL.
8287 if (const auto *VecTy = From->getAs<ExtVectorType>())
8288 From = VecTy->getElementType();
8289 if (const auto *VecTy = To->getAs<ExtVectorType>())
8290 To = VecTy->getElementType();
8291 // It's a floating promotion if the source type is a lower rank.
8292 return ICE->getCastKind() == CK_FloatingCast &&
8293 S.Context.getFloatingTypeOrder(From, To) < 0;
8294}
8295
8300 if (Diags.isIgnored(
8301 diag::warn_format_conversion_argument_type_mismatch_signedness,
8302 Loc) ||
8303 Diags.isIgnored(
8304 // Arbitrary -Wformat diagnostic to detect -Wno-format:
8305 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
8307 }
8308 }
8309 return Match;
8310}
8311
8312bool
8313CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8314 const char *StartSpecifier,
8315 unsigned SpecifierLen,
8316 const Expr *E) {
8317 using namespace analyze_format_string;
8318 using namespace analyze_printf;
8319
8320 // Now type check the data expression that matches the
8321 // format specifier.
8322 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8323 if (!AT.isValid())
8324 return true;
8325
8326 QualType ExprTy = E->getType();
8327 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8328 ExprTy = TET->getUnderlyingExpr()->getType();
8329 }
8330
8331 // When using the format attribute in C++, you can receive a function or an
8332 // array that will necessarily decay to a pointer when passed to the final
8333 // format consumer. Apply decay before type comparison.
8334 if (ExprTy->canDecayToPointerType())
8335 ExprTy = S.Context.getDecayedType(ExprTy);
8336
8337 // Diagnose attempts to print a boolean value as a character. Unlike other
8338 // -Wformat diagnostics, this is fine from a type perspective, but it still
8339 // doesn't make sense.
8340 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8342 const CharSourceRange &CSR =
8343 getSpecifierRange(StartSpecifier, SpecifierLen);
8344 SmallString<4> FSString;
8345 llvm::raw_svector_ostream os(FSString);
8346 FS.toString(os);
8347 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8348 << FSString,
8349 E->getExprLoc(), false, CSR);
8350 return true;
8351 }
8352
8353 // Diagnose attempts to use '%P' with ObjC object types, which will result in
8354 // dumping raw class data (like is-a pointer), not actual data.
8355 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::PArg &&
8356 ExprTy->isObjCObjectPointerType()) {
8357 const CharSourceRange &CSR =
8358 getSpecifierRange(StartSpecifier, SpecifierLen);
8359 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
8360 E->getExprLoc(), false, CSR);
8361 return true;
8362 }
8363
8364 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
8365 ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8366 ArgType::MatchKind OrigMatch = Match;
8367
8369 if (Match == ArgType::Match)
8370 return true;
8371
8372 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
8373 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
8374
8375 // Look through argument promotions for our error message's reported type.
8376 // This includes the integral and floating promotions, but excludes array
8377 // and function pointer decay (seeing that an argument intended to be a
8378 // string has type 'char [6]' is probably more confusing than 'char *') and
8379 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8380 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8381 if (isArithmeticArgumentPromotion(S, ICE)) {
8382 E = ICE->getSubExpr();
8383 ExprTy = E->getType();
8384
8385 // Check if we didn't match because of an implicit cast from a 'char'
8386 // or 'short' to an 'int'. This is done because printf is a varargs
8387 // function.
8388 if (ICE->getType() == S.Context.IntTy ||
8389 ICE->getType() == S.Context.UnsignedIntTy) {
8390 // All further checking is done on the subexpression
8391 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
8392 if (OrigMatch == ArgType::NoMatchSignedness &&
8393 ImplicitMatch != ArgType::NoMatchSignedness)
8394 // If the original match was a signedness match this match on the
8395 // implicit cast type also need to be signedness match otherwise we
8396 // might introduce new unexpected warnings from -Wformat-signedness.
8397 return true;
8398 ImplicitMatch = handleFormatSignedness(
8399 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
8400 if (ImplicitMatch == ArgType::Match)
8401 return true;
8402 }
8403 }
8404 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8405 // Special case for 'a', which has type 'int' in C.
8406 // Note, however, that we do /not/ want to treat multibyte constants like
8407 // 'MooV' as characters! This form is deprecated but still exists. In
8408 // addition, don't treat expressions as of type 'char' if one byte length
8409 // modifier is provided.
8410 if (ExprTy == S.Context.IntTy &&
8411 FS.getLengthModifier().getKind() != LengthModifier::AsChar)
8412 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
8413 ExprTy = S.Context.CharTy;
8414 // To improve check results, we consider a character literal in C
8415 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
8416 // more likely a type confusion situation, so we will suggest to
8417 // use '%hhd' instead by discarding the MatchPromotion.
8418 if (Match == ArgType::MatchPromotion)
8419 Match = ArgType::NoMatch;
8420 }
8421 }
8422 if (Match == ArgType::MatchPromotion) {
8423 // WG14 N2562 only clarified promotions in *printf
8424 // For NSLog in ObjC, just preserve -Wformat behavior
8425 if (!S.getLangOpts().ObjC &&
8426 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
8427 ImplicitMatch != ArgType::NoMatchTypeConfusion)
8428 return true;
8429 Match = ArgType::NoMatch;
8430 }
8431 if (ImplicitMatch == ArgType::NoMatchPedantic ||
8432 ImplicitMatch == ArgType::NoMatchTypeConfusion)
8433 Match = ImplicitMatch;
8434 assert(Match != ArgType::MatchPromotion);
8435
8436 // Look through unscoped enums to their underlying type.
8437 bool IsEnum = false;
8438 bool IsScopedEnum = false;
8439 QualType IntendedTy = ExprTy;
8440 if (const auto *ED = ExprTy->getAsEnumDecl()) {
8441 IntendedTy = ED->getIntegerType();
8442 if (!ED->isScoped()) {
8443 ExprTy = IntendedTy;
8444 // This controls whether we're talking about the underlying type or not,
8445 // which we only want to do when it's an unscoped enum.
8446 IsEnum = true;
8447 } else {
8448 IsScopedEnum = true;
8449 }
8450 }
8451
8452 // %C in an Objective-C context prints a unichar, not a wchar_t.
8453 // If the argument is an integer of some kind, believe the %C and suggest
8454 // a cast instead of changing the conversion specifier.
8455 if (isObjCContext() &&
8456 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8458 !ExprTy->isCharType()) {
8459 // 'unichar' is defined as a typedef of unsigned short, but we should
8460 // prefer using the typedef if it is visible.
8461 IntendedTy = S.Context.UnsignedShortTy;
8462
8463 // While we are here, check if the value is an IntegerLiteral that happens
8464 // to be within the valid range.
8465 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8466 const llvm::APInt &V = IL->getValue();
8467 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8468 return true;
8469 }
8470
8471 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8473 if (S.LookupName(Result, S.getCurScope())) {
8474 NamedDecl *ND = Result.getFoundDecl();
8475 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8476 if (TD->getUnderlyingType() == IntendedTy)
8477 IntendedTy =
8479 /*Qualifier=*/std::nullopt, TD);
8480 }
8481 }
8482 }
8483
8484 // Special-case some of Darwin's platform-independence types by suggesting
8485 // casts to primitive types that are known to be large enough.
8486 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8487 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8488 QualType CastTy;
8489 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8490 if (!CastTy.isNull()) {
8491 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8492 // (long in ASTContext). Only complain to pedants or when they're the
8493 // underlying type of a scoped enum (which always needs a cast).
8494 if (!IsScopedEnum &&
8495 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8496 (AT.isSizeT() || AT.isPtrdiffT()) &&
8497 AT.matchesType(S.Context, CastTy))
8498 Match = ArgType::NoMatchPedantic;
8499 IntendedTy = CastTy;
8500 ShouldNotPrintDirectly = true;
8501 }
8502 }
8503
8504 // We may be able to offer a FixItHint if it is a supported type.
8505 PrintfSpecifier fixedFS = FS;
8506 bool Success =
8507 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8508
8509 if (Success) {
8510 // Get the fix string from the fixed format specifier
8511 SmallString<16> buf;
8512 llvm::raw_svector_ostream os(buf);
8513 fixedFS.toString(os);
8514
8515 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8516
8517 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
8518 unsigned Diag;
8519 switch (Match) {
8520 case ArgType::Match:
8521 case ArgType::MatchPromotion:
8522 case ArgType::NoMatchPromotionTypeConfusion:
8523 llvm_unreachable("expected non-matching");
8524 case ArgType::NoMatchSignedness:
8525 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
8526 break;
8527 case ArgType::NoMatchPedantic:
8528 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8529 break;
8530 case ArgType::NoMatchTypeConfusion:
8531 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8532 break;
8533 case ArgType::NoMatch:
8534 Diag = diag::warn_format_conversion_argument_type_mismatch;
8535 break;
8536 }
8537
8538 // In this case, the specifier is wrong and should be changed to match
8539 // the argument.
8540 EmitFormatDiagnostic(S.PDiag(Diag)
8542 << IntendedTy << IsEnum << E->getSourceRange(),
8543 E->getBeginLoc(),
8544 /*IsStringLocation*/ false, SpecRange,
8545 FixItHint::CreateReplacement(SpecRange, os.str()));
8546 } else {
8547 // The canonical type for formatting this value is different from the
8548 // actual type of the expression. (This occurs, for example, with Darwin's
8549 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8550 // should be printed as 'long' for 64-bit compatibility.)
8551 // Rather than emitting a normal format/argument mismatch, we want to
8552 // add a cast to the recommended type (and correct the format string
8553 // if necessary). We should also do so for scoped enumerations.
8554 SmallString<16> CastBuf;
8555 llvm::raw_svector_ostream CastFix(CastBuf);
8556 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
8557 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8558 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
8559
8561 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
8562 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
8563 E->getExprLoc());
8564 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
8565 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8566
8567 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8568 // If there's already a cast present, just replace it.
8569 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8570 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8571
8572 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
8573 // If the expression has high enough precedence,
8574 // just write the C-style cast.
8575 Hints.push_back(
8576 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8577 } else {
8578 // Otherwise, add parens around the expression as well as the cast.
8579 CastFix << "(";
8580 Hints.push_back(
8581 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8582
8583 // We don't use getLocForEndOfToken because it returns invalid source
8584 // locations for macro expansions (by design).
8588 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8589 }
8590
8591 if (ShouldNotPrintDirectly && !IsScopedEnum) {
8592 // The expression has a type that should not be printed directly.
8593 // We extract the name from the typedef because we don't want to show
8594 // the underlying type in the diagnostic.
8595 StringRef Name;
8596 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
8597 Name = TypedefTy->getDecl()->getName();
8598 else
8599 Name = CastTyName;
8600 unsigned Diag = Match == ArgType::NoMatchPedantic
8601 ? diag::warn_format_argument_needs_cast_pedantic
8602 : diag::warn_format_argument_needs_cast;
8603 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8604 << E->getSourceRange(),
8605 E->getBeginLoc(), /*IsStringLocation=*/false,
8606 SpecRange, Hints);
8607 } else {
8608 // In this case, the expression could be printed using a different
8609 // specifier, but we've decided that the specifier is probably correct
8610 // and we should cast instead. Just use the normal warning message.
8611
8612 unsigned Diag =
8613 IsScopedEnum
8614 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8615 : diag::warn_format_conversion_argument_type_mismatch;
8616
8617 EmitFormatDiagnostic(
8618 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8619 << IsEnum << E->getSourceRange(),
8620 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8621 }
8622 }
8623 } else {
8624 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8625 SpecifierLen);
8626 // Since the warning for passing non-POD types to variadic functions
8627 // was deferred until now, we emit a warning for non-POD
8628 // arguments here.
8629 bool EmitTypeMismatch = false;
8630 switch (S.isValidVarArgType(ExprTy)) {
8631 case VarArgKind::Valid:
8633 unsigned Diag;
8634 switch (Match) {
8635 case ArgType::Match:
8636 case ArgType::MatchPromotion:
8637 case ArgType::NoMatchPromotionTypeConfusion:
8638 case ArgType::NoMatchSignedness:
8639 llvm_unreachable("expected non-matching");
8640 case ArgType::NoMatchPedantic:
8641 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8642 break;
8643 case ArgType::NoMatchTypeConfusion:
8644 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8645 break;
8646 case ArgType::NoMatch:
8647 Diag = diag::warn_format_conversion_argument_type_mismatch;
8648 break;
8649 }
8650
8651 EmitFormatDiagnostic(
8652 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8653 << IsEnum << CSR << E->getSourceRange(),
8654 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8655 break;
8656 }
8659 if (CallType == VariadicCallType::DoesNotApply) {
8660 EmitTypeMismatch = true;
8661 } else {
8662 EmitFormatDiagnostic(
8663 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8664 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8665 << AT.getRepresentativeTypeName(S.Context) << CSR
8666 << E->getSourceRange(),
8667 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8668 checkForCStrMembers(AT, E);
8669 }
8670 break;
8671
8673 if (CallType == VariadicCallType::DoesNotApply)
8674 EmitTypeMismatch = true;
8675 else if (ExprTy->isObjCObjectType())
8676 EmitFormatDiagnostic(
8677 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8678 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8679 << AT.getRepresentativeTypeName(S.Context) << CSR
8680 << E->getSourceRange(),
8681 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8682 else
8683 // FIXME: If this is an initializer list, suggest removing the braces
8684 // or inserting a cast to the target type.
8685 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8686 << isa<InitListExpr>(E) << ExprTy << CallType
8688 break;
8689 }
8690
8691 if (EmitTypeMismatch) {
8692 // The function is not variadic, so we do not generate warnings about
8693 // being allowed to pass that object as a variadic argument. Instead,
8694 // since there are inherently no printf specifiers for types which cannot
8695 // be passed as variadic arguments, emit a plain old specifier mismatch
8696 // argument.
8697 EmitFormatDiagnostic(
8698 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8699 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
8700 << E->getSourceRange(),
8701 E->getBeginLoc(), false, CSR);
8702 }
8703
8704 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8705 "format string specifier index out of range");
8706 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8707 }
8708
8709 return true;
8710}
8711
8712//===--- CHECK: Scanf format string checking ------------------------------===//
8713
8714namespace {
8715
8716class CheckScanfHandler : public CheckFormatHandler {
8717public:
8718 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8719 const Expr *origFormatExpr, FormatStringType type,
8720 unsigned firstDataArg, unsigned numDataArgs,
8721 const char *beg, Sema::FormatArgumentPassingKind APK,
8722 ArrayRef<const Expr *> Args, unsigned formatIdx,
8723 bool inFunctionCall, VariadicCallType CallType,
8724 llvm::SmallBitVector &CheckedVarArgs,
8725 UncoveredArgHandler &UncoveredArg)
8726 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8727 numDataArgs, beg, APK, Args, formatIdx,
8728 inFunctionCall, CallType, CheckedVarArgs,
8729 UncoveredArg) {}
8730
8731 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8732 const char *startSpecifier,
8733 unsigned specifierLen) override;
8734
8735 bool HandleInvalidScanfConversionSpecifier(
8737 const char *startSpecifier,
8738 unsigned specifierLen) override;
8739
8740 void HandleIncompleteScanList(const char *start, const char *end) override;
8741};
8742
8743} // namespace
8744
8745void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8746 const char *end) {
8747 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8748 getLocationOfByte(end), /*IsStringLocation*/true,
8749 getSpecifierRange(start, end - start));
8750}
8751
8752bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8754 const char *startSpecifier,
8755 unsigned specifierLen) {
8757 FS.getConversionSpecifier();
8758
8759 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8760 getLocationOfByte(CS.getStart()),
8761 startSpecifier, specifierLen,
8762 CS.getStart(), CS.getLength());
8763}
8764
8765bool CheckScanfHandler::HandleScanfSpecifier(
8767 const char *startSpecifier,
8768 unsigned specifierLen) {
8769 using namespace analyze_scanf;
8770 using namespace analyze_format_string;
8771
8772 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8773
8774 // Handle case where '%' and '*' don't consume an argument. These shouldn't
8775 // be used to decide if we are using positional arguments consistently.
8776 if (FS.consumesDataArgument()) {
8777 if (atFirstArg) {
8778 atFirstArg = false;
8779 usesPositionalArgs = FS.usesPositionalArg();
8780 }
8781 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8782 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8783 startSpecifier, specifierLen);
8784 return false;
8785 }
8786 }
8787
8788 // Check if the field with is non-zero.
8789 const OptionalAmount &Amt = FS.getFieldWidth();
8790 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8791 if (Amt.getConstantAmount() == 0) {
8792 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8793 Amt.getConstantLength());
8794 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8795 getLocationOfByte(Amt.getStart()),
8796 /*IsStringLocation*/true, R,
8798 }
8799 }
8800
8801 if (!FS.consumesDataArgument()) {
8802 // FIXME: Technically specifying a precision or field width here
8803 // makes no sense. Worth issuing a warning at some point.
8804 return true;
8805 }
8806
8807 // Consume the argument.
8808 unsigned argIndex = FS.getArgIndex();
8809 if (argIndex < NumDataArgs) {
8810 // The check to see if the argIndex is valid will come later.
8811 // We set the bit here because we may exit early from this
8812 // function if we encounter some other error.
8813 CoveredArgs.set(argIndex);
8814 }
8815
8816 // Check the length modifier is valid with the given conversion specifier.
8817 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8818 S.getLangOpts()))
8819 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8820 diag::warn_format_nonsensical_length);
8821 else if (!FS.hasStandardLengthModifier())
8822 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8823 else if (!FS.hasStandardLengthConversionCombination())
8824 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8825 diag::warn_format_non_standard_conversion_spec);
8826
8827 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8828 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8829
8830 // The remaining checks depend on the data arguments.
8831 if (!HasFormatArguments())
8832 return true;
8833
8834 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8835 return false;
8836
8837 // Check that the argument type matches the format specifier.
8838 const Expr *Ex = getDataArg(argIndex);
8839 if (!Ex)
8840 return true;
8841
8842 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8843
8844 if (!AT.isValid()) {
8845 return true;
8846 }
8847
8849 AT.matchesType(S.Context, Ex->getType());
8852 return true;
8855
8856 ScanfSpecifier fixedFS = FS;
8857 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8858 S.getLangOpts(), S.Context);
8859
8860 unsigned Diag =
8861 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8862 : Signedness
8863 ? diag::warn_format_conversion_argument_type_mismatch_signedness
8864 : diag::warn_format_conversion_argument_type_mismatch;
8865
8866 if (Success) {
8867 // Get the fix string from the fixed format specifier.
8868 SmallString<128> buf;
8869 llvm::raw_svector_ostream os(buf);
8870 fixedFS.toString(os);
8871
8872 EmitFormatDiagnostic(
8874 << Ex->getType() << false << Ex->getSourceRange(),
8875 Ex->getBeginLoc(),
8876 /*IsStringLocation*/ false,
8877 getSpecifierRange(startSpecifier, specifierLen),
8879 getSpecifierRange(startSpecifier, specifierLen), os.str()));
8880 } else {
8881 EmitFormatDiagnostic(S.PDiag(Diag)
8883 << Ex->getType() << false << Ex->getSourceRange(),
8884 Ex->getBeginLoc(),
8885 /*IsStringLocation*/ false,
8886 getSpecifierRange(startSpecifier, specifierLen));
8887 }
8888
8889 return true;
8890}
8891
8892static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
8894 const StringLiteral *Fmt,
8896 const Expr *FmtExpr, bool InFunctionCall) {
8897 bool HadError = false;
8898 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
8899 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
8900 while (FmtIter < FmtEnd && RefIter < RefEnd) {
8901 // In positional-style format strings, the same specifier can appear
8902 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
8903 // are sorted by getPosition(), and we process each range of equal
8904 // getPosition() values as one group.
8905 // RefArgs are taken from a string literal that was given to
8906 // attribute(format_matches), and if we got this far, we have already
8907 // verified that if it has positional specifiers that appear in multiple
8908 // locations, then they are all mutually compatible. What's left for us to
8909 // do is verify that all specifiers with the same position in FmtArgs are
8910 // compatible with the RefArgs specifiers. We check each specifier from
8911 // FmtArgs against the first member of the RefArgs group.
8912 for (; FmtIter < FmtEnd; ++FmtIter) {
8913 // Clang does not diagnose missing format specifiers in positional-style
8914 // strings (TODO: which it probably should do, as it is UB to skip over a
8915 // format argument). Skip specifiers if needed.
8916 if (FmtIter->getPosition() < RefIter->getPosition())
8917 continue;
8918
8919 // Delimits a new getPosition() value.
8920 if (FmtIter->getPosition() > RefIter->getPosition())
8921 break;
8922
8923 HadError |=
8924 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
8925 }
8926
8927 // Jump RefIter to the start of the next group.
8928 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
8929 return Arg.getPosition() != RefIter->getPosition();
8930 });
8931 }
8932
8933 if (FmtIter < FmtEnd) {
8934 CheckFormatHandler::EmitFormatDiagnostic(
8935 S, InFunctionCall, FmtExpr,
8936 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
8937 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
8938 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
8939 } else if (RefIter < RefEnd) {
8940 CheckFormatHandler::EmitFormatDiagnostic(
8941 S, InFunctionCall, FmtExpr,
8942 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
8943 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
8944 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
8945 << 1 << RefIter->getSourceRange();
8946 }
8947 return !HadError;
8948}
8949
8951 Sema &S, const FormatStringLiteral *FExpr,
8952 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
8954 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
8955 bool inFunctionCall, VariadicCallType CallType,
8956 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
8957 bool IgnoreStringsWithoutSpecifiers) {
8958 // CHECK: is the format string a wide literal?
8959 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8960 CheckFormatHandler::EmitFormatDiagnostic(
8961 S, inFunctionCall, Args[format_idx],
8962 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8963 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8964 return;
8965 }
8966
8967 // Str - The format string. NOTE: this is NOT null-terminated!
8968 StringRef StrRef = FExpr->getString();
8969 const char *Str = StrRef.data();
8970 // Account for cases where the string literal is truncated in a declaration.
8971 const ConstantArrayType *T =
8972 S.Context.getAsConstantArrayType(FExpr->getType());
8973 assert(T && "String literal not of constant array type!");
8974 size_t TypeSize = T->getZExtSize();
8975 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8976 const unsigned numDataArgs = Args.size() - firstDataArg;
8977
8978 if (IgnoreStringsWithoutSpecifiers &&
8980 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8981 return;
8982
8983 // Emit a warning if the string literal is truncated and does not contain an
8984 // embedded null character.
8985 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
8986 CheckFormatHandler::EmitFormatDiagnostic(
8987 S, inFunctionCall, Args[format_idx],
8988 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8989 FExpr->getBeginLoc(),
8990 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8991 return;
8992 }
8993
8994 // CHECK: empty format string?
8995 if (StrLen == 0 && numDataArgs > 0) {
8996 CheckFormatHandler::EmitFormatDiagnostic(
8997 S, inFunctionCall, Args[format_idx],
8998 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8999 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9000 return;
9001 }
9002
9008 bool IsObjC =
9010 if (ReferenceFormatString == nullptr) {
9011 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9012 numDataArgs, IsObjC, Str, APK, Args, format_idx,
9013 inFunctionCall, CallType, CheckedVarArgs,
9014 UncoveredArg);
9015
9017 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
9020 H.DoneProcessing();
9021 } else {
9023 Type, ReferenceFormatString, FExpr->getFormatString(),
9024 inFunctionCall ? nullptr : Args[format_idx]);
9025 }
9026 } else if (Type == FormatStringType::Scanf) {
9027 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9028 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
9029 CallType, CheckedVarArgs, UncoveredArg);
9030
9032 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9033 H.DoneProcessing();
9034 } // TODO: handle other formats
9035}
9036
9038 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
9039 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
9045 return true;
9046
9047 bool IsObjC =
9050 FormatStringLiteral RefLit = AuthoritativeFormatString;
9051 FormatStringLiteral TestLit = TestedFormatString;
9052 const Expr *Arg;
9053 bool DiagAtStringLiteral;
9054 if (FunctionCallArg) {
9055 Arg = FunctionCallArg;
9056 DiagAtStringLiteral = false;
9057 } else {
9058 Arg = TestedFormatString;
9059 DiagAtStringLiteral = true;
9060 }
9061 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
9062 AuthoritativeFormatString, Type,
9063 IsObjC, true, RefArgs) &&
9064 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
9065 DiagAtStringLiteral, FmtArgs)) {
9066 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
9067 TestedFormatString, FmtArgs, Arg,
9068 DiagAtStringLiteral);
9069 }
9070 return false;
9071}
9072
9074 const StringLiteral *Str) {
9080 return true;
9081
9082 FormatStringLiteral RefLit = Str;
9084 bool IsObjC =
9086 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
9087 true, Args))
9088 return false;
9089
9090 // Group arguments by getPosition() value, and check that each member of the
9091 // group is compatible with the first member. This verifies that when
9092 // positional arguments are used multiple times (such as %2$i %2$d), all uses
9093 // are mutually compatible. As an optimization, don't test the first member
9094 // against itself.
9095 bool HadError = false;
9096 auto Iter = Args.begin();
9097 auto End = Args.end();
9098 while (Iter != End) {
9099 const auto &FirstInGroup = *Iter;
9100 for (++Iter;
9101 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
9102 ++Iter) {
9103 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
9104 }
9105 }
9106 return !HadError;
9107}
9108
9110 // Str - The format string. NOTE: this is NOT null-terminated!
9111 StringRef StrRef = FExpr->getString();
9112 const char *Str = StrRef.data();
9113 // Account for cases where the string literal is truncated in a declaration.
9115 assert(T && "String literal not of constant array type!");
9116 size_t TypeSize = T->getZExtSize();
9117 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9118 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9119 getLangOpts(),
9121}
9122
9123//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9124
9125// Returns the related absolute value function that is larger, of 0 if one
9126// does not exist.
9127static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9128 switch (AbsFunction) {
9129 default:
9130 return 0;
9131
9132 case Builtin::BI__builtin_abs:
9133 return Builtin::BI__builtin_labs;
9134 case Builtin::BI__builtin_labs:
9135 return Builtin::BI__builtin_llabs;
9136 case Builtin::BI__builtin_llabs:
9137 return 0;
9138
9139 case Builtin::BI__builtin_fabsf:
9140 return Builtin::BI__builtin_fabs;
9141 case Builtin::BI__builtin_fabs:
9142 return Builtin::BI__builtin_fabsl;
9143 case Builtin::BI__builtin_fabsl:
9144 return 0;
9145
9146 case Builtin::BI__builtin_cabsf:
9147 return Builtin::BI__builtin_cabs;
9148 case Builtin::BI__builtin_cabs:
9149 return Builtin::BI__builtin_cabsl;
9150 case Builtin::BI__builtin_cabsl:
9151 return 0;
9152
9153 case Builtin::BIabs:
9154 return Builtin::BIlabs;
9155 case Builtin::BIlabs:
9156 return Builtin::BIllabs;
9157 case Builtin::BIllabs:
9158 return 0;
9159
9160 case Builtin::BIfabsf:
9161 return Builtin::BIfabs;
9162 case Builtin::BIfabs:
9163 return Builtin::BIfabsl;
9164 case Builtin::BIfabsl:
9165 return 0;
9166
9167 case Builtin::BIcabsf:
9168 return Builtin::BIcabs;
9169 case Builtin::BIcabs:
9170 return Builtin::BIcabsl;
9171 case Builtin::BIcabsl:
9172 return 0;
9173 }
9174}
9175
9176// Returns the argument type of the absolute value function.
9178 unsigned AbsType) {
9179 if (AbsType == 0)
9180 return QualType();
9181
9183 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9184 if (Error != ASTContext::GE_None)
9185 return QualType();
9186
9188 if (!FT)
9189 return QualType();
9190
9191 if (FT->getNumParams() != 1)
9192 return QualType();
9193
9194 return FT->getParamType(0);
9195}
9196
9197// Returns the best absolute value function, or zero, based on type and
9198// current absolute value function.
9199static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9200 unsigned AbsFunctionKind) {
9201 unsigned BestKind = 0;
9202 uint64_t ArgSize = Context.getTypeSize(ArgType);
9203 for (unsigned Kind = AbsFunctionKind; Kind != 0;
9204 Kind = getLargerAbsoluteValueFunction(Kind)) {
9205 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9206 if (Context.getTypeSize(ParamType) >= ArgSize) {
9207 if (BestKind == 0)
9208 BestKind = Kind;
9209 else if (Context.hasSameType(ParamType, ArgType)) {
9210 BestKind = Kind;
9211 break;
9212 }
9213 }
9214 }
9215 return BestKind;
9216}
9217
9223
9226 return AVK_Integer;
9227 if (T->isRealFloatingType())
9228 return AVK_Floating;
9229 if (T->isAnyComplexType())
9230 return AVK_Complex;
9231
9232 llvm_unreachable("Type not integer, floating, or complex");
9233}
9234
9235// Changes the absolute value function to a different type. Preserves whether
9236// the function is a builtin.
9237static unsigned changeAbsFunction(unsigned AbsKind,
9238 AbsoluteValueKind ValueKind) {
9239 switch (ValueKind) {
9240 case AVK_Integer:
9241 switch (AbsKind) {
9242 default:
9243 return 0;
9244 case Builtin::BI__builtin_fabsf:
9245 case Builtin::BI__builtin_fabs:
9246 case Builtin::BI__builtin_fabsl:
9247 case Builtin::BI__builtin_cabsf:
9248 case Builtin::BI__builtin_cabs:
9249 case Builtin::BI__builtin_cabsl:
9250 return Builtin::BI__builtin_abs;
9251 case Builtin::BIfabsf:
9252 case Builtin::BIfabs:
9253 case Builtin::BIfabsl:
9254 case Builtin::BIcabsf:
9255 case Builtin::BIcabs:
9256 case Builtin::BIcabsl:
9257 return Builtin::BIabs;
9258 }
9259 case AVK_Floating:
9260 switch (AbsKind) {
9261 default:
9262 return 0;
9263 case Builtin::BI__builtin_abs:
9264 case Builtin::BI__builtin_labs:
9265 case Builtin::BI__builtin_llabs:
9266 case Builtin::BI__builtin_cabsf:
9267 case Builtin::BI__builtin_cabs:
9268 case Builtin::BI__builtin_cabsl:
9269 return Builtin::BI__builtin_fabsf;
9270 case Builtin::BIabs:
9271 case Builtin::BIlabs:
9272 case Builtin::BIllabs:
9273 case Builtin::BIcabsf:
9274 case Builtin::BIcabs:
9275 case Builtin::BIcabsl:
9276 return Builtin::BIfabsf;
9277 }
9278 case AVK_Complex:
9279 switch (AbsKind) {
9280 default:
9281 return 0;
9282 case Builtin::BI__builtin_abs:
9283 case Builtin::BI__builtin_labs:
9284 case Builtin::BI__builtin_llabs:
9285 case Builtin::BI__builtin_fabsf:
9286 case Builtin::BI__builtin_fabs:
9287 case Builtin::BI__builtin_fabsl:
9288 return Builtin::BI__builtin_cabsf;
9289 case Builtin::BIabs:
9290 case Builtin::BIlabs:
9291 case Builtin::BIllabs:
9292 case Builtin::BIfabsf:
9293 case Builtin::BIfabs:
9294 case Builtin::BIfabsl:
9295 return Builtin::BIcabsf;
9296 }
9297 }
9298 llvm_unreachable("Unable to convert function");
9299}
9300
9301static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9302 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9303 if (!FnInfo)
9304 return 0;
9305
9306 switch (FDecl->getBuiltinID()) {
9307 default:
9308 return 0;
9309 case Builtin::BI__builtin_abs:
9310 case Builtin::BI__builtin_fabs:
9311 case Builtin::BI__builtin_fabsf:
9312 case Builtin::BI__builtin_fabsl:
9313 case Builtin::BI__builtin_labs:
9314 case Builtin::BI__builtin_llabs:
9315 case Builtin::BI__builtin_cabs:
9316 case Builtin::BI__builtin_cabsf:
9317 case Builtin::BI__builtin_cabsl:
9318 case Builtin::BIabs:
9319 case Builtin::BIlabs:
9320 case Builtin::BIllabs:
9321 case Builtin::BIfabs:
9322 case Builtin::BIfabsf:
9323 case Builtin::BIfabsl:
9324 case Builtin::BIcabs:
9325 case Builtin::BIcabsf:
9326 case Builtin::BIcabsl:
9327 return FDecl->getBuiltinID();
9328 }
9329 llvm_unreachable("Unknown Builtin type");
9330}
9331
9332// If the replacement is valid, emit a note with replacement function.
9333// Additionally, suggest including the proper header if not already included.
9335 unsigned AbsKind, QualType ArgType) {
9336 bool EmitHeaderHint = true;
9337 const char *HeaderName = nullptr;
9338 std::string FunctionName;
9339 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9340 FunctionName = "std::abs";
9341 if (ArgType->isIntegralOrEnumerationType()) {
9342 HeaderName = "cstdlib";
9343 } else if (ArgType->isRealFloatingType()) {
9344 HeaderName = "cmath";
9345 } else {
9346 llvm_unreachable("Invalid Type");
9347 }
9348
9349 // Lookup all std::abs
9350 if (NamespaceDecl *Std = S.getStdNamespace()) {
9354
9355 for (const auto *I : R) {
9356 const FunctionDecl *FDecl = nullptr;
9357 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9358 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9359 } else {
9360 FDecl = dyn_cast<FunctionDecl>(I);
9361 }
9362 if (!FDecl)
9363 continue;
9364
9365 // Found std::abs(), check that they are the right ones.
9366 if (FDecl->getNumParams() != 1)
9367 continue;
9368
9369 // Check that the parameter type can handle the argument.
9370 QualType ParamType = FDecl->getParamDecl(0)->getType();
9371 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9372 S.Context.getTypeSize(ArgType) <=
9373 S.Context.getTypeSize(ParamType)) {
9374 // Found a function, don't need the header hint.
9375 EmitHeaderHint = false;
9376 break;
9377 }
9378 }
9379 }
9380 } else {
9381 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9382 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9383
9384 if (HeaderName) {
9385 DeclarationName DN(&S.Context.Idents.get(FunctionName));
9388 S.LookupName(R, S.getCurScope());
9389
9390 if (R.isSingleResult()) {
9391 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9392 if (FD && FD->getBuiltinID() == AbsKind) {
9393 EmitHeaderHint = false;
9394 } else {
9395 return;
9396 }
9397 } else if (!R.empty()) {
9398 return;
9399 }
9400 }
9401 }
9402
9403 S.Diag(Loc, diag::note_replace_abs_function)
9404 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9405
9406 if (!HeaderName)
9407 return;
9408
9409 if (!EmitHeaderHint)
9410 return;
9411
9412 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9413 << FunctionName;
9414}
9415
9416template <std::size_t StrLen>
9417static bool IsStdFunction(const FunctionDecl *FDecl,
9418 const char (&Str)[StrLen]) {
9419 if (!FDecl)
9420 return false;
9421 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9422 return false;
9423 if (!FDecl->isInStdNamespace())
9424 return false;
9425
9426 return true;
9427}
9428
9429enum class MathCheck { NaN, Inf };
9430static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
9431 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
9432 return llvm::is_contained(names, calleeName);
9433 };
9434
9435 switch (Check) {
9436 case MathCheck::NaN:
9437 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
9438 "__builtin_nanf16", "__builtin_nanf128"});
9439 case MathCheck::Inf:
9440 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
9441 "__builtin_inff16", "__builtin_inff128"});
9442 }
9443 llvm_unreachable("unknown MathCheck");
9444}
9445
9446static bool IsInfinityFunction(const FunctionDecl *FDecl) {
9447 if (FDecl->getName() != "infinity")
9448 return false;
9449
9450 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
9451 const CXXRecordDecl *RDecl = MDecl->getParent();
9452 if (RDecl->getName() != "numeric_limits")
9453 return false;
9454
9455 if (const NamespaceDecl *NSDecl =
9456 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
9457 return NSDecl->isStdNamespace();
9458 }
9459
9460 return false;
9461}
9462
9463void Sema::CheckInfNaNFunction(const CallExpr *Call,
9464 const FunctionDecl *FDecl) {
9465 if (!FDecl->getIdentifier())
9466 return;
9467
9468 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
9469 if (FPO.getNoHonorNaNs() &&
9470 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
9471 IsInfOrNanFunction(FDecl->getName(), MathCheck::NaN))) {
9472 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9473 << 1 << 0 << Call->getSourceRange();
9474 return;
9475 }
9476
9477 if (FPO.getNoHonorInfs() &&
9478 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
9479 IsInfinityFunction(FDecl) ||
9480 IsInfOrNanFunction(FDecl->getName(), MathCheck::Inf))) {
9481 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9482 << 0 << 0 << Call->getSourceRange();
9483 }
9484}
9485
9486void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9487 const FunctionDecl *FDecl) {
9488 if (Call->getNumArgs() != 1)
9489 return;
9490
9491 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9492 bool IsStdAbs = IsStdFunction(FDecl, "abs");
9493 if (AbsKind == 0 && !IsStdAbs)
9494 return;
9495
9496 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9497 QualType ParamType = Call->getArg(0)->getType();
9498
9499 // Unsigned types cannot be negative. Suggest removing the absolute value
9500 // function call.
9501 if (ArgType->isUnsignedIntegerType()) {
9502 std::string FunctionName =
9503 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9504 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9505 Diag(Call->getExprLoc(), diag::note_remove_abs)
9506 << FunctionName
9507 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9508 return;
9509 }
9510
9511 // Taking the absolute value of a pointer is very suspicious, they probably
9512 // wanted to index into an array, dereference a pointer, call a function, etc.
9513 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9514 unsigned DiagType = 0;
9515 if (ArgType->isFunctionType())
9516 DiagType = 1;
9517 else if (ArgType->isArrayType())
9518 DiagType = 2;
9519
9520 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9521 return;
9522 }
9523
9524 // std::abs has overloads which prevent most of the absolute value problems
9525 // from occurring.
9526 if (IsStdAbs)
9527 return;
9528
9529 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9530 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9531
9532 // The argument and parameter are the same kind. Check if they are the right
9533 // size.
9534 if (ArgValueKind == ParamValueKind) {
9535 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9536 return;
9537
9538 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9539 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9540 << FDecl << ArgType << ParamType;
9541
9542 if (NewAbsKind == 0)
9543 return;
9544
9545 emitReplacement(*this, Call->getExprLoc(),
9546 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9547 return;
9548 }
9549
9550 // ArgValueKind != ParamValueKind
9551 // The wrong type of absolute value function was used. Attempt to find the
9552 // proper one.
9553 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9554 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9555 if (NewAbsKind == 0)
9556 return;
9557
9558 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9559 << FDecl << ParamValueKind << ArgValueKind;
9560
9561 emitReplacement(*this, Call->getExprLoc(),
9562 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9563}
9564
9565//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9566void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9567 const FunctionDecl *FDecl) {
9568 if (!Call || !FDecl) return;
9569
9570 // Ignore template specializations and macros.
9571 if (inTemplateInstantiation()) return;
9572 if (Call->getExprLoc().isMacroID()) return;
9573
9574 // Only care about the one template argument, two function parameter std::max
9575 if (Call->getNumArgs() != 2) return;
9576 if (!IsStdFunction(FDecl, "max")) return;
9577 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9578 if (!ArgList) return;
9579 if (ArgList->size() != 1) return;
9580
9581 // Check that template type argument is unsigned integer.
9582 const auto& TA = ArgList->get(0);
9583 if (TA.getKind() != TemplateArgument::Type) return;
9584 QualType ArgType = TA.getAsType();
9585 if (!ArgType->isUnsignedIntegerType()) return;
9586
9587 // See if either argument is a literal zero.
9588 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9589 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9590 if (!MTE) return false;
9591 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9592 if (!Num) return false;
9593 if (Num->getValue() != 0) return false;
9594 return true;
9595 };
9596
9597 const Expr *FirstArg = Call->getArg(0);
9598 const Expr *SecondArg = Call->getArg(1);
9599 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9600 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9601
9602 // Only warn when exactly one argument is zero.
9603 if (IsFirstArgZero == IsSecondArgZero) return;
9604
9605 SourceRange FirstRange = FirstArg->getSourceRange();
9606 SourceRange SecondRange = SecondArg->getSourceRange();
9607
9608 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9609
9610 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9611 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9612
9613 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9614 SourceRange RemovalRange;
9615 if (IsFirstArgZero) {
9616 RemovalRange = SourceRange(FirstRange.getBegin(),
9617 SecondRange.getBegin().getLocWithOffset(-1));
9618 } else {
9619 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9620 SecondRange.getEnd());
9621 }
9622
9623 Diag(Call->getExprLoc(), diag::note_remove_max_call)
9624 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9625 << FixItHint::CreateRemoval(RemovalRange);
9626}
9627
9628//===--- CHECK: Standard memory functions ---------------------------------===//
9629
9630/// Takes the expression passed to the size_t parameter of functions
9631/// such as memcmp, strncat, etc and warns if it's a comparison.
9632///
9633/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9635 const IdentifierInfo *FnName,
9636 SourceLocation FnLoc,
9637 SourceLocation RParenLoc) {
9638 const auto *Size = dyn_cast<BinaryOperator>(E);
9639 if (!Size)
9640 return false;
9641
9642 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9643 if (!Size->isComparisonOp() && !Size->isLogicalOp())
9644 return false;
9645
9646 SourceRange SizeRange = Size->getSourceRange();
9647 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9648 << SizeRange << FnName;
9649 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9650 << FnName
9652 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9653 << FixItHint::CreateRemoval(RParenLoc);
9654 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9655 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9657 ")");
9658
9659 return true;
9660}
9661
9662/// Determine whether the given type is or contains a dynamic class type
9663/// (e.g., whether it has a vtable).
9665 bool &IsContained) {
9666 // Look through array types while ignoring qualifiers.
9667 const Type *Ty = T->getBaseElementTypeUnsafe();
9668 IsContained = false;
9669
9670 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9671 RD = RD ? RD->getDefinition() : nullptr;
9672 if (!RD || RD->isInvalidDecl())
9673 return nullptr;
9674
9675 if (RD->isDynamicClass())
9676 return RD;
9677
9678 // Check all the fields. If any bases were dynamic, the class is dynamic.
9679 // It's impossible for a class to transitively contain itself by value, so
9680 // infinite recursion is impossible.
9681 for (auto *FD : RD->fields()) {
9682 bool SubContained;
9683 if (const CXXRecordDecl *ContainedRD =
9684 getContainedDynamicClass(FD->getType(), SubContained)) {
9685 IsContained = true;
9686 return ContainedRD;
9687 }
9688 }
9689
9690 return nullptr;
9691}
9692
9694 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9695 if (Unary->getKind() == UETT_SizeOf)
9696 return Unary;
9697 return nullptr;
9698}
9699
9700/// If E is a sizeof expression, returns its argument expression,
9701/// otherwise returns NULL.
9702static const Expr *getSizeOfExprArg(const Expr *E) {
9704 if (!SizeOf->isArgumentType())
9705 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9706 return nullptr;
9707}
9708
9709/// If E is a sizeof expression, returns its argument type.
9712 return SizeOf->getTypeOfArgument();
9713 return QualType();
9714}
9715
9716namespace {
9717
9718struct SearchNonTrivialToInitializeField
9719 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9720 using Super =
9722
9723 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9724
9725 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9726 SourceLocation SL) {
9727 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9728 asDerived().visitArray(PDIK, AT, SL);
9729 return;
9730 }
9731
9732 Super::visitWithKind(PDIK, FT, SL);
9733 }
9734
9735 void visitARCStrong(QualType FT, SourceLocation SL) {
9736 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9737 }
9738 void visitARCWeak(QualType FT, SourceLocation SL) {
9739 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9740 }
9741 void visitStruct(QualType FT, SourceLocation SL) {
9742 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
9743 visit(FD->getType(), FD->getLocation());
9744 }
9745 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9746 const ArrayType *AT, SourceLocation SL) {
9747 visit(getContext().getBaseElementType(AT), SL);
9748 }
9749 void visitTrivial(QualType FT, SourceLocation SL) {}
9750
9751 static void diag(QualType RT, const Expr *E, Sema &S) {
9752 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9753 }
9754
9755 ASTContext &getContext() { return S.getASTContext(); }
9756
9757 const Expr *E;
9758 Sema &S;
9759};
9760
9761struct SearchNonTrivialToCopyField
9762 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9764
9765 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9766
9767 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9768 SourceLocation SL) {
9769 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9770 asDerived().visitArray(PCK, AT, SL);
9771 return;
9772 }
9773
9774 Super::visitWithKind(PCK, FT, SL);
9775 }
9776
9777 void visitARCStrong(QualType FT, SourceLocation SL) {
9778 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9779 }
9780 void visitARCWeak(QualType FT, SourceLocation SL) {
9781 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9782 }
9783 void visitPtrAuth(QualType FT, SourceLocation SL) {
9784 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9785 }
9786 void visitStruct(QualType FT, SourceLocation SL) {
9787 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
9788 visit(FD->getType(), FD->getLocation());
9789 }
9790 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9791 SourceLocation SL) {
9792 visit(getContext().getBaseElementType(AT), SL);
9793 }
9794 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9795 SourceLocation SL) {}
9796 void visitTrivial(QualType FT, SourceLocation SL) {}
9797 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9798
9799 static void diag(QualType RT, const Expr *E, Sema &S) {
9800 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9801 }
9802
9803 ASTContext &getContext() { return S.getASTContext(); }
9804
9805 const Expr *E;
9806 Sema &S;
9807};
9808
9809}
9810
9811/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9812static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9813 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9814
9815 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9816 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9817 return false;
9818
9819 return doesExprLikelyComputeSize(BO->getLHS()) ||
9820 doesExprLikelyComputeSize(BO->getRHS());
9821 }
9822
9823 return getAsSizeOfExpr(SizeofExpr) != nullptr;
9824}
9825
9826/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9827///
9828/// \code
9829/// #define MACRO 0
9830/// foo(MACRO);
9831/// foo(0);
9832/// \endcode
9833///
9834/// This should return true for the first call to foo, but not for the second
9835/// (regardless of whether foo is a macro or function).
9837 SourceLocation CallLoc,
9838 SourceLocation ArgLoc) {
9839 if (!CallLoc.isMacroID())
9840 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9841
9842 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9843 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9844}
9845
9846/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9847/// last two arguments transposed.
9848static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9849 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9850 return;
9851
9852 const Expr *SizeArg =
9853 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9854
9855 auto isLiteralZero = [](const Expr *E) {
9856 return (isa<IntegerLiteral>(E) &&
9857 cast<IntegerLiteral>(E)->getValue() == 0) ||
9858 (isa<CharacterLiteral>(E) &&
9859 cast<CharacterLiteral>(E)->getValue() == 0);
9860 };
9861
9862 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9863 SourceLocation CallLoc = Call->getRParenLoc();
9865 if (isLiteralZero(SizeArg) &&
9866 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9867
9868 SourceLocation DiagLoc = SizeArg->getExprLoc();
9869
9870 // Some platforms #define bzero to __builtin_memset. See if this is the
9871 // case, and if so, emit a better diagnostic.
9872 if (BId == Builtin::BIbzero ||
9874 CallLoc, SM, S.getLangOpts()) == "bzero")) {
9875 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9876 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9877 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9878 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9879 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9880 }
9881 return;
9882 }
9883
9884 // If the second argument to a memset is a sizeof expression and the third
9885 // isn't, this is also likely an error. This should catch
9886 // 'memset(buf, sizeof(buf), 0xff)'.
9887 if (BId == Builtin::BImemset &&
9888 doesExprLikelyComputeSize(Call->getArg(1)) &&
9889 !doesExprLikelyComputeSize(Call->getArg(2))) {
9890 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9891 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9892 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9893 return;
9894 }
9895}
9896
9897void Sema::CheckMemaccessArguments(const CallExpr *Call,
9898 unsigned BId,
9899 IdentifierInfo *FnName) {
9900 assert(BId != 0);
9901
9902 // It is possible to have a non-standard definition of memset. Validate
9903 // we have enough arguments, and if not, abort further checking.
9904 unsigned ExpectedNumArgs =
9905 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9906 if (Call->getNumArgs() < ExpectedNumArgs)
9907 return;
9908
9909 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9910 BId == Builtin::BIstrndup ? 1 : 2);
9911 unsigned LenArg =
9912 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9913 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9914
9915 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9916 Call->getBeginLoc(), Call->getRParenLoc()))
9917 return;
9918
9919 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9920 CheckMemaccessSize(*this, BId, Call);
9921
9922 // We have special checking when the length is a sizeof expression.
9923 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9924 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9925 llvm::FoldingSetNodeID SizeOfArgID;
9926
9927 // Although widely used, 'bzero' is not a standard function. Be more strict
9928 // with the argument types before allowing diagnostics and only allow the
9929 // form bzero(ptr, sizeof(...)).
9930 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9931 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9932 return;
9933
9934 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9935 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9936 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9937
9938 QualType DestTy = Dest->getType();
9939 QualType PointeeTy;
9940 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9941 PointeeTy = DestPtrTy->getPointeeType();
9942
9943 // Never warn about void type pointers. This can be used to suppress
9944 // false positives.
9945 if (PointeeTy->isVoidType())
9946 continue;
9947
9948 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9949 // actually comparing the expressions for equality. Because computing the
9950 // expression IDs can be expensive, we only do this if the diagnostic is
9951 // enabled.
9952 if (SizeOfArg &&
9953 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9954 SizeOfArg->getExprLoc())) {
9955 // We only compute IDs for expressions if the warning is enabled, and
9956 // cache the sizeof arg's ID.
9957 if (SizeOfArgID == llvm::FoldingSetNodeID())
9958 SizeOfArg->Profile(SizeOfArgID, Context, true);
9959 llvm::FoldingSetNodeID DestID;
9960 Dest->Profile(DestID, Context, true);
9961 if (DestID == SizeOfArgID) {
9962 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9963 // over sizeof(src) as well.
9964 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9965 StringRef ReadableName = FnName->getName();
9966
9967 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9968 if (UnaryOp->getOpcode() == UO_AddrOf)
9969 ActionIdx = 1; // If its an address-of operator, just remove it.
9970 if (!PointeeTy->isIncompleteType() &&
9971 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9972 ActionIdx = 2; // If the pointee's size is sizeof(char),
9973 // suggest an explicit length.
9974
9975 // If the function is defined as a builtin macro, do not show macro
9976 // expansion.
9977 SourceLocation SL = SizeOfArg->getExprLoc();
9978 SourceRange DSR = Dest->getSourceRange();
9979 SourceRange SSR = SizeOfArg->getSourceRange();
9981
9982 if (SM.isMacroArgExpansion(SL)) {
9983 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9984 SL = SM.getSpellingLoc(SL);
9985 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9986 SM.getSpellingLoc(DSR.getEnd()));
9987 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9988 SM.getSpellingLoc(SSR.getEnd()));
9989 }
9990
9991 DiagRuntimeBehavior(SL, SizeOfArg,
9992 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9993 << ReadableName
9994 << PointeeTy
9995 << DestTy
9996 << DSR
9997 << SSR);
9998 DiagRuntimeBehavior(SL, SizeOfArg,
9999 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10000 << ActionIdx
10001 << SSR);
10002
10003 break;
10004 }
10005 }
10006
10007 // Also check for cases where the sizeof argument is the exact same
10008 // type as the memory argument, and where it points to a user-defined
10009 // record type.
10010 if (SizeOfArgTy != QualType()) {
10011 if (PointeeTy->isRecordType() &&
10012 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10013 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10014 PDiag(diag::warn_sizeof_pointer_type_memaccess)
10015 << FnName << SizeOfArgTy << ArgIdx
10016 << PointeeTy << Dest->getSourceRange()
10017 << LenExpr->getSourceRange());
10018 break;
10019 }
10020 }
10021 } else if (DestTy->isArrayType()) {
10022 PointeeTy = DestTy;
10023 }
10024
10025 if (PointeeTy == QualType())
10026 continue;
10027
10028 // Always complain about dynamic classes.
10029 bool IsContained;
10030 if (const CXXRecordDecl *ContainedRD =
10031 getContainedDynamicClass(PointeeTy, IsContained)) {
10032
10033 unsigned OperationType = 0;
10034 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10035 // "overwritten" if we're warning about the destination for any call
10036 // but memcmp; otherwise a verb appropriate to the call.
10037 if (ArgIdx != 0 || IsCmp) {
10038 if (BId == Builtin::BImemcpy)
10039 OperationType = 1;
10040 else if(BId == Builtin::BImemmove)
10041 OperationType = 2;
10042 else if (IsCmp)
10043 OperationType = 3;
10044 }
10045
10046 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10047 PDiag(diag::warn_dyn_class_memaccess)
10048 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10049 << IsContained << ContainedRD << OperationType
10050 << Call->getCallee()->getSourceRange());
10051 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10052 BId != Builtin::BImemset)
10054 Dest->getExprLoc(), Dest,
10055 PDiag(diag::warn_arc_object_memaccess)
10056 << ArgIdx << FnName << PointeeTy
10057 << Call->getCallee()->getSourceRange());
10058 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
10059
10060 // FIXME: Do not consider incomplete types even though they may be
10061 // completed later. GCC does not diagnose such code, but we may want to
10062 // consider diagnosing it in the future, perhaps under a different, but
10063 // related, diagnostic group.
10064 bool NonTriviallyCopyableCXXRecord =
10065 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
10066 !PointeeTy.isTriviallyCopyableType(Context);
10067
10068 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10070 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10071 PDiag(diag::warn_cstruct_memaccess)
10072 << ArgIdx << FnName << PointeeTy << 0);
10073 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10074 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10075 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10076 // FIXME: Limiting this warning to dest argument until we decide
10077 // whether it's valid for source argument too.
10078 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10079 PDiag(diag::warn_cxxstruct_memaccess)
10080 << FnName << PointeeTy);
10081 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10083 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10084 PDiag(diag::warn_cstruct_memaccess)
10085 << ArgIdx << FnName << PointeeTy << 1);
10086 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10087 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10088 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10089 // FIXME: Limiting this warning to dest argument until we decide
10090 // whether it's valid for source argument too.
10091 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10092 PDiag(diag::warn_cxxstruct_memaccess)
10093 << FnName << PointeeTy);
10094 } else {
10095 continue;
10096 }
10097 } else
10098 continue;
10099
10101 Dest->getExprLoc(), Dest,
10102 PDiag(diag::note_bad_memaccess_silence)
10103 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10104 break;
10105 }
10106}
10107
10108// A little helper routine: ignore addition and subtraction of integer literals.
10109// This intentionally does not ignore all integer constant expressions because
10110// we don't want to remove sizeof().
10111static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10112 Ex = Ex->IgnoreParenCasts();
10113
10114 while (true) {
10115 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10116 if (!BO || !BO->isAdditiveOp())
10117 break;
10118
10119 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10120 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10121
10122 if (isa<IntegerLiteral>(RHS))
10123 Ex = LHS;
10124 else if (isa<IntegerLiteral>(LHS))
10125 Ex = RHS;
10126 else
10127 break;
10128 }
10129
10130 return Ex;
10131}
10132
10134 ASTContext &Context) {
10135 // Only handle constant-sized or VLAs, but not flexible members.
10136 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10137 // Only issue the FIXIT for arrays of size > 1.
10138 if (CAT->getZExtSize() <= 1)
10139 return false;
10140 } else if (!Ty->isVariableArrayType()) {
10141 return false;
10142 }
10143 return true;
10144}
10145
10146void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10147 IdentifierInfo *FnName) {
10148
10149 // Don't crash if the user has the wrong number of arguments
10150 unsigned NumArgs = Call->getNumArgs();
10151 if ((NumArgs != 3) && (NumArgs != 4))
10152 return;
10153
10154 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10155 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10156 const Expr *CompareWithSrc = nullptr;
10157
10158 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10159 Call->getBeginLoc(), Call->getRParenLoc()))
10160 return;
10161
10162 // Look for 'strlcpy(dst, x, sizeof(x))'
10163 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10164 CompareWithSrc = Ex;
10165 else {
10166 // Look for 'strlcpy(dst, x, strlen(x))'
10167 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10168 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10169 SizeCall->getNumArgs() == 1)
10170 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10171 }
10172 }
10173
10174 if (!CompareWithSrc)
10175 return;
10176
10177 // Determine if the argument to sizeof/strlen is equal to the source
10178 // argument. In principle there's all kinds of things you could do
10179 // here, for instance creating an == expression and evaluating it with
10180 // EvaluateAsBooleanCondition, but this uses a more direct technique:
10181 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10182 if (!SrcArgDRE)
10183 return;
10184
10185 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10186 if (!CompareWithSrcDRE ||
10187 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10188 return;
10189
10190 const Expr *OriginalSizeArg = Call->getArg(2);
10191 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10192 << OriginalSizeArg->getSourceRange() << FnName;
10193
10194 // Output a FIXIT hint if the destination is an array (rather than a
10195 // pointer to an array). This could be enhanced to handle some
10196 // pointers if we know the actual size, like if DstArg is 'array+2'
10197 // we could say 'sizeof(array)-2'.
10198 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10200 return;
10201
10202 SmallString<128> sizeString;
10203 llvm::raw_svector_ostream OS(sizeString);
10204 OS << "sizeof(";
10205 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10206 OS << ")";
10207
10208 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10209 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10210 OS.str());
10211}
10212
10213/// Check if two expressions refer to the same declaration.
10214static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10215 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10216 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10217 return D1->getDecl() == D2->getDecl();
10218 return false;
10219}
10220
10221static const Expr *getStrlenExprArg(const Expr *E) {
10222 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10223 const FunctionDecl *FD = CE->getDirectCallee();
10224 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10225 return nullptr;
10226 return CE->getArg(0)->IgnoreParenCasts();
10227 }
10228 return nullptr;
10229}
10230
10231void Sema::CheckStrncatArguments(const CallExpr *CE,
10232 const IdentifierInfo *FnName) {
10233 // Don't crash if the user has the wrong number of arguments.
10234 if (CE->getNumArgs() < 3)
10235 return;
10236 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10237 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10238 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10239
10240 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10241 CE->getRParenLoc()))
10242 return;
10243
10244 // Identify common expressions, which are wrongly used as the size argument
10245 // to strncat and may lead to buffer overflows.
10246 unsigned PatternType = 0;
10247 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10248 // - sizeof(dst)
10249 if (referToTheSameDecl(SizeOfArg, DstArg))
10250 PatternType = 1;
10251 // - sizeof(src)
10252 else if (referToTheSameDecl(SizeOfArg, SrcArg))
10253 PatternType = 2;
10254 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10255 if (BE->getOpcode() == BO_Sub) {
10256 const Expr *L = BE->getLHS()->IgnoreParenCasts();
10257 const Expr *R = BE->getRHS()->IgnoreParenCasts();
10258 // - sizeof(dst) - strlen(dst)
10259 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10261 PatternType = 1;
10262 // - sizeof(src) - (anything)
10263 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10264 PatternType = 2;
10265 }
10266 }
10267
10268 if (PatternType == 0)
10269 return;
10270
10271 // Generate the diagnostic.
10272 SourceLocation SL = LenArg->getBeginLoc();
10273 SourceRange SR = LenArg->getSourceRange();
10275
10276 // If the function is defined as a builtin macro, do not show macro expansion.
10277 if (SM.isMacroArgExpansion(SL)) {
10278 SL = SM.getSpellingLoc(SL);
10279 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10280 SM.getSpellingLoc(SR.getEnd()));
10281 }
10282
10283 // Check if the destination is an array (rather than a pointer to an array).
10284 QualType DstTy = DstArg->getType();
10285 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10286 Context);
10287 if (!isKnownSizeArray) {
10288 if (PatternType == 1)
10289 Diag(SL, diag::warn_strncat_wrong_size) << SR;
10290 else
10291 Diag(SL, diag::warn_strncat_src_size) << SR;
10292 return;
10293 }
10294
10295 if (PatternType == 1)
10296 Diag(SL, diag::warn_strncat_large_size) << SR;
10297 else
10298 Diag(SL, diag::warn_strncat_src_size) << SR;
10299
10300 SmallString<128> sizeString;
10301 llvm::raw_svector_ostream OS(sizeString);
10302 OS << "sizeof(";
10303 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10304 OS << ") - ";
10305 OS << "strlen(";
10306 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10307 OS << ") - 1";
10308
10309 Diag(SL, diag::note_strncat_wrong_size)
10310 << FixItHint::CreateReplacement(SR, OS.str());
10311}
10312
10313namespace {
10314void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10315 const UnaryOperator *UnaryExpr, const Decl *D) {
10316 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10317 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10318 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10319 return;
10320 }
10321}
10322
10323void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10324 const UnaryOperator *UnaryExpr) {
10325 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10326 const Decl *D = Lvalue->getDecl();
10327 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
10328 if (!DD->getType()->isReferenceType())
10329 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10330 }
10331 }
10332
10333 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10334 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10335 Lvalue->getMemberDecl());
10336}
10337
10338void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10339 const UnaryOperator *UnaryExpr) {
10340 const auto *Lambda = dyn_cast<LambdaExpr>(
10342 if (!Lambda)
10343 return;
10344
10345 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10346 << CalleeName << 2 /*object: lambda expression*/;
10347}
10348
10349void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10350 const DeclRefExpr *Lvalue) {
10351 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10352 if (Var == nullptr)
10353 return;
10354
10355 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10356 << CalleeName << 0 /*object: */ << Var;
10357}
10358
10359void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10360 const CastExpr *Cast) {
10361 SmallString<128> SizeString;
10362 llvm::raw_svector_ostream OS(SizeString);
10363
10364 clang::CastKind Kind = Cast->getCastKind();
10365 if (Kind == clang::CK_BitCast &&
10366 !Cast->getSubExpr()->getType()->isFunctionPointerType())
10367 return;
10368 if (Kind == clang::CK_IntegralToPointer &&
10369 !isa<IntegerLiteral>(
10370 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10371 return;
10372
10373 switch (Cast->getCastKind()) {
10374 case clang::CK_BitCast:
10375 case clang::CK_IntegralToPointer:
10376 case clang::CK_FunctionToPointerDecay:
10377 OS << '\'';
10378 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10379 OS << '\'';
10380 break;
10381 default:
10382 return;
10383 }
10384
10385 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10386 << CalleeName << 0 /*object: */ << OS.str();
10387}
10388} // namespace
10389
10390void Sema::CheckFreeArguments(const CallExpr *E) {
10391 const std::string CalleeName =
10392 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10393
10394 { // Prefer something that doesn't involve a cast to make things simpler.
10395 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10396 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10397 switch (UnaryExpr->getOpcode()) {
10398 case UnaryOperator::Opcode::UO_AddrOf:
10399 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10400 case UnaryOperator::Opcode::UO_Plus:
10401 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10402 default:
10403 break;
10404 }
10405
10406 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10407 if (Lvalue->getType()->isArrayType())
10408 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10409
10410 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10411 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10412 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10413 return;
10414 }
10415
10416 if (isa<BlockExpr>(Arg)) {
10417 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10418 << CalleeName << 1 /*object: block*/;
10419 return;
10420 }
10421 }
10422 // Maybe the cast was important, check after the other cases.
10423 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10424 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10425}
10426
10427void
10428Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10429 SourceLocation ReturnLoc,
10430 bool isObjCMethod,
10431 const AttrVec *Attrs,
10432 const FunctionDecl *FD) {
10433 // Check if the return value is null but should not be.
10434 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10435 (!isObjCMethod && isNonNullType(lhsType))) &&
10436 CheckNonNullExpr(*this, RetValExp))
10437 Diag(ReturnLoc, diag::warn_null_ret)
10438 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10439
10440 // C++11 [basic.stc.dynamic.allocation]p4:
10441 // If an allocation function declared with a non-throwing
10442 // exception-specification fails to allocate storage, it shall return
10443 // a null pointer. Any other allocation function that fails to allocate
10444 // storage shall indicate failure only by throwing an exception [...]
10445 if (FD) {
10447 if (Op == OO_New || Op == OO_Array_New) {
10448 const FunctionProtoType *Proto
10449 = FD->getType()->castAs<FunctionProtoType>();
10450 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10451 CheckNonNullExpr(*this, RetValExp))
10452 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10453 << FD << getLangOpts().CPlusPlus11;
10454 }
10455 }
10456
10457 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
10458 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
10459 }
10460
10461 // PPC MMA non-pointer types are not allowed as return type. Checking the type
10462 // here prevent the user from using a PPC MMA type as trailing return type.
10463 if (Context.getTargetInfo().getTriple().isPPC64())
10464 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10465}
10466
10468 const Expr *RHS, BinaryOperatorKind Opcode) {
10469 if (!BinaryOperator::isEqualityOp(Opcode))
10470 return;
10471
10472 // Match and capture subexpressions such as "(float) X == 0.1".
10473 const FloatingLiteral *FPLiteral;
10474 const CastExpr *FPCast;
10475 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
10476 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
10477 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
10478 return FPLiteral && FPCast;
10479 };
10480
10481 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
10482 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
10483 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
10484 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
10485 TargetTy->isFloatingPoint()) {
10486 bool Lossy;
10487 llvm::APFloat TargetC = FPLiteral->getValue();
10488 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
10489 llvm::APFloat::rmNearestTiesToEven, &Lossy);
10490 if (Lossy) {
10491 // If the literal cannot be represented in the source type, then a
10492 // check for == is always false and check for != is always true.
10493 Diag(Loc, diag::warn_float_compare_literal)
10494 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
10495 << LHS->getSourceRange() << RHS->getSourceRange();
10496 return;
10497 }
10498 }
10499 }
10500
10501 // Match a more general floating-point equality comparison (-Wfloat-equal).
10502 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
10503 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
10504
10505 // Special case: check for x == x (which is OK).
10506 // Do not emit warnings for such cases.
10507 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10508 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10509 if (DRL->getDecl() == DRR->getDecl())
10510 return;
10511
10512 // Special case: check for comparisons against literals that can be exactly
10513 // represented by APFloat. In such cases, do not emit a warning. This
10514 // is a heuristic: often comparison against such literals are used to
10515 // detect if a value in a variable has not changed. This clearly can
10516 // lead to false negatives.
10517 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10518 if (FLL->isExact())
10519 return;
10520 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10521 if (FLR->isExact())
10522 return;
10523
10524 // Check for comparisons with builtin types.
10525 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
10526 CL && CL->getBuiltinCallee())
10527 return;
10528
10529 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
10530 CR && CR->getBuiltinCallee())
10531 return;
10532
10533 // Emit the diagnostic.
10534 Diag(Loc, diag::warn_floatingpoint_eq)
10535 << LHS->getSourceRange() << RHS->getSourceRange();
10536}
10537
10538//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10539//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10540
10541namespace {
10542
10543/// Structure recording the 'active' range of an integer-valued
10544/// expression.
10545struct IntRange {
10546 /// The number of bits active in the int. Note that this includes exactly one
10547 /// sign bit if !NonNegative.
10548 unsigned Width;
10549
10550 /// True if the int is known not to have negative values. If so, all leading
10551 /// bits before Width are known zero, otherwise they are known to be the
10552 /// same as the MSB within Width.
10553 bool NonNegative;
10554
10555 IntRange(unsigned Width, bool NonNegative)
10556 : Width(Width), NonNegative(NonNegative) {}
10557
10558 /// Number of bits excluding the sign bit.
10559 unsigned valueBits() const {
10560 return NonNegative ? Width : Width - 1;
10561 }
10562
10563 /// Returns the range of the bool type.
10564 static IntRange forBoolType() {
10565 return IntRange(1, true);
10566 }
10567
10568 /// Returns the range of an opaque value of the given integral type.
10569 static IntRange forValueOfType(ASTContext &C, QualType T) {
10570 return forValueOfCanonicalType(C,
10572 }
10573
10574 /// Returns the range of an opaque value of a canonical integral type.
10575 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10576 assert(T->isCanonicalUnqualified());
10577
10578 if (const auto *VT = dyn_cast<VectorType>(T))
10579 T = VT->getElementType().getTypePtr();
10580 if (const auto *CT = dyn_cast<ComplexType>(T))
10581 T = CT->getElementType().getTypePtr();
10582 if (const auto *AT = dyn_cast<AtomicType>(T))
10583 T = AT->getValueType().getTypePtr();
10584
10585 if (!C.getLangOpts().CPlusPlus) {
10586 // For enum types in C code, use the underlying datatype.
10587 if (const auto *ED = T->getAsEnumDecl())
10588 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
10589 } else if (auto *Enum = T->getAsEnumDecl()) {
10590 // For enum types in C++, use the known bit width of the enumerators.
10591 // In C++11, enums can have a fixed underlying type. Use this type to
10592 // compute the range.
10593 if (Enum->isFixed()) {
10594 return IntRange(C.getIntWidth(QualType(T, 0)),
10595 !Enum->getIntegerType()->isSignedIntegerType());
10596 }
10597
10598 unsigned NumPositive = Enum->getNumPositiveBits();
10599 unsigned NumNegative = Enum->getNumNegativeBits();
10600
10601 if (NumNegative == 0)
10602 return IntRange(NumPositive, true/*NonNegative*/);
10603 else
10604 return IntRange(std::max(NumPositive + 1, NumNegative),
10605 false/*NonNegative*/);
10606 }
10607
10608 if (const auto *EIT = dyn_cast<BitIntType>(T))
10609 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10610
10611 const BuiltinType *BT = cast<BuiltinType>(T);
10612 assert(BT->isInteger());
10613
10614 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10615 }
10616
10617 /// Returns the "target" range of a canonical integral type, i.e.
10618 /// the range of values expressible in the type.
10619 ///
10620 /// This matches forValueOfCanonicalType except that enums have the
10621 /// full range of their type, not the range of their enumerators.
10622 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10623 assert(T->isCanonicalUnqualified());
10624
10625 if (const VectorType *VT = dyn_cast<VectorType>(T))
10626 T = VT->getElementType().getTypePtr();
10627 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10628 T = CT->getElementType().getTypePtr();
10629 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10630 T = AT->getValueType().getTypePtr();
10631 if (const auto *ED = T->getAsEnumDecl())
10632 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
10633
10634 if (const auto *EIT = dyn_cast<BitIntType>(T))
10635 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10636
10637 const BuiltinType *BT = cast<BuiltinType>(T);
10638 assert(BT->isInteger());
10639
10640 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10641 }
10642
10643 /// Returns the supremum of two ranges: i.e. their conservative merge.
10644 static IntRange join(IntRange L, IntRange R) {
10645 bool Unsigned = L.NonNegative && R.NonNegative;
10646 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10647 L.NonNegative && R.NonNegative);
10648 }
10649
10650 /// Return the range of a bitwise-AND of the two ranges.
10651 static IntRange bit_and(IntRange L, IntRange R) {
10652 unsigned Bits = std::max(L.Width, R.Width);
10653 bool NonNegative = false;
10654 if (L.NonNegative) {
10655 Bits = std::min(Bits, L.Width);
10656 NonNegative = true;
10657 }
10658 if (R.NonNegative) {
10659 Bits = std::min(Bits, R.Width);
10660 NonNegative = true;
10661 }
10662 return IntRange(Bits, NonNegative);
10663 }
10664
10665 /// Return the range of a sum of the two ranges.
10666 static IntRange sum(IntRange L, IntRange R) {
10667 bool Unsigned = L.NonNegative && R.NonNegative;
10668 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10669 Unsigned);
10670 }
10671
10672 /// Return the range of a difference of the two ranges.
10673 static IntRange difference(IntRange L, IntRange R) {
10674 // We need a 1-bit-wider range if:
10675 // 1) LHS can be negative: least value can be reduced.
10676 // 2) RHS can be negative: greatest value can be increased.
10677 bool CanWiden = !L.NonNegative || !R.NonNegative;
10678 bool Unsigned = L.NonNegative && R.Width == 0;
10679 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10680 !Unsigned,
10681 Unsigned);
10682 }
10683
10684 /// Return the range of a product of the two ranges.
10685 static IntRange product(IntRange L, IntRange R) {
10686 // If both LHS and RHS can be negative, we can form
10687 // -2^L * -2^R = 2^(L + R)
10688 // which requires L + R + 1 value bits to represent.
10689 bool CanWiden = !L.NonNegative && !R.NonNegative;
10690 bool Unsigned = L.NonNegative && R.NonNegative;
10691 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10692 Unsigned);
10693 }
10694
10695 /// Return the range of a remainder operation between the two ranges.
10696 static IntRange rem(IntRange L, IntRange R) {
10697 // The result of a remainder can't be larger than the result of
10698 // either side. The sign of the result is the sign of the LHS.
10699 bool Unsigned = L.NonNegative;
10700 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10701 Unsigned);
10702 }
10703};
10704
10705} // namespace
10706
10707static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
10708 if (value.isSigned() && value.isNegative())
10709 return IntRange(value.getSignificantBits(), false);
10710
10711 if (value.getBitWidth() > MaxWidth)
10712 value = value.trunc(MaxWidth);
10713
10714 // isNonNegative() just checks the sign bit without considering
10715 // signedness.
10716 return IntRange(value.getActiveBits(), true);
10717}
10718
10719static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
10720 if (result.isInt())
10721 return GetValueRange(result.getInt(), MaxWidth);
10722
10723 if (result.isVector()) {
10724 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
10725 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10726 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
10727 R = IntRange::join(R, El);
10728 }
10729 return R;
10730 }
10731
10732 if (result.isComplexInt()) {
10733 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
10734 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
10735 return IntRange::join(R, I);
10736 }
10737
10738 // This can happen with lossless casts to intptr_t of "based" lvalues.
10739 // Assume it might use arbitrary bits.
10740 // FIXME: The only reason we need to pass the type in here is to get
10741 // the sign right on this one case. It would be nice if APValue
10742 // preserved this.
10743 assert(result.isLValue() || result.isAddrLabelDiff());
10744 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10745}
10746
10747static QualType GetExprType(const Expr *E) {
10748 QualType Ty = E->getType();
10749 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
10750 Ty = AtomicRHS->getValueType();
10751 return Ty;
10752}
10753
10754/// Attempts to estimate an approximate range for the given integer expression.
10755/// Returns a range if successful, otherwise it returns \c std::nullopt if a
10756/// reliable estimation cannot be determined.
10757///
10758/// \param MaxWidth The width to which the value will be truncated.
10759/// \param InConstantContext If \c true, interpret the expression within a
10760/// constant context.
10761/// \param Approximate If \c true, provide a likely range of values by assuming
10762/// that arithmetic on narrower types remains within those types.
10763/// If \c false, return a range that includes all possible values
10764/// resulting from the expression.
10765/// \returns A range of values that the expression might take, or
10766/// std::nullopt if a reliable estimation cannot be determined.
10767static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
10768 unsigned MaxWidth,
10769 bool InConstantContext,
10770 bool Approximate) {
10771 E = E->IgnoreParens();
10772
10773 // Try a full evaluation first.
10774 Expr::EvalResult result;
10775 if (E->EvaluateAsRValue(result, C, InConstantContext))
10776 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
10777
10778 // I think we only want to look through implicit casts here; if the
10779 // user has an explicit widening cast, we should treat the value as
10780 // being of the new, wider type.
10781 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10782 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10783 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
10784 Approximate);
10785
10786 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10787
10788 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10789 CE->getCastKind() == CK_BooleanToSignedIntegral;
10790
10791 // Assume that non-integer casts can span the full range of the type.
10792 if (!isIntegerCast)
10793 return OutputTypeRange;
10794
10795 std::optional<IntRange> SubRange = TryGetExprRange(
10796 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
10797 InConstantContext, Approximate);
10798 if (!SubRange)
10799 return std::nullopt;
10800
10801 // Bail out if the subexpr's range is as wide as the cast type.
10802 if (SubRange->Width >= OutputTypeRange.Width)
10803 return OutputTypeRange;
10804
10805 // Otherwise, we take the smaller width, and we're non-negative if
10806 // either the output type or the subexpr is.
10807 return IntRange(SubRange->Width,
10808 SubRange->NonNegative || OutputTypeRange.NonNegative);
10809 }
10810
10811 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10812 // If we can fold the condition, just take that operand.
10813 bool CondResult;
10814 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10815 return TryGetExprRange(
10816 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
10817 InConstantContext, Approximate);
10818
10819 // Otherwise, conservatively merge.
10820 // TryGetExprRange requires an integer expression, but a throw expression
10821 // results in a void type.
10822 Expr *TrueExpr = CO->getTrueExpr();
10823 if (TrueExpr->getType()->isVoidType())
10824 return std::nullopt;
10825
10826 std::optional<IntRange> L =
10827 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
10828 if (!L)
10829 return std::nullopt;
10830
10831 Expr *FalseExpr = CO->getFalseExpr();
10832 if (FalseExpr->getType()->isVoidType())
10833 return std::nullopt;
10834
10835 std::optional<IntRange> R =
10836 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
10837 if (!R)
10838 return std::nullopt;
10839
10840 return IntRange::join(*L, *R);
10841 }
10842
10843 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10844 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
10845
10846 switch (BO->getOpcode()) {
10847 case BO_Cmp:
10848 llvm_unreachable("builtin <=> should have class type");
10849
10850 // Boolean-valued operations are single-bit and positive.
10851 case BO_LAnd:
10852 case BO_LOr:
10853 case BO_LT:
10854 case BO_GT:
10855 case BO_LE:
10856 case BO_GE:
10857 case BO_EQ:
10858 case BO_NE:
10859 return IntRange::forBoolType();
10860
10861 // The type of the assignments is the type of the LHS, so the RHS
10862 // is not necessarily the same type.
10863 case BO_MulAssign:
10864 case BO_DivAssign:
10865 case BO_RemAssign:
10866 case BO_AddAssign:
10867 case BO_SubAssign:
10868 case BO_XorAssign:
10869 case BO_OrAssign:
10870 // TODO: bitfields?
10871 return IntRange::forValueOfType(C, GetExprType(E));
10872
10873 // Simple assignments just pass through the RHS, which will have
10874 // been coerced to the LHS type.
10875 case BO_Assign:
10876 // TODO: bitfields?
10877 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10878 Approximate);
10879
10880 // Operations with opaque sources are black-listed.
10881 case BO_PtrMemD:
10882 case BO_PtrMemI:
10883 return IntRange::forValueOfType(C, GetExprType(E));
10884
10885 // Bitwise-and uses the *infinum* of the two source ranges.
10886 case BO_And:
10887 case BO_AndAssign:
10888 Combine = IntRange::bit_and;
10889 break;
10890
10891 // Left shift gets black-listed based on a judgement call.
10892 case BO_Shl:
10893 // ...except that we want to treat '1 << (blah)' as logically
10894 // positive. It's an important idiom.
10895 if (IntegerLiteral *I
10896 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10897 if (I->getValue() == 1) {
10898 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10899 return IntRange(R.Width, /*NonNegative*/ true);
10900 }
10901 }
10902 [[fallthrough]];
10903
10904 case BO_ShlAssign:
10905 return IntRange::forValueOfType(C, GetExprType(E));
10906
10907 // Right shift by a constant can narrow its left argument.
10908 case BO_Shr:
10909 case BO_ShrAssign: {
10910 std::optional<IntRange> L = TryGetExprRange(
10911 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
10912 if (!L)
10913 return std::nullopt;
10914
10915 // If the shift amount is a positive constant, drop the width by
10916 // that much.
10917 if (std::optional<llvm::APSInt> shift =
10918 BO->getRHS()->getIntegerConstantExpr(C)) {
10919 if (shift->isNonNegative()) {
10920 if (shift->uge(L->Width))
10921 L->Width = (L->NonNegative ? 0 : 1);
10922 else
10923 L->Width -= shift->getZExtValue();
10924 }
10925 }
10926
10927 return L;
10928 }
10929
10930 // Comma acts as its right operand.
10931 case BO_Comma:
10932 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10933 Approximate);
10934
10935 case BO_Add:
10936 if (!Approximate)
10937 Combine = IntRange::sum;
10938 break;
10939
10940 case BO_Sub:
10941 if (BO->getLHS()->getType()->isPointerType())
10942 return IntRange::forValueOfType(C, GetExprType(E));
10943 if (!Approximate)
10944 Combine = IntRange::difference;
10945 break;
10946
10947 case BO_Mul:
10948 if (!Approximate)
10949 Combine = IntRange::product;
10950 break;
10951
10952 // The width of a division result is mostly determined by the size
10953 // of the LHS.
10954 case BO_Div: {
10955 // Don't 'pre-truncate' the operands.
10956 unsigned opWidth = C.getIntWidth(GetExprType(E));
10957 std::optional<IntRange> L = TryGetExprRange(
10958 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
10959 if (!L)
10960 return std::nullopt;
10961
10962 // If the divisor is constant, use that.
10963 if (std::optional<llvm::APSInt> divisor =
10964 BO->getRHS()->getIntegerConstantExpr(C)) {
10965 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
10966 if (log2 >= L->Width)
10967 L->Width = (L->NonNegative ? 0 : 1);
10968 else
10969 L->Width = std::min(L->Width - log2, MaxWidth);
10970 return L;
10971 }
10972
10973 // Otherwise, just use the LHS's width.
10974 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
10975 // could be -1.
10976 std::optional<IntRange> R = TryGetExprRange(
10977 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
10978 if (!R)
10979 return std::nullopt;
10980
10981 return IntRange(L->Width, L->NonNegative && R->NonNegative);
10982 }
10983
10984 case BO_Rem:
10985 Combine = IntRange::rem;
10986 break;
10987
10988 // The default behavior is okay for these.
10989 case BO_Xor:
10990 case BO_Or:
10991 break;
10992 }
10993
10994 // Combine the two ranges, but limit the result to the type in which we
10995 // performed the computation.
10997 unsigned opWidth = C.getIntWidth(T);
10998 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
10999 InConstantContext, Approximate);
11000 if (!L)
11001 return std::nullopt;
11002
11003 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
11004 InConstantContext, Approximate);
11005 if (!R)
11006 return std::nullopt;
11007
11008 IntRange C = Combine(*L, *R);
11009 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11010 C.Width = std::min(C.Width, MaxWidth);
11011 return C;
11012 }
11013
11014 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11015 switch (UO->getOpcode()) {
11016 // Boolean-valued operations are white-listed.
11017 case UO_LNot:
11018 return IntRange::forBoolType();
11019
11020 // Operations with opaque sources are black-listed.
11021 case UO_Deref:
11022 case UO_AddrOf: // should be impossible
11023 return IntRange::forValueOfType(C, GetExprType(E));
11024
11025 case UO_Minus: {
11026 if (E->getType()->isUnsignedIntegerType()) {
11027 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11028 Approximate);
11029 }
11030
11031 std::optional<IntRange> SubRange = TryGetExprRange(
11032 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11033
11034 if (!SubRange)
11035 return std::nullopt;
11036
11037 // If the range was previously non-negative, we need an extra bit for the
11038 // sign bit. Otherwise, we need an extra bit because the negation of the
11039 // most-negative value is one bit wider than that value.
11040 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
11041 }
11042
11043 case UO_Not: {
11044 if (E->getType()->isUnsignedIntegerType()) {
11045 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11046 Approximate);
11047 }
11048
11049 std::optional<IntRange> SubRange = TryGetExprRange(
11050 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11051
11052 if (!SubRange)
11053 return std::nullopt;
11054
11055 // The width increments by 1 if the sub-expression cannot be negative
11056 // since it now can be.
11057 return IntRange(
11058 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
11059 false);
11060 }
11061
11062 default:
11063 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11064 Approximate);
11065 }
11066 }
11067
11068 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11069 return TryGetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11070 Approximate);
11071
11072 if (const auto *BitField = E->getSourceBitField())
11073 return IntRange(BitField->getBitWidthValue(),
11074 BitField->getType()->isUnsignedIntegerOrEnumerationType());
11075
11076 if (GetExprType(E)->isVoidType())
11077 return std::nullopt;
11078
11079 return IntRange::forValueOfType(C, GetExprType(E));
11080}
11081
11082static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11083 bool InConstantContext,
11084 bool Approximate) {
11085 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11086 Approximate);
11087}
11088
11089/// Checks whether the given value, which currently has the given
11090/// source semantics, has the same value when coerced through the
11091/// target semantics.
11092static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11093 const llvm::fltSemantics &Src,
11094 const llvm::fltSemantics &Tgt) {
11095 llvm::APFloat truncated = value;
11096
11097 bool ignored;
11098 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11099 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11100
11101 return truncated.bitwiseIsEqual(value);
11102}
11103
11104/// Checks whether the given value, which currently has the given
11105/// source semantics, has the same value when coerced through the
11106/// target semantics.
11107///
11108/// The value might be a vector of floats (or a complex number).
11109static bool IsSameFloatAfterCast(const APValue &value,
11110 const llvm::fltSemantics &Src,
11111 const llvm::fltSemantics &Tgt) {
11112 if (value.isFloat())
11113 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11114
11115 if (value.isVector()) {
11116 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11117 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11118 return false;
11119 return true;
11120 }
11121
11122 assert(value.isComplexFloat());
11123 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11124 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11125}
11126
11128 bool IsListInit = false);
11129
11130static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
11131 // Suppress cases where we are comparing against an enum constant.
11132 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11133 if (isa<EnumConstantDecl>(DR->getDecl()))
11134 return true;
11135
11136 // Suppress cases where the value is expanded from a macro, unless that macro
11137 // is how a language represents a boolean literal. This is the case in both C
11138 // and Objective-C.
11139 SourceLocation BeginLoc = E->getBeginLoc();
11140 if (BeginLoc.isMacroID()) {
11141 StringRef MacroName = Lexer::getImmediateMacroName(
11142 BeginLoc, S.getSourceManager(), S.getLangOpts());
11143 return MacroName != "YES" && MacroName != "NO" &&
11144 MacroName != "true" && MacroName != "false";
11145 }
11146
11147 return false;
11148}
11149
11150static bool isKnownToHaveUnsignedValue(const Expr *E) {
11151 return E->getType()->isIntegerType() &&
11152 (!E->getType()->isSignedIntegerType() ||
11154}
11155
11156namespace {
11157/// The promoted range of values of a type. In general this has the
11158/// following structure:
11159///
11160/// |-----------| . . . |-----------|
11161/// ^ ^ ^ ^
11162/// Min HoleMin HoleMax Max
11163///
11164/// ... where there is only a hole if a signed type is promoted to unsigned
11165/// (in which case Min and Max are the smallest and largest representable
11166/// values).
11167struct PromotedRange {
11168 // Min, or HoleMax if there is a hole.
11169 llvm::APSInt PromotedMin;
11170 // Max, or HoleMin if there is a hole.
11171 llvm::APSInt PromotedMax;
11172
11173 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11174 if (R.Width == 0)
11175 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11176 else if (R.Width >= BitWidth && !Unsigned) {
11177 // Promotion made the type *narrower*. This happens when promoting
11178 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11179 // Treat all values of 'signed int' as being in range for now.
11180 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11181 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11182 } else {
11183 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11184 .extOrTrunc(BitWidth);
11185 PromotedMin.setIsUnsigned(Unsigned);
11186
11187 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11188 .extOrTrunc(BitWidth);
11189 PromotedMax.setIsUnsigned(Unsigned);
11190 }
11191 }
11192
11193 // Determine whether this range is contiguous (has no hole).
11194 bool isContiguous() const { return PromotedMin <= PromotedMax; }
11195
11196 // Where a constant value is within the range.
11197 enum ComparisonResult {
11198 LT = 0x1,
11199 LE = 0x2,
11200 GT = 0x4,
11201 GE = 0x8,
11202 EQ = 0x10,
11203 NE = 0x20,
11204 InRangeFlag = 0x40,
11205
11206 Less = LE | LT | NE,
11207 Min = LE | InRangeFlag,
11208 InRange = InRangeFlag,
11209 Max = GE | InRangeFlag,
11210 Greater = GE | GT | NE,
11211
11212 OnlyValue = LE | GE | EQ | InRangeFlag,
11213 InHole = NE
11214 };
11215
11216 ComparisonResult compare(const llvm::APSInt &Value) const {
11217 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11218 Value.isUnsigned() == PromotedMin.isUnsigned());
11219 if (!isContiguous()) {
11220 assert(Value.isUnsigned() && "discontiguous range for signed compare");
11221 if (Value.isMinValue()) return Min;
11222 if (Value.isMaxValue()) return Max;
11223 if (Value >= PromotedMin) return InRange;
11224 if (Value <= PromotedMax) return InRange;
11225 return InHole;
11226 }
11227
11228 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11229 case -1: return Less;
11230 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11231 case 1:
11232 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11233 case -1: return InRange;
11234 case 0: return Max;
11235 case 1: return Greater;
11236 }
11237 }
11238
11239 llvm_unreachable("impossible compare result");
11240 }
11241
11242 static std::optional<StringRef>
11243 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11244 if (Op == BO_Cmp) {
11245 ComparisonResult LTFlag = LT, GTFlag = GT;
11246 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11247
11248 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11249 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11250 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11251 return std::nullopt;
11252 }
11253
11254 ComparisonResult TrueFlag, FalseFlag;
11255 if (Op == BO_EQ) {
11256 TrueFlag = EQ;
11257 FalseFlag = NE;
11258 } else if (Op == BO_NE) {
11259 TrueFlag = NE;
11260 FalseFlag = EQ;
11261 } else {
11262 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11263 TrueFlag = LT;
11264 FalseFlag = GE;
11265 } else {
11266 TrueFlag = GT;
11267 FalseFlag = LE;
11268 }
11269 if (Op == BO_GE || Op == BO_LE)
11270 std::swap(TrueFlag, FalseFlag);
11271 }
11272 if (R & TrueFlag)
11273 return StringRef("true");
11274 if (R & FalseFlag)
11275 return StringRef("false");
11276 return std::nullopt;
11277 }
11278};
11279}
11280
11281static bool HasEnumType(const Expr *E) {
11282 // Strip off implicit integral promotions.
11283 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11284 if (ICE->getCastKind() != CK_IntegralCast &&
11285 ICE->getCastKind() != CK_NoOp)
11286 break;
11287 E = ICE->getSubExpr();
11288 }
11289
11290 return E->getType()->isEnumeralType();
11291}
11292
11293static int classifyConstantValue(Expr *Constant) {
11294 // The values of this enumeration are used in the diagnostics
11295 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11296 enum ConstantValueKind {
11297 Miscellaneous = 0,
11298 LiteralTrue,
11299 LiteralFalse
11300 };
11301 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11302 return BL->getValue() ? ConstantValueKind::LiteralTrue
11303 : ConstantValueKind::LiteralFalse;
11304 return ConstantValueKind::Miscellaneous;
11305}
11306
11308 Expr *Constant, Expr *Other,
11309 const llvm::APSInt &Value,
11310 bool RhsConstant) {
11312 return false;
11313
11314 Expr *OriginalOther = Other;
11315
11316 Constant = Constant->IgnoreParenImpCasts();
11317 Other = Other->IgnoreParenImpCasts();
11318
11319 // Suppress warnings on tautological comparisons between values of the same
11320 // enumeration type. There are only two ways we could warn on this:
11321 // - If the constant is outside the range of representable values of
11322 // the enumeration. In such a case, we should warn about the cast
11323 // to enumeration type, not about the comparison.
11324 // - If the constant is the maximum / minimum in-range value. For an
11325 // enumeratin type, such comparisons can be meaningful and useful.
11326 if (Constant->getType()->isEnumeralType() &&
11327 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11328 return false;
11329
11330 std::optional<IntRange> OtherValueRange = TryGetExprRange(
11331 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
11332 if (!OtherValueRange)
11333 return false;
11334
11335 QualType OtherT = Other->getType();
11336 if (const auto *AT = OtherT->getAs<AtomicType>())
11337 OtherT = AT->getValueType();
11338 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11339
11340 // Special case for ObjC BOOL on targets where its a typedef for a signed char
11341 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11342 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11343 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
11344 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11345
11346 // Whether we're treating Other as being a bool because of the form of
11347 // expression despite it having another type (typically 'int' in C).
11348 bool OtherIsBooleanDespiteType =
11349 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11350 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11351 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
11352
11353 // Check if all values in the range of possible values of this expression
11354 // lead to the same comparison outcome.
11355 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
11356 Value.isUnsigned());
11357 auto Cmp = OtherPromotedValueRange.compare(Value);
11358 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11359 if (!Result)
11360 return false;
11361
11362 // Also consider the range determined by the type alone. This allows us to
11363 // classify the warning under the proper diagnostic group.
11364 bool TautologicalTypeCompare = false;
11365 {
11366 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11367 Value.isUnsigned());
11368 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11369 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11370 RhsConstant)) {
11371 TautologicalTypeCompare = true;
11372 Cmp = TypeCmp;
11374 }
11375 }
11376
11377 // Don't warn if the non-constant operand actually always evaluates to the
11378 // same value.
11379 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
11380 return false;
11381
11382 // Suppress the diagnostic for an in-range comparison if the constant comes
11383 // from a macro or enumerator. We don't want to diagnose
11384 //
11385 // some_long_value <= INT_MAX
11386 //
11387 // when sizeof(int) == sizeof(long).
11388 bool InRange = Cmp & PromotedRange::InRangeFlag;
11389 if (InRange && IsEnumConstOrFromMacro(S, Constant))
11390 return false;
11391
11392 // A comparison of an unsigned bit-field against 0 is really a type problem,
11393 // even though at the type level the bit-field might promote to 'signed int'.
11394 if (Other->refersToBitField() && InRange && Value == 0 &&
11395 Other->getType()->isUnsignedIntegerOrEnumerationType())
11396 TautologicalTypeCompare = true;
11397
11398 // If this is a comparison to an enum constant, include that
11399 // constant in the diagnostic.
11400 const EnumConstantDecl *ED = nullptr;
11401 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
11402 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11403
11404 // Should be enough for uint128 (39 decimal digits)
11405 SmallString<64> PrettySourceValue;
11406 llvm::raw_svector_ostream OS(PrettySourceValue);
11407 if (ED) {
11408 OS << '\'' << *ED << "' (" << Value << ")";
11409 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11410 Constant->IgnoreParenImpCasts())) {
11411 OS << (BL->getValue() ? "YES" : "NO");
11412 } else {
11413 OS << Value;
11414 }
11415
11416 if (!TautologicalTypeCompare) {
11417 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11418 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
11419 << E->getOpcodeStr() << OS.str() << *Result
11420 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11421 return true;
11422 }
11423
11424 if (IsObjCSignedCharBool) {
11425 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11426 S.PDiag(diag::warn_tautological_compare_objc_bool)
11427 << OS.str() << *Result);
11428 return true;
11429 }
11430
11431 // FIXME: We use a somewhat different formatting for the in-range cases and
11432 // cases involving boolean values for historical reasons. We should pick a
11433 // consistent way of presenting these diagnostics.
11434 if (!InRange || Other->isKnownToHaveBooleanValue()) {
11435
11437 E->getOperatorLoc(), E,
11438 S.PDiag(!InRange ? diag::warn_out_of_range_compare
11439 : diag::warn_tautological_bool_compare)
11440 << OS.str() << classifyConstantValue(Constant) << OtherT
11441 << OtherIsBooleanDespiteType << *Result
11442 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11443 } else {
11444 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11445 unsigned Diag =
11446 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11447 ? (HasEnumType(OriginalOther)
11448 ? diag::warn_unsigned_enum_always_true_comparison
11449 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11450 : diag::warn_unsigned_always_true_comparison)
11451 : diag::warn_tautological_constant_compare;
11452
11453 S.Diag(E->getOperatorLoc(), Diag)
11454 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11455 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11456 }
11457
11458 return true;
11459}
11460
11461/// Analyze the operands of the given comparison. Implements the
11462/// fallback case from AnalyzeComparison.
11464 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11465 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11466}
11467
11468/// Implements -Wsign-compare.
11469///
11470/// \param E the binary operator to check for warnings
11472 // The type the comparison is being performed in.
11473 QualType T = E->getLHS()->getType();
11474
11475 // Only analyze comparison operators where both sides have been converted to
11476 // the same type.
11477 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11478 return AnalyzeImpConvsInComparison(S, E);
11479
11480 // Don't analyze value-dependent comparisons directly.
11481 if (E->isValueDependent())
11482 return AnalyzeImpConvsInComparison(S, E);
11483
11484 Expr *LHS = E->getLHS();
11485 Expr *RHS = E->getRHS();
11486
11487 if (T->isIntegralType(S.Context)) {
11488 std::optional<llvm::APSInt> RHSValue =
11490 std::optional<llvm::APSInt> LHSValue =
11492
11493 // We don't care about expressions whose result is a constant.
11494 if (RHSValue && LHSValue)
11495 return AnalyzeImpConvsInComparison(S, E);
11496
11497 // We only care about expressions where just one side is literal
11498 if ((bool)RHSValue ^ (bool)LHSValue) {
11499 // Is the constant on the RHS or LHS?
11500 const bool RhsConstant = (bool)RHSValue;
11501 Expr *Const = RhsConstant ? RHS : LHS;
11502 Expr *Other = RhsConstant ? LHS : RHS;
11503 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11504
11505 // Check whether an integer constant comparison results in a value
11506 // of 'true' or 'false'.
11507 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11508 return AnalyzeImpConvsInComparison(S, E);
11509 }
11510 }
11511
11513 // We don't do anything special if this isn't an unsigned integral
11514 // comparison: we're only interested in integral comparisons, and
11515 // signed comparisons only happen in cases we don't care to warn about.
11516 return AnalyzeImpConvsInComparison(S, E);
11517 }
11518
11519 LHS = LHS->IgnoreParenImpCasts();
11520 RHS = RHS->IgnoreParenImpCasts();
11521
11522 if (!S.getLangOpts().CPlusPlus) {
11523 // Avoid warning about comparison of integers with different signs when
11524 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11525 // the type of `E`.
11526 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11527 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11528 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11529 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11530 }
11531
11532 // Check to see if one of the (unmodified) operands is of different
11533 // signedness.
11534 Expr *signedOperand, *unsignedOperand;
11536 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11537 "unsigned comparison between two signed integer expressions?");
11538 signedOperand = LHS;
11539 unsignedOperand = RHS;
11540 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11541 signedOperand = RHS;
11542 unsignedOperand = LHS;
11543 } else {
11544 return AnalyzeImpConvsInComparison(S, E);
11545 }
11546
11547 // Otherwise, calculate the effective range of the signed operand.
11548 std::optional<IntRange> signedRange =
11550 /*Approximate=*/true);
11551 if (!signedRange)
11552 return;
11553
11554 // Go ahead and analyze implicit conversions in the operands. Note
11555 // that we skip the implicit conversions on both sides.
11556 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11557 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11558
11559 // If the signed range is non-negative, -Wsign-compare won't fire.
11560 if (signedRange->NonNegative)
11561 return;
11562
11563 // For (in)equality comparisons, if the unsigned operand is a
11564 // constant which cannot collide with a overflowed signed operand,
11565 // then reinterpreting the signed operand as unsigned will not
11566 // change the result of the comparison.
11567 if (E->isEqualityOp()) {
11568 unsigned comparisonWidth = S.Context.getIntWidth(T);
11569 std::optional<IntRange> unsignedRange = TryGetExprRange(
11570 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
11571 /*Approximate=*/true);
11572 if (!unsignedRange)
11573 return;
11574
11575 // We should never be unable to prove that the unsigned operand is
11576 // non-negative.
11577 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
11578
11579 if (unsignedRange->Width < comparisonWidth)
11580 return;
11581 }
11582
11583 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11584 S.PDiag(diag::warn_mixed_sign_comparison)
11585 << LHS->getType() << RHS->getType()
11586 << LHS->getSourceRange() << RHS->getSourceRange());
11587}
11588
11589/// Analyzes an attempt to assign the given value to a bitfield.
11590///
11591/// Returns true if there was something fishy about the attempt.
11593 SourceLocation InitLoc) {
11594 assert(Bitfield->isBitField());
11595 if (Bitfield->isInvalidDecl())
11596 return false;
11597
11598 // White-list bool bitfields.
11599 QualType BitfieldType = Bitfield->getType();
11600 if (BitfieldType->isBooleanType())
11601 return false;
11602
11603 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
11604 // If the underlying enum type was not explicitly specified as an unsigned
11605 // type and the enum contain only positive values, MSVC++ will cause an
11606 // inconsistency by storing this as a signed type.
11607 if (S.getLangOpts().CPlusPlus11 &&
11608 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11609 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11610 BitfieldEnumDecl->getNumNegativeBits() == 0) {
11611 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11612 << BitfieldEnumDecl;
11613 }
11614 }
11615
11616 // Ignore value- or type-dependent expressions.
11617 if (Bitfield->getBitWidth()->isValueDependent() ||
11618 Bitfield->getBitWidth()->isTypeDependent() ||
11619 Init->isValueDependent() ||
11620 Init->isTypeDependent())
11621 return false;
11622
11623 Expr *OriginalInit = Init->IgnoreParenImpCasts();
11624 unsigned FieldWidth = Bitfield->getBitWidthValue();
11625
11627 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11629 // The RHS is not constant. If the RHS has an enum type, make sure the
11630 // bitfield is wide enough to hold all the values of the enum without
11631 // truncation.
11632 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
11633 const PreferredTypeAttr *PTAttr = nullptr;
11634 if (!ED) {
11635 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
11636 if (PTAttr)
11637 ED = PTAttr->getType()->getAsEnumDecl();
11638 }
11639 if (ED) {
11640 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
11641
11642 // Enum types are implicitly signed on Windows, so check if there are any
11643 // negative enumerators to see if the enum was intended to be signed or
11644 // not.
11645 bool SignedEnum = ED->getNumNegativeBits() > 0;
11646
11647 // Check for surprising sign changes when assigning enum values to a
11648 // bitfield of different signedness. If the bitfield is signed and we
11649 // have exactly the right number of bits to store this unsigned enum,
11650 // suggest changing the enum to an unsigned type. This typically happens
11651 // on Windows where unfixed enums always use an underlying type of 'int'.
11652 unsigned DiagID = 0;
11653 if (SignedEnum && !SignedBitfield) {
11654 DiagID =
11655 PTAttr == nullptr
11656 ? diag::warn_unsigned_bitfield_assigned_signed_enum
11657 : diag::
11658 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
11659 } else if (SignedBitfield && !SignedEnum &&
11660 ED->getNumPositiveBits() == FieldWidth) {
11661 DiagID =
11662 PTAttr == nullptr
11663 ? diag::warn_signed_bitfield_enum_conversion
11664 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
11665 }
11666 if (DiagID) {
11667 S.Diag(InitLoc, DiagID) << Bitfield << ED;
11668 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11669 SourceRange TypeRange =
11670 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11671 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11672 << SignedEnum << TypeRange;
11673 if (PTAttr)
11674 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
11675 << ED;
11676 }
11677
11678 // Compute the required bitwidth. If the enum has negative values, we need
11679 // one more bit than the normal number of positive bits to represent the
11680 // sign bit.
11681 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11682 ED->getNumNegativeBits())
11683 : ED->getNumPositiveBits();
11684
11685 // Check the bitwidth.
11686 if (BitsNeeded > FieldWidth) {
11687 Expr *WidthExpr = Bitfield->getBitWidth();
11688 auto DiagID =
11689 PTAttr == nullptr
11690 ? diag::warn_bitfield_too_small_for_enum
11691 : diag::warn_preferred_type_bitfield_too_small_for_enum;
11692 S.Diag(InitLoc, DiagID) << Bitfield << ED;
11693 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11694 << BitsNeeded << ED << WidthExpr->getSourceRange();
11695 if (PTAttr)
11696 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
11697 << ED;
11698 }
11699 }
11700
11701 return false;
11702 }
11703
11704 llvm::APSInt Value = Result.Val.getInt();
11705
11706 unsigned OriginalWidth = Value.getBitWidth();
11707
11708 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
11709 // false positives where the user is demonstrating they intend to use the
11710 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
11711 // to a one-bit bit-field to see if the value came from a macro named 'true'.
11712 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
11713 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
11714 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
11715 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
11716 S.findMacroSpelling(MaybeMacroLoc, "true"))
11717 return false;
11718 }
11719
11720 if (!Value.isSigned() || Value.isNegative())
11721 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11722 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11723 OriginalWidth = Value.getSignificantBits();
11724
11725 if (OriginalWidth <= FieldWidth)
11726 return false;
11727
11728 // Compute the value which the bitfield will contain.
11729 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11730 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11731
11732 // Check whether the stored value is equal to the original value.
11733 TruncatedValue = TruncatedValue.extend(OriginalWidth);
11734 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11735 return false;
11736
11737 std::string PrettyValue = toString(Value, 10);
11738 std::string PrettyTrunc = toString(TruncatedValue, 10);
11739
11740 S.Diag(InitLoc, OneAssignedToOneBitBitfield
11741 ? diag::warn_impcast_single_bit_bitield_precision_constant
11742 : diag::warn_impcast_bitfield_precision_constant)
11743 << PrettyValue << PrettyTrunc << OriginalInit->getType()
11744 << Init->getSourceRange();
11745
11746 return true;
11747}
11748
11749/// Analyze the given simple or compound assignment for warning-worthy
11750/// operations.
11752 // Just recurse on the LHS.
11753 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11754
11755 // We want to recurse on the RHS as normal unless we're assigning to
11756 // a bitfield.
11757 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11758 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11759 E->getOperatorLoc())) {
11760 // Recurse, ignoring any implicit conversions on the RHS.
11761 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11762 E->getOperatorLoc());
11763 }
11764 }
11765
11766 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11767
11768 // Diagnose implicitly sequentially-consistent atomic assignment.
11769 if (E->getLHS()->getType()->isAtomicType())
11770 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11771}
11772
11773/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
11774static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
11775 QualType T, SourceLocation CContext, unsigned diag,
11776 bool PruneControlFlow = false) {
11777 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
11778 // address space annotations isn't really useful. The warnings aren't because
11779 // you're converting a `private int` to `unsigned int`, it is because you're
11780 // conerting `int` to `unsigned int`.
11781 if (SourceType.hasAddressSpace())
11782 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
11783 if (T.hasAddressSpace())
11785 if (PruneControlFlow) {
11787 S.PDiag(diag)
11788 << SourceType << T << E->getSourceRange()
11789 << SourceRange(CContext));
11790 return;
11791 }
11792 S.Diag(E->getExprLoc(), diag)
11793 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11794}
11795
11796/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
11797static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
11798 SourceLocation CContext, unsigned diag,
11799 bool PruneControlFlow = false) {
11800 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
11801}
11802
11803/// Diagnose an implicit cast from a floating point value to an integer value.
11805 SourceLocation CContext) {
11806 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11807 bool PruneWarnings = S.inTemplateInstantiation();
11808
11809 const Expr *InnerE = E->IgnoreParenImpCasts();
11810 // We also want to warn on, e.g., "int i = -1.234"
11811 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
11812 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11813 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11814
11815 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11816
11817 llvm::APFloat Value(0.0);
11818 bool IsConstant =
11820 if (!IsConstant) {
11821 if (S.ObjC().isSignedCharBool(T)) {
11823 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11824 << E->getType());
11825 }
11826
11827 return DiagnoseImpCast(S, E, T, CContext,
11828 diag::warn_impcast_float_integer, PruneWarnings);
11829 }
11830
11831 bool isExact = false;
11832
11833 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11835 llvm::APFloat::opStatus Result = Value.convertToInteger(
11836 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11837
11838 // FIXME: Force the precision of the source value down so we don't print
11839 // digits which are usually useless (we don't really care here if we
11840 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
11841 // would automatically print the shortest representation, but it's a bit
11842 // tricky to implement.
11843 SmallString<16> PrettySourceValue;
11844 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11845 precision = (precision * 59 + 195) / 196;
11846 Value.toString(PrettySourceValue, precision);
11847
11848 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
11850 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11851 << PrettySourceValue);
11852 }
11853
11854 if (Result == llvm::APFloat::opOK && isExact) {
11855 if (IsLiteral) return;
11856 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11857 PruneWarnings);
11858 }
11859
11860 // Conversion of a floating-point value to a non-bool integer where the
11861 // integral part cannot be represented by the integer type is undefined.
11862 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11863 return DiagnoseImpCast(
11864 S, E, T, CContext,
11865 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11866 : diag::warn_impcast_float_to_integer_out_of_range,
11867 PruneWarnings);
11868
11869 unsigned DiagID = 0;
11870 if (IsLiteral) {
11871 // Warn on floating point literal to integer.
11872 DiagID = diag::warn_impcast_literal_float_to_integer;
11873 } else if (IntegerValue == 0) {
11874 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
11875 return DiagnoseImpCast(S, E, T, CContext,
11876 diag::warn_impcast_float_integer, PruneWarnings);
11877 }
11878 // Warn on non-zero to zero conversion.
11879 DiagID = diag::warn_impcast_float_to_integer_zero;
11880 } else {
11881 if (IntegerValue.isUnsigned()) {
11882 if (!IntegerValue.isMaxValue()) {
11883 return DiagnoseImpCast(S, E, T, CContext,
11884 diag::warn_impcast_float_integer, PruneWarnings);
11885 }
11886 } else { // IntegerValue.isSigned()
11887 if (!IntegerValue.isMaxSignedValue() &&
11888 !IntegerValue.isMinSignedValue()) {
11889 return DiagnoseImpCast(S, E, T, CContext,
11890 diag::warn_impcast_float_integer, PruneWarnings);
11891 }
11892 }
11893 // Warn on evaluatable floating point expression to integer conversion.
11894 DiagID = diag::warn_impcast_float_to_integer;
11895 }
11896
11897 SmallString<16> PrettyTargetValue;
11898 if (IsBool)
11899 PrettyTargetValue = Value.isZero() ? "false" : "true";
11900 else
11901 IntegerValue.toString(PrettyTargetValue);
11902
11903 if (PruneWarnings) {
11905 S.PDiag(DiagID)
11906 << E->getType() << T.getUnqualifiedType()
11907 << PrettySourceValue << PrettyTargetValue
11908 << E->getSourceRange() << SourceRange(CContext));
11909 } else {
11910 S.Diag(E->getExprLoc(), DiagID)
11911 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11912 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11913 }
11914}
11915
11916/// Analyze the given compound assignment for the possible losing of
11917/// floating-point precision.
11919 assert(isa<CompoundAssignOperator>(E) &&
11920 "Must be compound assignment operation");
11921 // Recurse on the LHS and RHS in here
11922 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11923 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11924
11925 if (E->getLHS()->getType()->isAtomicType())
11926 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11927
11928 // Now check the outermost expression
11929 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11930 const auto *RBT = cast<CompoundAssignOperator>(E)
11931 ->getComputationResultType()
11932 ->getAs<BuiltinType>();
11933
11934 // The below checks assume source is floating point.
11935 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11936
11937 // If source is floating point but target is an integer.
11938 if (ResultBT->isInteger())
11939 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11940 E->getExprLoc(), diag::warn_impcast_float_integer);
11941
11942 if (!ResultBT->isFloatingPoint())
11943 return;
11944
11945 // If both source and target are floating points, warn about losing precision.
11947 QualType(ResultBT, 0), QualType(RBT, 0));
11948 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11949 // warn about dropping FP rank.
11950 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11951 diag::warn_impcast_float_result_precision);
11952}
11953
11954static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11955 IntRange Range) {
11956 if (!Range.Width) return "0";
11957
11958 llvm::APSInt ValueInRange = Value;
11959 ValueInRange.setIsSigned(!Range.NonNegative);
11960 ValueInRange = ValueInRange.trunc(Range.Width);
11961 return toString(ValueInRange, 10);
11962}
11963
11964static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
11965 bool ToBool) {
11966 if (!isa<ImplicitCastExpr>(Ex))
11967 return false;
11968
11969 const Expr *InnerE = Ex->IgnoreParenImpCasts();
11971 const Type *Source =
11973 if (Target->isDependentType())
11974 return false;
11975
11976 const auto *FloatCandidateBT =
11977 dyn_cast<BuiltinType>(ToBool ? Source : Target);
11978 const Type *BoolCandidateType = ToBool ? Target : Source;
11979
11980 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11981 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11982}
11983
11984static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
11985 SourceLocation CC) {
11986 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
11987 const Expr *CurrA = TheCall->getArg(I);
11988 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11989 continue;
11990
11991 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
11992 S, TheCall->getArg(I - 1), false));
11993 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
11994 S, TheCall->getArg(I + 1), false));
11995 if (IsSwapped) {
11996 // Warn on this floating-point to bool conversion.
11998 CurrA->getType(), CC,
11999 diag::warn_impcast_floating_point_to_bool);
12000 }
12001 }
12002}
12003
12005 SourceLocation CC) {
12006 // Don't warn on functions which have return type nullptr_t.
12007 if (isa<CallExpr>(E))
12008 return;
12009
12010 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12011 const Expr *NewE = E->IgnoreParenImpCasts();
12012 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
12013 bool HasNullPtrType = NewE->getType()->isNullPtrType();
12014 if (!IsGNUNullExpr && !HasNullPtrType)
12015 return;
12016
12017 // Return if target type is a safe conversion.
12018 if (T->isAnyPointerType() || T->isBlockPointerType() ||
12020 return;
12021
12022 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12023 E->getExprLoc()))
12024 return;
12025
12027
12028 // Venture through the macro stacks to get to the source of macro arguments.
12029 // The new location is a better location than the complete location that was
12030 // passed in.
12033
12034 // __null is usually wrapped in a macro. Go up a macro if that is the case.
12035 if (IsGNUNullExpr && Loc.isMacroID()) {
12036 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12037 Loc, S.SourceMgr, S.getLangOpts());
12038 if (MacroName == "NULL")
12040 }
12041
12042 // Only warn if the null and context location are in the same macro expansion.
12043 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12044 return;
12045
12046 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12047 << HasNullPtrType << T << SourceRange(CC)
12050}
12051
12052// Helper function to filter out cases for constant width constant conversion.
12053// Don't warn on char array initialization or for non-decimal values.
12055 SourceLocation CC) {
12056 // If initializing from a constant, and the constant starts with '0',
12057 // then it is a binary, octal, or hexadecimal. Allow these constants
12058 // to fill all the bits, even if there is a sign change.
12059 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12060 const char FirstLiteralCharacter =
12061 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12062 if (FirstLiteralCharacter == '0')
12063 return false;
12064 }
12065
12066 // If the CC location points to a '{', and the type is char, then assume
12067 // assume it is an array initialization.
12068 if (CC.isValid() && T->isCharType()) {
12069 const char FirstContextCharacter =
12071 if (FirstContextCharacter == '{')
12072 return false;
12073 }
12074
12075 return true;
12076}
12077
12079 const auto *IL = dyn_cast<IntegerLiteral>(E);
12080 if (!IL) {
12081 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12082 if (UO->getOpcode() == UO_Minus)
12083 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12084 }
12085 }
12086
12087 return IL;
12088}
12089
12091 E = E->IgnoreParenImpCasts();
12092 SourceLocation ExprLoc = E->getExprLoc();
12093
12094 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12095 BinaryOperator::Opcode Opc = BO->getOpcode();
12097 // Do not diagnose unsigned shifts.
12098 if (Opc == BO_Shl) {
12099 const auto *LHS = getIntegerLiteral(BO->getLHS());
12100 const auto *RHS = getIntegerLiteral(BO->getRHS());
12101 if (LHS && LHS->getValue() == 0)
12102 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12103 else if (!E->isValueDependent() && LHS && RHS &&
12104 RHS->getValue().isNonNegative() &&
12106 S.Diag(ExprLoc, diag::warn_left_shift_always)
12107 << (Result.Val.getInt() != 0);
12108 else if (E->getType()->isSignedIntegerType())
12109 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
12112 ") != 0");
12113 }
12114 }
12115
12116 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12117 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12118 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12119 if (!LHS || !RHS)
12120 return;
12121 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12122 (RHS->getValue() == 0 || RHS->getValue() == 1))
12123 // Do not diagnose common idioms.
12124 return;
12125 if (LHS->getValue() != 0 && RHS->getValue() != 0)
12126 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12127 }
12128}
12129
12131 const Type *Target, Expr *E,
12132 QualType T,
12133 SourceLocation CC) {
12134 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
12135 Source != Target);
12139 llvm::APSInt Value(32);
12140 Value = Result.Val.getInt();
12141 bool IsASCII = Value <= 0x7F;
12142 bool IsBMP = Value <= 0xD7FF || (Value >= 0xE000 && Value <= 0xFFFF);
12143 bool ConversionPreservesSemantics =
12144 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
12145
12146 if (!ConversionPreservesSemantics) {
12147 auto IsSingleCodeUnitCP = [](const QualType &T,
12148 const llvm::APSInt &Value) {
12149 if (T->isChar8Type())
12150 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
12151 if (T->isChar16Type())
12152 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
12153 assert(T->isChar32Type());
12154 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
12155 };
12156
12157 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
12158 << E->getType() << T
12159 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
12160 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
12161 }
12162 } else {
12163 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
12165 DiagnoseImpCast(S, E, T, CC,
12166 LosesPrecision ? diag::warn_impcast_unicode_precision
12167 : diag::warn_impcast_unicode_char_type);
12168 }
12169}
12170
12175};
12176
12178 QualType To) {
12179 QualType MaybePointee = From->getPointeeType();
12180 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12181 From = MaybePointee;
12182 MaybePointee = To->getPointeeType();
12183 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12184 To = MaybePointee;
12185
12186 if (const auto *FromFn = From->getAs<FunctionType>()) {
12187 if (const auto *ToFn = To->getAs<FunctionType>()) {
12188 if (FromFn->getCFIUncheckedCalleeAttr() &&
12189 !ToFn->getCFIUncheckedCalleeAttr())
12190 return Discarding;
12191 if (!FromFn->getCFIUncheckedCalleeAttr() &&
12192 ToFn->getCFIUncheckedCalleeAttr())
12193 return Adding;
12194 }
12195 }
12196 return None;
12197}
12198
12200 From = Context.getCanonicalType(From);
12201 To = Context.getCanonicalType(To);
12202 return ::AdjustingCFIUncheckedCallee(From, To) == Discarding;
12203}
12204
12206 From = Context.getCanonicalType(From);
12207 To = Context.getCanonicalType(To);
12208 return ::AdjustingCFIUncheckedCallee(From, To) == Adding;
12209}
12210
12212 bool *ICContext, bool IsListInit) {
12213 if (E->isTypeDependent() || E->isValueDependent()) return;
12214
12215 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
12217 if (Source == Target) return;
12218 if (Target->isDependentType()) return;
12219
12220 // If the conversion context location is invalid don't complain. We also
12221 // don't want to emit a warning if the issue occurs from the expansion of
12222 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12223 // delay this check as long as possible. Once we detect we are in that
12224 // scenario, we just return.
12225 if (CC.isInvalid())
12226 return;
12227
12228 if (Source->isAtomicType())
12229 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12230
12231 // Diagnose implicit casts to bool.
12232 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12233 if (isa<StringLiteral>(E))
12234 // Warn on string literal to bool. Checks for string literals in logical
12235 // and expressions, for instance, assert(0 && "error here"), are
12236 // prevented by a check in AnalyzeImplicitConversions().
12237 return DiagnoseImpCast(*this, E, T, CC,
12238 diag::warn_impcast_string_literal_to_bool);
12239 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12240 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12241 // This covers the literal expressions that evaluate to Objective-C
12242 // objects.
12243 return DiagnoseImpCast(*this, E, T, CC,
12244 diag::warn_impcast_objective_c_literal_to_bool);
12245 }
12246 if (Source->isPointerType() || Source->canDecayToPointerType()) {
12247 // Warn on pointer to bool conversion that is always true.
12249 SourceRange(CC));
12250 }
12251 }
12252
12253 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12254 // is a typedef for signed char (macOS), then that constant value has to be 1
12255 // or 0.
12256 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
12259 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12261 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12262 << toString(Result.Val.getInt(), 10));
12263 }
12264 return;
12265 }
12266 }
12267
12268 // Check implicit casts from Objective-C collection literals to specialized
12269 // collection types, e.g., NSArray<NSString *> *.
12270 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12271 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
12272 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12273 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
12274
12275 // Strip vector types.
12276 if (isa<VectorType>(Source)) {
12277 if (Target->isSveVLSBuiltinType() &&
12278 (ARM().areCompatibleSveTypes(QualType(Target, 0),
12279 QualType(Source, 0)) ||
12280 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
12281 QualType(Source, 0))))
12282 return;
12283
12284 if (Target->isRVVVLSBuiltinType() &&
12286 QualType(Source, 0)) ||
12288 QualType(Source, 0))))
12289 return;
12290
12291 if (!isa<VectorType>(Target)) {
12292 if (SourceMgr.isInSystemMacro(CC))
12293 return;
12294 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
12295 } else if (getLangOpts().HLSL &&
12296 Target->castAs<VectorType>()->getNumElements() <
12297 Source->castAs<VectorType>()->getNumElements()) {
12298 // Diagnose vector truncation but don't return. We may also want to
12299 // diagnose an element conversion.
12300 DiagnoseImpCast(*this, E, T, CC,
12301 diag::warn_hlsl_impcast_vector_truncation);
12302 }
12303
12304 // If the vector cast is cast between two vectors of the same size, it is
12305 // a bitcast, not a conversion, except under HLSL where it is a conversion.
12306 if (!getLangOpts().HLSL &&
12308 return;
12309
12310 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12311 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12312 }
12313 if (auto VecTy = dyn_cast<VectorType>(Target))
12314 Target = VecTy->getElementType().getTypePtr();
12315
12316 // Strip complex types.
12317 if (isa<ComplexType>(Source)) {
12318 if (!isa<ComplexType>(Target)) {
12319 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12320 return;
12321
12322 return DiagnoseImpCast(*this, E, T, CC,
12324 ? diag::err_impcast_complex_scalar
12325 : diag::warn_impcast_complex_scalar);
12326 }
12327
12328 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12329 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12330 }
12331
12332 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12333 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12334
12335 // Strip SVE vector types
12336 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
12337 // Need the original target type for vector type checks
12338 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
12339 // Handle conversion from scalable to fixed when msve-vector-bits is
12340 // specified
12341 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
12342 QualType(Source, 0)) ||
12343 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
12344 QualType(Source, 0)))
12345 return;
12346
12347 // If the vector cast is cast between two vectors of the same size, it is
12348 // a bitcast, not a conversion.
12350 return;
12351
12352 Source = SourceBT->getSveEltType(Context).getTypePtr();
12353 }
12354
12355 if (TargetBT && TargetBT->isSveVLSBuiltinType())
12356 Target = TargetBT->getSveEltType(Context).getTypePtr();
12357
12358 // If the source is floating point...
12359 if (SourceBT && SourceBT->isFloatingPoint()) {
12360 // ...and the target is floating point...
12361 if (TargetBT && TargetBT->isFloatingPoint()) {
12362 // ...then warn if we're dropping FP rank.
12363
12365 QualType(SourceBT, 0), QualType(TargetBT, 0));
12366 if (Order > 0) {
12367 // Don't warn about float constants that are precisely
12368 // representable in the target type.
12369 Expr::EvalResult result;
12370 if (E->EvaluateAsRValue(result, Context)) {
12371 // Value might be a float, a float vector, or a float complex.
12373 result.Val,
12375 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12376 return;
12377 }
12378
12379 if (SourceMgr.isInSystemMacro(CC))
12380 return;
12381
12382 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
12383 }
12384 // ... or possibly if we're increasing rank, too
12385 else if (Order < 0) {
12386 if (SourceMgr.isInSystemMacro(CC))
12387 return;
12388
12389 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
12390 }
12391 return;
12392 }
12393
12394 // If the target is integral, always warn.
12395 if (TargetBT && TargetBT->isInteger()) {
12396 if (SourceMgr.isInSystemMacro(CC))
12397 return;
12398
12399 DiagnoseFloatingImpCast(*this, E, T, CC);
12400 }
12401
12402 // Detect the case where a call result is converted from floating-point to
12403 // to bool, and the final argument to the call is converted from bool, to
12404 // discover this typo:
12405 //
12406 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
12407 //
12408 // FIXME: This is an incredibly special case; is there some more general
12409 // way to detect this class of misplaced-parentheses bug?
12410 if (Target->isBooleanType() && isa<CallExpr>(E)) {
12411 // Check last argument of function call to see if it is an
12412 // implicit cast from a type matching the type the result
12413 // is being cast to.
12414 CallExpr *CEx = cast<CallExpr>(E);
12415 if (unsigned NumArgs = CEx->getNumArgs()) {
12416 Expr *LastA = CEx->getArg(NumArgs - 1);
12417 Expr *InnerE = LastA->IgnoreParenImpCasts();
12418 if (isa<ImplicitCastExpr>(LastA) &&
12419 InnerE->getType()->isBooleanType()) {
12420 // Warn on this floating-point to bool conversion
12421 DiagnoseImpCast(*this, E, T, CC,
12422 diag::warn_impcast_floating_point_to_bool);
12423 }
12424 }
12425 }
12426 return;
12427 }
12428
12429 // Valid casts involving fixed point types should be accounted for here.
12430 if (Source->isFixedPointType()) {
12431 if (Target->isUnsaturatedFixedPointType()) {
12435 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12436 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
12437 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
12438 if (Value > MaxVal || Value < MinVal) {
12440 PDiag(diag::warn_impcast_fixed_point_range)
12441 << Value.toString() << T
12442 << E->getSourceRange()
12443 << clang::SourceRange(CC));
12444 return;
12445 }
12446 }
12447 } else if (Target->isIntegerType()) {
12451 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12452
12453 bool Overflowed;
12454 llvm::APSInt IntResult = FXResult.convertToInt(
12455 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
12456 &Overflowed);
12457
12458 if (Overflowed) {
12460 PDiag(diag::warn_impcast_fixed_point_range)
12461 << FXResult.toString() << T
12462 << E->getSourceRange()
12463 << clang::SourceRange(CC));
12464 return;
12465 }
12466 }
12467 }
12468 } else if (Target->isUnsaturatedFixedPointType()) {
12469 if (Source->isIntegerType()) {
12473 llvm::APSInt Value = Result.Val.getInt();
12474
12475 bool Overflowed;
12476 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12477 Value, Context.getFixedPointSemantics(T), &Overflowed);
12478
12479 if (Overflowed) {
12481 PDiag(diag::warn_impcast_fixed_point_range)
12482 << toString(Value, /*Radix=*/10) << T
12483 << E->getSourceRange()
12484 << clang::SourceRange(CC));
12485 return;
12486 }
12487 }
12488 }
12489 }
12490
12491 // If we are casting an integer type to a floating point type without
12492 // initialization-list syntax, we might lose accuracy if the floating
12493 // point type has a narrower significand than the integer type.
12494 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12495 TargetBT->isFloatingType() && !IsListInit) {
12496 // Determine the number of precision bits in the source integer type.
12497 std::optional<IntRange> SourceRange =
12499 /*Approximate=*/true);
12500 if (!SourceRange)
12501 return;
12502 unsigned int SourcePrecision = SourceRange->Width;
12503
12504 // Determine the number of precision bits in the
12505 // target floating point type.
12506 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12507 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12508
12509 if (SourcePrecision > 0 && TargetPrecision > 0 &&
12510 SourcePrecision > TargetPrecision) {
12511
12512 if (std::optional<llvm::APSInt> SourceInt =
12514 // If the source integer is a constant, convert it to the target
12515 // floating point type. Issue a warning if the value changes
12516 // during the whole conversion.
12517 llvm::APFloat TargetFloatValue(
12518 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12519 llvm::APFloat::opStatus ConversionStatus =
12520 TargetFloatValue.convertFromAPInt(
12521 *SourceInt, SourceBT->isSignedInteger(),
12522 llvm::APFloat::rmNearestTiesToEven);
12523
12524 if (ConversionStatus != llvm::APFloat::opOK) {
12525 SmallString<32> PrettySourceValue;
12526 SourceInt->toString(PrettySourceValue, 10);
12527 SmallString<32> PrettyTargetValue;
12528 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12529
12531 E->getExprLoc(), E,
12532 PDiag(diag::warn_impcast_integer_float_precision_constant)
12533 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12534 << E->getSourceRange() << clang::SourceRange(CC));
12535 }
12536 } else {
12537 // Otherwise, the implicit conversion may lose precision.
12538 DiagnoseImpCast(*this, E, T, CC,
12539 diag::warn_impcast_integer_float_precision);
12540 }
12541 }
12542 }
12543
12544 DiagnoseNullConversion(*this, E, T, CC);
12545
12547
12548 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
12549 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
12550 return;
12551 }
12552
12553 if (Target->isBooleanType())
12555
12557 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
12558 << QualType(Source, 0) << QualType(Target, 0);
12559 }
12560
12561 if (!Source->isIntegerType() || !Target->isIntegerType())
12562 return;
12563
12564 // TODO: remove this early return once the false positives for constant->bool
12565 // in templates, macros, etc, are reduced or removed.
12566 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12567 return;
12568
12569 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
12570 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12572 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12573 << E->getType());
12574 }
12575 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
12576 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
12577 if (!LikelySourceRange)
12578 return;
12579
12580 IntRange SourceTypeRange =
12581 IntRange::forTargetOfCanonicalType(Context, Source);
12582 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
12583
12584 if (LikelySourceRange->Width > TargetRange.Width) {
12585 // If the source is a constant, use a default-on diagnostic.
12586 // TODO: this should happen for bitfield stores, too.
12590 llvm::APSInt Value(32);
12591 Value = Result.Val.getInt();
12592
12593 if (SourceMgr.isInSystemMacro(CC))
12594 return;
12595
12596 std::string PrettySourceValue = toString(Value, 10);
12597 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12598
12600 PDiag(diag::warn_impcast_integer_precision_constant)
12601 << PrettySourceValue << PrettyTargetValue
12602 << E->getType() << T << E->getSourceRange()
12603 << SourceRange(CC));
12604 return;
12605 }
12606
12607 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12608 if (SourceMgr.isInSystemMacro(CC))
12609 return;
12610
12611 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
12612 if (UO->getOpcode() == UO_Minus)
12613 return DiagnoseImpCast(
12614 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
12615 }
12616
12617 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
12618 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
12619 /* pruneControlFlow */ true);
12620 return DiagnoseImpCast(*this, E, T, CC,
12621 diag::warn_impcast_integer_precision);
12622 }
12623
12624 if (TargetRange.Width > SourceTypeRange.Width) {
12625 if (auto *UO = dyn_cast<UnaryOperator>(E))
12626 if (UO->getOpcode() == UO_Minus)
12627 if (Source->isUnsignedIntegerType()) {
12628 if (Target->isUnsignedIntegerType())
12629 return DiagnoseImpCast(*this, E, T, CC,
12630 diag::warn_impcast_high_order_zero_bits);
12631 if (Target->isSignedIntegerType())
12632 return DiagnoseImpCast(*this, E, T, CC,
12633 diag::warn_impcast_nonnegative_result);
12634 }
12635 }
12636
12637 if (TargetRange.Width == LikelySourceRange->Width &&
12638 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
12639 Source->isSignedIntegerType()) {
12640 // Warn when doing a signed to signed conversion, warn if the positive
12641 // source value is exactly the width of the target type, which will
12642 // cause a negative value to be stored.
12643
12647 llvm::APSInt Value = Result.Val.getInt();
12648 if (isSameWidthConstantConversion(*this, E, T, CC)) {
12649 std::string PrettySourceValue = toString(Value, 10);
12650 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12651
12652 Diag(E->getExprLoc(),
12653 PDiag(diag::warn_impcast_integer_precision_constant)
12654 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12655 << E->getSourceRange() << SourceRange(CC));
12656 return;
12657 }
12658 }
12659
12660 // Fall through for non-constants to give a sign conversion warning.
12661 }
12662
12663 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
12664 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
12665 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
12666 LikelySourceRange->Width == TargetRange.Width))) {
12667 if (SourceMgr.isInSystemMacro(CC))
12668 return;
12669
12670 if (SourceBT && SourceBT->isInteger() && TargetBT &&
12671 TargetBT->isInteger() &&
12672 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
12673 return;
12674 }
12675
12676 unsigned DiagID = diag::warn_impcast_integer_sign;
12677
12678 // Traditionally, gcc has warned about this under -Wsign-compare.
12679 // We also want to warn about it in -Wconversion.
12680 // So if -Wconversion is off, use a completely identical diagnostic
12681 // in the sign-compare group.
12682 // The conditional-checking code will
12683 if (ICContext) {
12684 DiagID = diag::warn_impcast_integer_sign_conditional;
12685 *ICContext = true;
12686 }
12687
12688 DiagnoseImpCast(*this, E, T, CC, DiagID);
12689 }
12690
12691 // If we're implicitly converting from an integer into an enumeration, that
12692 // is valid in C but invalid in C++.
12693 QualType SourceType = E->getEnumCoercedType(Context);
12694 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
12695 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
12696 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
12697
12698 // Diagnose conversions between different enumeration types.
12699 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12700 // type, to give us better diagnostics.
12701 Source = Context.getCanonicalType(SourceType).getTypePtr();
12702
12703 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
12704 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
12705 if (SourceEnum->getOriginalDecl()->hasNameForLinkage() &&
12706 TargetEnum->getOriginalDecl()->hasNameForLinkage() &&
12707 SourceEnum != TargetEnum) {
12708 if (SourceMgr.isInSystemMacro(CC))
12709 return;
12710
12711 return DiagnoseImpCast(*this, E, SourceType, T, CC,
12712 diag::warn_impcast_different_enum_types);
12713 }
12714}
12715
12718
12720 SourceLocation CC, bool &ICContext) {
12721 E = E->IgnoreParenImpCasts();
12722 // Diagnose incomplete type for second or third operand in C.
12723 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
12724 S.RequireCompleteExprType(E, diag::err_incomplete_type);
12725
12726 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12727 return CheckConditionalOperator(S, CO, CC, T);
12728
12730 if (E->getType() != T)
12731 return S.CheckImplicitConversion(E, T, CC, &ICContext);
12732}
12733
12736 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12737
12738 Expr *TrueExpr = E->getTrueExpr();
12739 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12740 TrueExpr = BCO->getCommon();
12741
12742 bool Suspicious = false;
12743 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12744 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12745
12746 if (T->isBooleanType())
12748
12749 // If -Wconversion would have warned about either of the candidates
12750 // for a signedness conversion to the context type...
12751 if (!Suspicious) return;
12752
12753 // ...but it's currently ignored...
12754 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12755 return;
12756
12757 // ...then check whether it would have warned about either of the
12758 // candidates for a signedness conversion to the condition type.
12759 if (E->getType() == T) return;
12760
12761 Suspicious = false;
12763 &Suspicious);
12764 if (!Suspicious)
12765 S.CheckImplicitConversion(E->getFalseExpr()->IgnoreParenImpCasts(),
12766 E->getType(), CC, &Suspicious);
12767}
12768
12769/// Check conversion of given expression to boolean.
12770/// Input argument E is a logical expression.
12772 // Run the bool-like conversion checks only for C since there bools are
12773 // still not used as the return type from "boolean" operators or as the input
12774 // type for conditional operators.
12775 if (S.getLangOpts().CPlusPlus)
12776 return;
12778 return;
12780}
12781
12782namespace {
12783struct AnalyzeImplicitConversionsWorkItem {
12784 Expr *E;
12785 SourceLocation CC;
12786 bool IsListInit;
12787};
12788}
12789
12791 Sema &S, Expr *E, QualType T, SourceLocation CC,
12792 bool ExtraCheckForImplicitConversion,
12794 E = E->IgnoreParenImpCasts();
12795 WorkList.push_back({E, CC, false});
12796
12797 if (ExtraCheckForImplicitConversion && E->getType() != T)
12798 S.CheckImplicitConversion(E, T, CC);
12799}
12800
12801/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12802/// that should be visited are added to WorkList.
12804 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12806 Expr *OrigE = Item.E;
12807 SourceLocation CC = Item.CC;
12808
12809 QualType T = OrigE->getType();
12810 Expr *E = OrigE->IgnoreParenImpCasts();
12811
12812 // Propagate whether we are in a C++ list initialization expression.
12813 // If so, we do not issue warnings for implicit int-float conversion
12814 // precision loss, because C++11 narrowing already handles it.
12815 //
12816 // HLSL's initialization lists are special, so they shouldn't observe the C++
12817 // behavior here.
12818 bool IsListInit =
12819 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
12820 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
12821
12822 if (E->isTypeDependent() || E->isValueDependent())
12823 return;
12824
12825 Expr *SourceExpr = E;
12826 // Examine, but don't traverse into the source expression of an
12827 // OpaqueValueExpr, since it may have multiple parents and we don't want to
12828 // emit duplicate diagnostics. Its fine to examine the form or attempt to
12829 // evaluate it in the context of checking the specific conversion to T though.
12830 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12831 if (auto *Src = OVE->getSourceExpr())
12832 SourceExpr = Src;
12833
12834 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12835 if (UO->getOpcode() == UO_Not &&
12836 UO->getSubExpr()->isKnownToHaveBooleanValue())
12837 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12838 << OrigE->getSourceRange() << T->isBooleanType()
12839 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12840
12841 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
12842 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
12843 BO->getLHS()->isKnownToHaveBooleanValue() &&
12844 BO->getRHS()->isKnownToHaveBooleanValue() &&
12845 BO->getLHS()->HasSideEffects(S.Context) &&
12846 BO->getRHS()->HasSideEffects(S.Context)) {
12848 const LangOptions &LO = S.getLangOpts();
12849 SourceLocation BLoc = BO->getOperatorLoc();
12850 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
12851 StringRef SR = clang::Lexer::getSourceText(
12852 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
12853 // To reduce false positives, only issue the diagnostic if the operator
12854 // is explicitly spelled as a punctuator. This suppresses the diagnostic
12855 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
12856 // in C, along with other macro spellings the user might invent.
12857 if (SR.str() == "&" || SR.str() == "|") {
12858
12859 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
12860 << (BO->getOpcode() == BO_And ? "&" : "|")
12861 << OrigE->getSourceRange()
12863 BO->getOperatorLoc(),
12864 (BO->getOpcode() == BO_And ? "&&" : "||"));
12865 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
12866 }
12867 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
12868 /// Analyze the given comma operator. The basic idea behind the analysis
12869 /// is to analyze the left and right operands slightly differently. The
12870 /// left operand needs to check whether the operand itself has an implicit
12871 /// conversion, but not whether the left operand induces an implicit
12872 /// conversion for the entire comma expression itself. This is similar to
12873 /// how CheckConditionalOperand behaves; it's as-if the correct operand
12874 /// were directly used for the implicit conversion check.
12875 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
12876 /*ExtraCheckForImplicitConversion=*/false, WorkList);
12877 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
12878 /*ExtraCheckForImplicitConversion=*/true, WorkList);
12879 return;
12880 }
12881 }
12882
12883 // For conditional operators, we analyze the arguments as if they
12884 // were being fed directly into the output.
12885 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
12886 CheckConditionalOperator(S, CO, CC, T);
12887 return;
12888 }
12889
12890 // Check implicit argument conversions for function calls.
12891 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
12893
12894 // Go ahead and check any implicit conversions we might have skipped.
12895 // The non-canonical typecheck is just an optimization;
12896 // CheckImplicitConversion will filter out dead implicit conversions.
12897 if (SourceExpr->getType() != T)
12898 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
12899
12900 // Now continue drilling into this expression.
12901
12902 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12903 // The bound subexpressions in a PseudoObjectExpr are not reachable
12904 // as transitive children.
12905 // FIXME: Use a more uniform representation for this.
12906 for (auto *SE : POE->semantics())
12907 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12908 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
12909 }
12910
12911 // Skip past explicit casts.
12912 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12913 E = CE->getSubExpr()->IgnoreParenImpCasts();
12914 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12915 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12916 WorkList.push_back({E, CC, IsListInit});
12917 return;
12918 }
12919
12920 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
12921 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
12922 // The base expression is only used to initialize the parameter for
12923 // arguments to `inout` parameters, so we only traverse down the base
12924 // expression for `inout` cases.
12925 if (OutArgE->isInOut())
12926 WorkList.push_back(
12927 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
12928 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
12929 return;
12930 }
12931
12932 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12933 // Do a somewhat different check with comparison operators.
12934 if (BO->isComparisonOp())
12935 return AnalyzeComparison(S, BO);
12936
12937 // And with simple assignments.
12938 if (BO->getOpcode() == BO_Assign)
12939 return AnalyzeAssignment(S, BO);
12940 // And with compound assignments.
12941 if (BO->isAssignmentOp())
12942 return AnalyzeCompoundAssignment(S, BO);
12943 }
12944
12945 // These break the otherwise-useful invariant below. Fortunately,
12946 // we don't really need to recurse into them, because any internal
12947 // expressions should have been analyzed already when they were
12948 // built into statements.
12949 if (isa<StmtExpr>(E)) return;
12950
12951 // Don't descend into unevaluated contexts.
12952 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12953
12954 // Now just recurse over the expression's children.
12955 CC = E->getExprLoc();
12956 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12957 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12958 for (Stmt *SubStmt : E->children()) {
12959 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12960 if (!ChildExpr)
12961 continue;
12962
12963 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
12964 if (ChildExpr == CSE->getOperand())
12965 // Do not recurse over a CoroutineSuspendExpr's operand.
12966 // The operand is also a subexpression of getCommonExpr(), and
12967 // recursing into it directly would produce duplicate diagnostics.
12968 continue;
12969
12970 if (IsLogicalAndOperator &&
12971 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12972 // Ignore checking string literals that are in logical and operators.
12973 // This is a common pattern for asserts.
12974 continue;
12975 WorkList.push_back({ChildExpr, CC, IsListInit});
12976 }
12977
12978 if (BO && BO->isLogicalOp()) {
12979 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12980 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12981 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12982
12983 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12984 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12985 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12986 }
12987
12988 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12989 if (U->getOpcode() == UO_LNot) {
12990 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12991 } else if (U->getOpcode() != UO_AddrOf) {
12992 if (U->getSubExpr()->getType()->isAtomicType())
12993 S.Diag(U->getSubExpr()->getBeginLoc(),
12994 diag::warn_atomic_implicit_seq_cst);
12995 }
12996 }
12997}
12998
12999/// AnalyzeImplicitConversions - Find and report any interesting
13000/// implicit conversions in the given expression. There are a couple
13001/// of competing diagnostics here, -Wconversion and -Wsign-compare.
13003 bool IsListInit/*= false*/) {
13005 WorkList.push_back({OrigE, CC, IsListInit});
13006 while (!WorkList.empty())
13007 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13008}
13009
13010// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13011// Returns true when emitting a warning about taking the address of a reference.
13012static bool CheckForReference(Sema &SemaRef, const Expr *E,
13013 const PartialDiagnostic &PD) {
13014 E = E->IgnoreParenImpCasts();
13015
13016 const FunctionDecl *FD = nullptr;
13017
13018 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13019 if (!DRE->getDecl()->getType()->isReferenceType())
13020 return false;
13021 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13022 if (!M->getMemberDecl()->getType()->isReferenceType())
13023 return false;
13024 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13025 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13026 return false;
13027 FD = Call->getDirectCallee();
13028 } else {
13029 return false;
13030 }
13031
13032 SemaRef.Diag(E->getExprLoc(), PD);
13033
13034 // If possible, point to location of function.
13035 if (FD) {
13036 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13037 }
13038
13039 return true;
13040}
13041
13042// Returns true if the SourceLocation is expanded from any macro body.
13043// Returns false if the SourceLocation is invalid, is from not in a macro
13044// expansion, or is from expanded from a top-level macro argument.
13046 if (Loc.isInvalid())
13047 return false;
13048
13049 while (Loc.isMacroID()) {
13050 if (SM.isMacroBodyExpansion(Loc))
13051 return true;
13052 Loc = SM.getImmediateMacroCallerLoc(Loc);
13053 }
13054
13055 return false;
13056}
13057
13060 bool IsEqual, SourceRange Range) {
13061 if (!E)
13062 return;
13063
13064 // Don't warn inside macros.
13065 if (E->getExprLoc().isMacroID()) {
13067 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13069 return;
13070 }
13071 E = E->IgnoreImpCasts();
13072
13073 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13074
13075 if (isa<CXXThisExpr>(E)) {
13076 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13077 : diag::warn_this_bool_conversion;
13078 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13079 return;
13080 }
13081
13082 bool IsAddressOf = false;
13083
13084 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
13085 if (UO->getOpcode() != UO_AddrOf)
13086 return;
13087 IsAddressOf = true;
13088 E = UO->getSubExpr();
13089 }
13090
13091 if (IsAddressOf) {
13092 unsigned DiagID = IsCompare
13093 ? diag::warn_address_of_reference_null_compare
13094 : diag::warn_address_of_reference_bool_conversion;
13095 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13096 << IsEqual;
13097 if (CheckForReference(*this, E, PD)) {
13098 return;
13099 }
13100 }
13101
13102 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13103 bool IsParam = isa<NonNullAttr>(NonnullAttr);
13104 std::string Str;
13105 llvm::raw_string_ostream S(Str);
13106 E->printPretty(S, nullptr, getPrintingPolicy());
13107 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13108 : diag::warn_cast_nonnull_to_bool;
13109 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13110 << E->getSourceRange() << Range << IsEqual;
13111 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13112 };
13113
13114 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13115 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13116 if (auto *Callee = Call->getDirectCallee()) {
13117 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13118 ComplainAboutNonnullParamOrCall(A);
13119 return;
13120 }
13121 }
13122 }
13123
13124 // Complain if we are converting a lambda expression to a boolean value
13125 // outside of instantiation.
13126 if (!inTemplateInstantiation()) {
13127 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
13128 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
13129 MRecordDecl && MRecordDecl->isLambda()) {
13130 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
13131 << /*LambdaPointerConversionOperatorType=*/3
13132 << MRecordDecl->getSourceRange() << Range << IsEqual;
13133 return;
13134 }
13135 }
13136 }
13137
13138 // Expect to find a single Decl. Skip anything more complicated.
13139 ValueDecl *D = nullptr;
13140 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13141 D = R->getDecl();
13142 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13143 D = M->getMemberDecl();
13144 }
13145
13146 // Weak Decls can be null.
13147 if (!D || D->isWeak())
13148 return;
13149
13150 // Check for parameter decl with nonnull attribute
13151 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13152 if (getCurFunction() &&
13153 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13154 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13155 ComplainAboutNonnullParamOrCall(A);
13156 return;
13157 }
13158
13159 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13160 // Skip function template not specialized yet.
13162 return;
13163 auto ParamIter = llvm::find(FD->parameters(), PV);
13164 assert(ParamIter != FD->param_end());
13165 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13166
13167 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13168 if (!NonNull->args_size()) {
13169 ComplainAboutNonnullParamOrCall(NonNull);
13170 return;
13171 }
13172
13173 for (const ParamIdx &ArgNo : NonNull->args()) {
13174 if (ArgNo.getASTIndex() == ParamNo) {
13175 ComplainAboutNonnullParamOrCall(NonNull);
13176 return;
13177 }
13178 }
13179 }
13180 }
13181 }
13182 }
13183
13184 QualType T = D->getType();
13185 const bool IsArray = T->isArrayType();
13186 const bool IsFunction = T->isFunctionType();
13187
13188 // Address of function is used to silence the function warning.
13189 if (IsAddressOf && IsFunction) {
13190 return;
13191 }
13192
13193 // Found nothing.
13194 if (!IsAddressOf && !IsFunction && !IsArray)
13195 return;
13196
13197 // Pretty print the expression for the diagnostic.
13198 std::string Str;
13199 llvm::raw_string_ostream S(Str);
13200 E->printPretty(S, nullptr, getPrintingPolicy());
13201
13202 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13203 : diag::warn_impcast_pointer_to_bool;
13204 enum {
13205 AddressOf,
13206 FunctionPointer,
13207 ArrayPointer
13208 } DiagType;
13209 if (IsAddressOf)
13210 DiagType = AddressOf;
13211 else if (IsFunction)
13212 DiagType = FunctionPointer;
13213 else if (IsArray)
13214 DiagType = ArrayPointer;
13215 else
13216 llvm_unreachable("Could not determine diagnostic.");
13217 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13218 << Range << IsEqual;
13219
13220 if (!IsFunction)
13221 return;
13222
13223 // Suggest '&' to silence the function warning.
13224 Diag(E->getExprLoc(), diag::note_function_warning_silence)
13226
13227 // Check to see if '()' fixit should be emitted.
13228 QualType ReturnType;
13229 UnresolvedSet<4> NonTemplateOverloads;
13230 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13231 if (ReturnType.isNull())
13232 return;
13233
13234 if (IsCompare) {
13235 // There are two cases here. If there is null constant, the only suggest
13236 // for a pointer return type. If the null is 0, then suggest if the return
13237 // type is a pointer or an integer type.
13238 if (!ReturnType->isPointerType()) {
13239 if (NullKind == Expr::NPCK_ZeroExpression ||
13240 NullKind == Expr::NPCK_ZeroLiteral) {
13241 if (!ReturnType->isIntegerType())
13242 return;
13243 } else {
13244 return;
13245 }
13246 }
13247 } else { // !IsCompare
13248 // For function to bool, only suggest if the function pointer has bool
13249 // return type.
13250 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13251 return;
13252 }
13253 Diag(E->getExprLoc(), diag::note_function_to_function_call)
13255}
13256
13257void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13258 // Don't diagnose in unevaluated contexts.
13260 return;
13261
13262 // Don't diagnose for value- or type-dependent expressions.
13263 if (E->isTypeDependent() || E->isValueDependent())
13264 return;
13265
13266 // Check for array bounds violations in cases where the check isn't triggered
13267 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13268 // ArraySubscriptExpr is on the RHS of a variable initialization.
13269 CheckArrayAccess(E);
13270
13271 // This is not the right CC for (e.g.) a variable initialization.
13272 AnalyzeImplicitConversions(*this, E, CC);
13273}
13274
13275void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13276 ::CheckBoolLikeConversion(*this, E, CC);
13277}
13278
13279void Sema::CheckForIntOverflow (const Expr *E) {
13280 // Use a work list to deal with nested struct initializers.
13282
13283 do {
13284 const Expr *OriginalE = Exprs.pop_back_val();
13285 const Expr *E = OriginalE->IgnoreParenCasts();
13286
13287 if (isa<BinaryOperator, UnaryOperator>(E)) {
13289 continue;
13290 }
13291
13292 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
13293 Exprs.append(InitList->inits().begin(), InitList->inits().end());
13294 else if (isa<ObjCBoxedExpr>(OriginalE))
13296 else if (const auto *Call = dyn_cast<CallExpr>(E))
13297 Exprs.append(Call->arg_begin(), Call->arg_end());
13298 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
13299 Exprs.append(Message->arg_begin(), Message->arg_end());
13300 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
13301 Exprs.append(Construct->arg_begin(), Construct->arg_end());
13302 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
13303 Exprs.push_back(Temporary->getSubExpr());
13304 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
13305 Exprs.push_back(Array->getIdx());
13306 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
13307 Exprs.push_back(Compound->getInitializer());
13308 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
13309 New && New->isArray()) {
13310 if (auto ArraySize = New->getArraySize())
13311 Exprs.push_back(*ArraySize);
13312 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
13313 Exprs.push_back(MTE->getSubExpr());
13314 } while (!Exprs.empty());
13315}
13316
13317namespace {
13318
13319/// Visitor for expressions which looks for unsequenced operations on the
13320/// same object.
13321class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13323
13324 /// A tree of sequenced regions within an expression. Two regions are
13325 /// unsequenced if one is an ancestor or a descendent of the other. When we
13326 /// finish processing an expression with sequencing, such as a comma
13327 /// expression, we fold its tree nodes into its parent, since they are
13328 /// unsequenced with respect to nodes we will visit later.
13329 class SequenceTree {
13330 struct Value {
13331 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13332 unsigned Parent : 31;
13333 LLVM_PREFERRED_TYPE(bool)
13334 unsigned Merged : 1;
13335 };
13336 SmallVector<Value, 8> Values;
13337
13338 public:
13339 /// A region within an expression which may be sequenced with respect
13340 /// to some other region.
13341 class Seq {
13342 friend class SequenceTree;
13343
13344 unsigned Index;
13345
13346 explicit Seq(unsigned N) : Index(N) {}
13347
13348 public:
13349 Seq() : Index(0) {}
13350 };
13351
13352 SequenceTree() { Values.push_back(Value(0)); }
13353 Seq root() const { return Seq(0); }
13354
13355 /// Create a new sequence of operations, which is an unsequenced
13356 /// subset of \p Parent. This sequence of operations is sequenced with
13357 /// respect to other children of \p Parent.
13358 Seq allocate(Seq Parent) {
13359 Values.push_back(Value(Parent.Index));
13360 return Seq(Values.size() - 1);
13361 }
13362
13363 /// Merge a sequence of operations into its parent.
13364 void merge(Seq S) {
13365 Values[S.Index].Merged = true;
13366 }
13367
13368 /// Determine whether two operations are unsequenced. This operation
13369 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13370 /// should have been merged into its parent as appropriate.
13371 bool isUnsequenced(Seq Cur, Seq Old) {
13372 unsigned C = representative(Cur.Index);
13373 unsigned Target = representative(Old.Index);
13374 while (C >= Target) {
13375 if (C == Target)
13376 return true;
13377 C = Values[C].Parent;
13378 }
13379 return false;
13380 }
13381
13382 private:
13383 /// Pick a representative for a sequence.
13384 unsigned representative(unsigned K) {
13385 if (Values[K].Merged)
13386 // Perform path compression as we go.
13387 return Values[K].Parent = representative(Values[K].Parent);
13388 return K;
13389 }
13390 };
13391
13392 /// An object for which we can track unsequenced uses.
13393 using Object = const NamedDecl *;
13394
13395 /// Different flavors of object usage which we track. We only track the
13396 /// least-sequenced usage of each kind.
13397 enum UsageKind {
13398 /// A read of an object. Multiple unsequenced reads are OK.
13399 UK_Use,
13400
13401 /// A modification of an object which is sequenced before the value
13402 /// computation of the expression, such as ++n in C++.
13403 UK_ModAsValue,
13404
13405 /// A modification of an object which is not sequenced before the value
13406 /// computation of the expression, such as n++.
13407 UK_ModAsSideEffect,
13408
13409 UK_Count = UK_ModAsSideEffect + 1
13410 };
13411
13412 /// Bundle together a sequencing region and the expression corresponding
13413 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13414 struct Usage {
13415 const Expr *UsageExpr = nullptr;
13416 SequenceTree::Seq Seq;
13417
13418 Usage() = default;
13419 };
13420
13421 struct UsageInfo {
13422 Usage Uses[UK_Count];
13423
13424 /// Have we issued a diagnostic for this object already?
13425 bool Diagnosed = false;
13426
13427 UsageInfo();
13428 };
13429 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13430
13431 Sema &SemaRef;
13432
13433 /// Sequenced regions within the expression.
13434 SequenceTree Tree;
13435
13436 /// Declaration modifications and references which we have seen.
13437 UsageInfoMap UsageMap;
13438
13439 /// The region we are currently within.
13440 SequenceTree::Seq Region;
13441
13442 /// Filled in with declarations which were modified as a side-effect
13443 /// (that is, post-increment operations).
13444 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13445
13446 /// Expressions to check later. We defer checking these to reduce
13447 /// stack usage.
13449
13450 /// RAII object wrapping the visitation of a sequenced subexpression of an
13451 /// expression. At the end of this process, the side-effects of the evaluation
13452 /// become sequenced with respect to the value computation of the result, so
13453 /// we downgrade any UK_ModAsSideEffect within the evaluation to
13454 /// UK_ModAsValue.
13455 struct SequencedSubexpression {
13456 SequencedSubexpression(SequenceChecker &Self)
13457 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13458 Self.ModAsSideEffect = &ModAsSideEffect;
13459 }
13460
13461 ~SequencedSubexpression() {
13462 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13463 // Add a new usage with usage kind UK_ModAsValue, and then restore
13464 // the previous usage with UK_ModAsSideEffect (thus clearing it if
13465 // the previous one was empty).
13466 UsageInfo &UI = Self.UsageMap[M.first];
13467 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13468 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13469 SideEffectUsage = M.second;
13470 }
13471 Self.ModAsSideEffect = OldModAsSideEffect;
13472 }
13473
13474 SequenceChecker &Self;
13475 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13476 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13477 };
13478
13479 /// RAII object wrapping the visitation of a subexpression which we might
13480 /// choose to evaluate as a constant. If any subexpression is evaluated and
13481 /// found to be non-constant, this allows us to suppress the evaluation of
13482 /// the outer expression.
13483 class EvaluationTracker {
13484 public:
13485 EvaluationTracker(SequenceChecker &Self)
13486 : Self(Self), Prev(Self.EvalTracker) {
13487 Self.EvalTracker = this;
13488 }
13489
13490 ~EvaluationTracker() {
13491 Self.EvalTracker = Prev;
13492 if (Prev)
13493 Prev->EvalOK &= EvalOK;
13494 }
13495
13496 bool evaluate(const Expr *E, bool &Result) {
13497 if (!EvalOK || E->isValueDependent())
13498 return false;
13499 EvalOK = E->EvaluateAsBooleanCondition(
13500 Result, Self.SemaRef.Context,
13501 Self.SemaRef.isConstantEvaluatedContext());
13502 return EvalOK;
13503 }
13504
13505 private:
13506 SequenceChecker &Self;
13507 EvaluationTracker *Prev;
13508 bool EvalOK = true;
13509 } *EvalTracker = nullptr;
13510
13511 /// Find the object which is produced by the specified expression,
13512 /// if any.
13513 Object getObject(const Expr *E, bool Mod) const {
13514 E = E->IgnoreParenCasts();
13515 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13516 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13517 return getObject(UO->getSubExpr(), Mod);
13518 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13519 if (BO->getOpcode() == BO_Comma)
13520 return getObject(BO->getRHS(), Mod);
13521 if (Mod && BO->isAssignmentOp())
13522 return getObject(BO->getLHS(), Mod);
13523 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13524 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13525 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13526 return ME->getMemberDecl();
13527 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13528 // FIXME: If this is a reference, map through to its value.
13529 return DRE->getDecl();
13530 return nullptr;
13531 }
13532
13533 /// Note that an object \p O was modified or used by an expression
13534 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13535 /// the object \p O as obtained via the \p UsageMap.
13536 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13537 // Get the old usage for the given object and usage kind.
13538 Usage &U = UI.Uses[UK];
13539 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13540 // If we have a modification as side effect and are in a sequenced
13541 // subexpression, save the old Usage so that we can restore it later
13542 // in SequencedSubexpression::~SequencedSubexpression.
13543 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13544 ModAsSideEffect->push_back(std::make_pair(O, U));
13545 // Then record the new usage with the current sequencing region.
13546 U.UsageExpr = UsageExpr;
13547 U.Seq = Region;
13548 }
13549 }
13550
13551 /// Check whether a modification or use of an object \p O in an expression
13552 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13553 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13554 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13555 /// usage and false we are checking for a mod-use unsequenced usage.
13556 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13557 UsageKind OtherKind, bool IsModMod) {
13558 if (UI.Diagnosed)
13559 return;
13560
13561 const Usage &U = UI.Uses[OtherKind];
13562 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13563 return;
13564
13565 const Expr *Mod = U.UsageExpr;
13566 const Expr *ModOrUse = UsageExpr;
13567 if (OtherKind == UK_Use)
13568 std::swap(Mod, ModOrUse);
13569
13570 SemaRef.DiagRuntimeBehavior(
13571 Mod->getExprLoc(), {Mod, ModOrUse},
13572 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13573 : diag::warn_unsequenced_mod_use)
13574 << O << SourceRange(ModOrUse->getExprLoc()));
13575 UI.Diagnosed = true;
13576 }
13577
13578 // A note on note{Pre, Post}{Use, Mod}:
13579 //
13580 // (It helps to follow the algorithm with an expression such as
13581 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13582 // operations before C++17 and both are well-defined in C++17).
13583 //
13584 // When visiting a node which uses/modify an object we first call notePreUse
13585 // or notePreMod before visiting its sub-expression(s). At this point the
13586 // children of the current node have not yet been visited and so the eventual
13587 // uses/modifications resulting from the children of the current node have not
13588 // been recorded yet.
13589 //
13590 // We then visit the children of the current node. After that notePostUse or
13591 // notePostMod is called. These will 1) detect an unsequenced modification
13592 // as side effect (as in "k++ + k") and 2) add a new usage with the
13593 // appropriate usage kind.
13594 //
13595 // We also have to be careful that some operation sequences modification as
13596 // side effect as well (for example: || or ,). To account for this we wrap
13597 // the visitation of such a sub-expression (for example: the LHS of || or ,)
13598 // with SequencedSubexpression. SequencedSubexpression is an RAII object
13599 // which record usages which are modifications as side effect, and then
13600 // downgrade them (or more accurately restore the previous usage which was a
13601 // modification as side effect) when exiting the scope of the sequenced
13602 // subexpression.
13603
13604 void notePreUse(Object O, const Expr *UseExpr) {
13605 UsageInfo &UI = UsageMap[O];
13606 // Uses conflict with other modifications.
13607 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13608 }
13609
13610 void notePostUse(Object O, const Expr *UseExpr) {
13611 UsageInfo &UI = UsageMap[O];
13612 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13613 /*IsModMod=*/false);
13614 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13615 }
13616
13617 void notePreMod(Object O, const Expr *ModExpr) {
13618 UsageInfo &UI = UsageMap[O];
13619 // Modifications conflict with other modifications and with uses.
13620 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13621 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13622 }
13623
13624 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13625 UsageInfo &UI = UsageMap[O];
13626 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13627 /*IsModMod=*/true);
13628 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13629 }
13630
13631public:
13632 SequenceChecker(Sema &S, const Expr *E,
13634 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13635 Visit(E);
13636 // Silence a -Wunused-private-field since WorkList is now unused.
13637 // TODO: Evaluate if it can be used, and if not remove it.
13638 (void)this->WorkList;
13639 }
13640
13641 void VisitStmt(const Stmt *S) {
13642 // Skip all statements which aren't expressions for now.
13643 }
13644
13645 void VisitExpr(const Expr *E) {
13646 // By default, just recurse to evaluated subexpressions.
13647 Base::VisitStmt(E);
13648 }
13649
13650 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
13651 for (auto *Sub : CSE->children()) {
13652 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
13653 if (!ChildExpr)
13654 continue;
13655
13656 if (ChildExpr == CSE->getOperand())
13657 // Do not recurse over a CoroutineSuspendExpr's operand.
13658 // The operand is also a subexpression of getCommonExpr(), and
13659 // recursing into it directly could confuse object management
13660 // for the sake of sequence tracking.
13661 continue;
13662
13663 Visit(Sub);
13664 }
13665 }
13666
13667 void VisitCastExpr(const CastExpr *E) {
13668 Object O = Object();
13669 if (E->getCastKind() == CK_LValueToRValue)
13670 O = getObject(E->getSubExpr(), false);
13671
13672 if (O)
13673 notePreUse(O, E);
13674 VisitExpr(E);
13675 if (O)
13676 notePostUse(O, E);
13677 }
13678
13679 void VisitSequencedExpressions(const Expr *SequencedBefore,
13680 const Expr *SequencedAfter) {
13681 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13682 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13683 SequenceTree::Seq OldRegion = Region;
13684
13685 {
13686 SequencedSubexpression SeqBefore(*this);
13687 Region = BeforeRegion;
13688 Visit(SequencedBefore);
13689 }
13690
13691 Region = AfterRegion;
13692 Visit(SequencedAfter);
13693
13694 Region = OldRegion;
13695
13696 Tree.merge(BeforeRegion);
13697 Tree.merge(AfterRegion);
13698 }
13699
13700 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13701 // C++17 [expr.sub]p1:
13702 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13703 // expression E1 is sequenced before the expression E2.
13704 if (SemaRef.getLangOpts().CPlusPlus17)
13705 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13706 else {
13707 Visit(ASE->getLHS());
13708 Visit(ASE->getRHS());
13709 }
13710 }
13711
13712 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13713 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13714 void VisitBinPtrMem(const BinaryOperator *BO) {
13715 // C++17 [expr.mptr.oper]p4:
13716 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13717 // the expression E1 is sequenced before the expression E2.
13718 if (SemaRef.getLangOpts().CPlusPlus17)
13719 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13720 else {
13721 Visit(BO->getLHS());
13722 Visit(BO->getRHS());
13723 }
13724 }
13725
13726 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13727 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13728 void VisitBinShlShr(const BinaryOperator *BO) {
13729 // C++17 [expr.shift]p4:
13730 // The expression E1 is sequenced before the expression E2.
13731 if (SemaRef.getLangOpts().CPlusPlus17)
13732 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13733 else {
13734 Visit(BO->getLHS());
13735 Visit(BO->getRHS());
13736 }
13737 }
13738
13739 void VisitBinComma(const BinaryOperator *BO) {
13740 // C++11 [expr.comma]p1:
13741 // Every value computation and side effect associated with the left
13742 // expression is sequenced before every value computation and side
13743 // effect associated with the right expression.
13744 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13745 }
13746
13747 void VisitBinAssign(const BinaryOperator *BO) {
13748 SequenceTree::Seq RHSRegion;
13749 SequenceTree::Seq LHSRegion;
13750 if (SemaRef.getLangOpts().CPlusPlus17) {
13751 RHSRegion = Tree.allocate(Region);
13752 LHSRegion = Tree.allocate(Region);
13753 } else {
13754 RHSRegion = Region;
13755 LHSRegion = Region;
13756 }
13757 SequenceTree::Seq OldRegion = Region;
13758
13759 // C++11 [expr.ass]p1:
13760 // [...] the assignment is sequenced after the value computation
13761 // of the right and left operands, [...]
13762 //
13763 // so check it before inspecting the operands and update the
13764 // map afterwards.
13765 Object O = getObject(BO->getLHS(), /*Mod=*/true);
13766 if (O)
13767 notePreMod(O, BO);
13768
13769 if (SemaRef.getLangOpts().CPlusPlus17) {
13770 // C++17 [expr.ass]p1:
13771 // [...] The right operand is sequenced before the left operand. [...]
13772 {
13773 SequencedSubexpression SeqBefore(*this);
13774 Region = RHSRegion;
13775 Visit(BO->getRHS());
13776 }
13777
13778 Region = LHSRegion;
13779 Visit(BO->getLHS());
13780
13781 if (O && isa<CompoundAssignOperator>(BO))
13782 notePostUse(O, BO);
13783
13784 } else {
13785 // C++11 does not specify any sequencing between the LHS and RHS.
13786 Region = LHSRegion;
13787 Visit(BO->getLHS());
13788
13789 if (O && isa<CompoundAssignOperator>(BO))
13790 notePostUse(O, BO);
13791
13792 Region = RHSRegion;
13793 Visit(BO->getRHS());
13794 }
13795
13796 // C++11 [expr.ass]p1:
13797 // the assignment is sequenced [...] before the value computation of the
13798 // assignment expression.
13799 // C11 6.5.16/3 has no such rule.
13800 Region = OldRegion;
13801 if (O)
13802 notePostMod(O, BO,
13803 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13804 : UK_ModAsSideEffect);
13805 if (SemaRef.getLangOpts().CPlusPlus17) {
13806 Tree.merge(RHSRegion);
13807 Tree.merge(LHSRegion);
13808 }
13809 }
13810
13811 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13812 VisitBinAssign(CAO);
13813 }
13814
13815 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13816 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13817 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13818 Object O = getObject(UO->getSubExpr(), true);
13819 if (!O)
13820 return VisitExpr(UO);
13821
13822 notePreMod(O, UO);
13823 Visit(UO->getSubExpr());
13824 // C++11 [expr.pre.incr]p1:
13825 // the expression ++x is equivalent to x+=1
13826 notePostMod(O, UO,
13827 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13828 : UK_ModAsSideEffect);
13829 }
13830
13831 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13832 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13833 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13834 Object O = getObject(UO->getSubExpr(), true);
13835 if (!O)
13836 return VisitExpr(UO);
13837
13838 notePreMod(O, UO);
13839 Visit(UO->getSubExpr());
13840 notePostMod(O, UO, UK_ModAsSideEffect);
13841 }
13842
13843 void VisitBinLOr(const BinaryOperator *BO) {
13844 // C++11 [expr.log.or]p2:
13845 // If the second expression is evaluated, every value computation and
13846 // side effect associated with the first expression is sequenced before
13847 // every value computation and side effect associated with the
13848 // second expression.
13849 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13850 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13851 SequenceTree::Seq OldRegion = Region;
13852
13853 EvaluationTracker Eval(*this);
13854 {
13855 SequencedSubexpression Sequenced(*this);
13856 Region = LHSRegion;
13857 Visit(BO->getLHS());
13858 }
13859
13860 // C++11 [expr.log.or]p1:
13861 // [...] the second operand is not evaluated if the first operand
13862 // evaluates to true.
13863 bool EvalResult = false;
13864 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13865 bool ShouldVisitRHS = !EvalOK || !EvalResult;
13866 if (ShouldVisitRHS) {
13867 Region = RHSRegion;
13868 Visit(BO->getRHS());
13869 }
13870
13871 Region = OldRegion;
13872 Tree.merge(LHSRegion);
13873 Tree.merge(RHSRegion);
13874 }
13875
13876 void VisitBinLAnd(const BinaryOperator *BO) {
13877 // C++11 [expr.log.and]p2:
13878 // If the second expression is evaluated, every value computation and
13879 // side effect associated with the first expression is sequenced before
13880 // every value computation and side effect associated with the
13881 // second expression.
13882 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13883 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13884 SequenceTree::Seq OldRegion = Region;
13885
13886 EvaluationTracker Eval(*this);
13887 {
13888 SequencedSubexpression Sequenced(*this);
13889 Region = LHSRegion;
13890 Visit(BO->getLHS());
13891 }
13892
13893 // C++11 [expr.log.and]p1:
13894 // [...] the second operand is not evaluated if the first operand is false.
13895 bool EvalResult = false;
13896 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13897 bool ShouldVisitRHS = !EvalOK || EvalResult;
13898 if (ShouldVisitRHS) {
13899 Region = RHSRegion;
13900 Visit(BO->getRHS());
13901 }
13902
13903 Region = OldRegion;
13904 Tree.merge(LHSRegion);
13905 Tree.merge(RHSRegion);
13906 }
13907
13908 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13909 // C++11 [expr.cond]p1:
13910 // [...] Every value computation and side effect associated with the first
13911 // expression is sequenced before every value computation and side effect
13912 // associated with the second or third expression.
13913 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13914
13915 // No sequencing is specified between the true and false expression.
13916 // However since exactly one of both is going to be evaluated we can
13917 // consider them to be sequenced. This is needed to avoid warning on
13918 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13919 // both the true and false expressions because we can't evaluate x.
13920 // This will still allow us to detect an expression like (pre C++17)
13921 // "(x ? y += 1 : y += 2) = y".
13922 //
13923 // We don't wrap the visitation of the true and false expression with
13924 // SequencedSubexpression because we don't want to downgrade modifications
13925 // as side effect in the true and false expressions after the visition
13926 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13927 // not warn between the two "y++", but we should warn between the "y++"
13928 // and the "y".
13929 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13930 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13931 SequenceTree::Seq OldRegion = Region;
13932
13933 EvaluationTracker Eval(*this);
13934 {
13935 SequencedSubexpression Sequenced(*this);
13936 Region = ConditionRegion;
13937 Visit(CO->getCond());
13938 }
13939
13940 // C++11 [expr.cond]p1:
13941 // [...] The first expression is contextually converted to bool (Clause 4).
13942 // It is evaluated and if it is true, the result of the conditional
13943 // expression is the value of the second expression, otherwise that of the
13944 // third expression. Only one of the second and third expressions is
13945 // evaluated. [...]
13946 bool EvalResult = false;
13947 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13948 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
13949 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
13950 if (ShouldVisitTrueExpr) {
13951 Region = TrueRegion;
13952 Visit(CO->getTrueExpr());
13953 }
13954 if (ShouldVisitFalseExpr) {
13955 Region = FalseRegion;
13956 Visit(CO->getFalseExpr());
13957 }
13958
13959 Region = OldRegion;
13960 Tree.merge(ConditionRegion);
13961 Tree.merge(TrueRegion);
13962 Tree.merge(FalseRegion);
13963 }
13964
13965 void VisitCallExpr(const CallExpr *CE) {
13966 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13967
13968 if (CE->isUnevaluatedBuiltinCall(Context))
13969 return;
13970
13971 // C++11 [intro.execution]p15:
13972 // When calling a function [...], every value computation and side effect
13973 // associated with any argument expression, or with the postfix expression
13974 // designating the called function, is sequenced before execution of every
13975 // expression or statement in the body of the function [and thus before
13976 // the value computation of its result].
13977 SequencedSubexpression Sequenced(*this);
13978 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
13979 // C++17 [expr.call]p5
13980 // The postfix-expression is sequenced before each expression in the
13981 // expression-list and any default argument. [...]
13982 SequenceTree::Seq CalleeRegion;
13983 SequenceTree::Seq OtherRegion;
13984 if (SemaRef.getLangOpts().CPlusPlus17) {
13985 CalleeRegion = Tree.allocate(Region);
13986 OtherRegion = Tree.allocate(Region);
13987 } else {
13988 CalleeRegion = Region;
13989 OtherRegion = Region;
13990 }
13991 SequenceTree::Seq OldRegion = Region;
13992
13993 // Visit the callee expression first.
13994 Region = CalleeRegion;
13995 if (SemaRef.getLangOpts().CPlusPlus17) {
13996 SequencedSubexpression Sequenced(*this);
13997 Visit(CE->getCallee());
13998 } else {
13999 Visit(CE->getCallee());
14000 }
14001
14002 // Then visit the argument expressions.
14003 Region = OtherRegion;
14004 for (const Expr *Argument : CE->arguments())
14005 Visit(Argument);
14006
14007 Region = OldRegion;
14008 if (SemaRef.getLangOpts().CPlusPlus17) {
14009 Tree.merge(CalleeRegion);
14010 Tree.merge(OtherRegion);
14011 }
14012 });
14013 }
14014
14015 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14016 // C++17 [over.match.oper]p2:
14017 // [...] the operator notation is first transformed to the equivalent
14018 // function-call notation as summarized in Table 12 (where @ denotes one
14019 // of the operators covered in the specified subclause). However, the
14020 // operands are sequenced in the order prescribed for the built-in
14021 // operator (Clause 8).
14022 //
14023 // From the above only overloaded binary operators and overloaded call
14024 // operators have sequencing rules in C++17 that we need to handle
14025 // separately.
14026 if (!SemaRef.getLangOpts().CPlusPlus17 ||
14027 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14028 return VisitCallExpr(CXXOCE);
14029
14030 enum {
14031 NoSequencing,
14032 LHSBeforeRHS,
14033 RHSBeforeLHS,
14034 LHSBeforeRest
14035 } SequencingKind;
14036 switch (CXXOCE->getOperator()) {
14037 case OO_Equal:
14038 case OO_PlusEqual:
14039 case OO_MinusEqual:
14040 case OO_StarEqual:
14041 case OO_SlashEqual:
14042 case OO_PercentEqual:
14043 case OO_CaretEqual:
14044 case OO_AmpEqual:
14045 case OO_PipeEqual:
14046 case OO_LessLessEqual:
14047 case OO_GreaterGreaterEqual:
14048 SequencingKind = RHSBeforeLHS;
14049 break;
14050
14051 case OO_LessLess:
14052 case OO_GreaterGreater:
14053 case OO_AmpAmp:
14054 case OO_PipePipe:
14055 case OO_Comma:
14056 case OO_ArrowStar:
14057 case OO_Subscript:
14058 SequencingKind = LHSBeforeRHS;
14059 break;
14060
14061 case OO_Call:
14062 SequencingKind = LHSBeforeRest;
14063 break;
14064
14065 default:
14066 SequencingKind = NoSequencing;
14067 break;
14068 }
14069
14070 if (SequencingKind == NoSequencing)
14071 return VisitCallExpr(CXXOCE);
14072
14073 // This is a call, so all subexpressions are sequenced before the result.
14074 SequencedSubexpression Sequenced(*this);
14075
14076 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14077 assert(SemaRef.getLangOpts().CPlusPlus17 &&
14078 "Should only get there with C++17 and above!");
14079 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14080 "Should only get there with an overloaded binary operator"
14081 " or an overloaded call operator!");
14082
14083 if (SequencingKind == LHSBeforeRest) {
14084 assert(CXXOCE->getOperator() == OO_Call &&
14085 "We should only have an overloaded call operator here!");
14086
14087 // This is very similar to VisitCallExpr, except that we only have the
14088 // C++17 case. The postfix-expression is the first argument of the
14089 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14090 // are in the following arguments.
14091 //
14092 // Note that we intentionally do not visit the callee expression since
14093 // it is just a decayed reference to a function.
14094 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14095 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14096 SequenceTree::Seq OldRegion = Region;
14097
14098 assert(CXXOCE->getNumArgs() >= 1 &&
14099 "An overloaded call operator must have at least one argument"
14100 " for the postfix-expression!");
14101 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14102 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14103 CXXOCE->getNumArgs() - 1);
14104
14105 // Visit the postfix-expression first.
14106 {
14107 Region = PostfixExprRegion;
14108 SequencedSubexpression Sequenced(*this);
14109 Visit(PostfixExpr);
14110 }
14111
14112 // Then visit the argument expressions.
14113 Region = ArgsRegion;
14114 for (const Expr *Arg : Args)
14115 Visit(Arg);
14116
14117 Region = OldRegion;
14118 Tree.merge(PostfixExprRegion);
14119 Tree.merge(ArgsRegion);
14120 } else {
14121 assert(CXXOCE->getNumArgs() == 2 &&
14122 "Should only have two arguments here!");
14123 assert((SequencingKind == LHSBeforeRHS ||
14124 SequencingKind == RHSBeforeLHS) &&
14125 "Unexpected sequencing kind!");
14126
14127 // We do not visit the callee expression since it is just a decayed
14128 // reference to a function.
14129 const Expr *E1 = CXXOCE->getArg(0);
14130 const Expr *E2 = CXXOCE->getArg(1);
14131 if (SequencingKind == RHSBeforeLHS)
14132 std::swap(E1, E2);
14133
14134 return VisitSequencedExpressions(E1, E2);
14135 }
14136 });
14137 }
14138
14139 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14140 // This is a call, so all subexpressions are sequenced before the result.
14141 SequencedSubexpression Sequenced(*this);
14142
14143 if (!CCE->isListInitialization())
14144 return VisitExpr(CCE);
14145
14146 // In C++11, list initializations are sequenced.
14147 SequenceExpressionsInOrder(
14148 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
14149 }
14150
14151 void VisitInitListExpr(const InitListExpr *ILE) {
14152 if (!SemaRef.getLangOpts().CPlusPlus11)
14153 return VisitExpr(ILE);
14154
14155 // In C++11, list initializations are sequenced.
14156 SequenceExpressionsInOrder(ILE->inits());
14157 }
14158
14159 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
14160 // C++20 parenthesized list initializations are sequenced. See C++20
14161 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
14162 SequenceExpressionsInOrder(PLIE->getInitExprs());
14163 }
14164
14165private:
14166 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
14168 SequenceTree::Seq Parent = Region;
14169 for (const Expr *E : ExpressionList) {
14170 if (!E)
14171 continue;
14172 Region = Tree.allocate(Parent);
14173 Elts.push_back(Region);
14174 Visit(E);
14175 }
14176
14177 // Forget that the initializers are sequenced.
14178 Region = Parent;
14179 for (unsigned I = 0; I < Elts.size(); ++I)
14180 Tree.merge(Elts[I]);
14181 }
14182};
14183
14184SequenceChecker::UsageInfo::UsageInfo() = default;
14185
14186} // namespace
14187
14188void Sema::CheckUnsequencedOperations(const Expr *E) {
14190 WorkList.push_back(E);
14191 while (!WorkList.empty()) {
14192 const Expr *Item = WorkList.pop_back_val();
14193 SequenceChecker(*this, Item, WorkList);
14194 }
14195}
14196
14197void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14198 bool IsConstexpr) {
14200 IsConstexpr || isa<ConstantExpr>(E));
14201 CheckImplicitConversions(E, CheckLoc);
14203 CheckUnsequencedOperations(E);
14204 if (!IsConstexpr && !E->isValueDependent())
14205 CheckForIntOverflow(E);
14206}
14207
14208void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14209 FieldDecl *BitField,
14210 Expr *Init) {
14211 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14212}
14213
14216 if (!PType->isVariablyModifiedType())
14217 return;
14218 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14219 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14220 return;
14221 }
14222 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14223 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14224 return;
14225 }
14226 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14227 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14228 return;
14229 }
14230
14231 const ArrayType *AT = S.Context.getAsArrayType(PType);
14232 if (!AT)
14233 return;
14234
14237 return;
14238 }
14239
14240 S.Diag(Loc, diag::err_array_star_in_function_definition);
14241}
14242
14244 bool CheckParameterNames) {
14245 bool HasInvalidParm = false;
14246 for (ParmVarDecl *Param : Parameters) {
14247 assert(Param && "null in a parameter list");
14248 // C99 6.7.5.3p4: the parameters in a parameter type list in a
14249 // function declarator that is part of a function definition of
14250 // that function shall not have incomplete type.
14251 //
14252 // C++23 [dcl.fct.def.general]/p2
14253 // The type of a parameter [...] for a function definition
14254 // shall not be a (possibly cv-qualified) class type that is incomplete
14255 // or abstract within the function body unless the function is deleted.
14256 if (!Param->isInvalidDecl() &&
14257 (RequireCompleteType(Param->getLocation(), Param->getType(),
14258 diag::err_typecheck_decl_incomplete_type) ||
14259 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
14260 diag::err_abstract_type_in_decl,
14262 Param->setInvalidDecl();
14263 HasInvalidParm = true;
14264 }
14265
14266 // C99 6.9.1p5: If the declarator includes a parameter type list, the
14267 // declaration of each parameter shall include an identifier.
14268 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14269 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14270 // Diagnose this as an extension in C17 and earlier.
14271 if (!getLangOpts().C23)
14272 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
14273 }
14274
14275 // C99 6.7.5.3p12:
14276 // If the function declarator is not part of a definition of that
14277 // function, parameters may have incomplete type and may use the [*]
14278 // notation in their sequences of declarator specifiers to specify
14279 // variable length array types.
14280 QualType PType = Param->getOriginalType();
14281 // FIXME: This diagnostic should point the '[*]' if source-location
14282 // information is added for it.
14283 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14284
14285 // If the parameter is a c++ class type and it has to be destructed in the
14286 // callee function, declare the destructor so that it can be called by the
14287 // callee function. Do not perform any direct access check on the dtor here.
14288 if (!Param->isInvalidDecl()) {
14289 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14290 if (!ClassDecl->isInvalidDecl() &&
14291 !ClassDecl->hasIrrelevantDestructor() &&
14292 !ClassDecl->isDependentContext() &&
14293 ClassDecl->isParamDestroyedInCallee()) {
14295 MarkFunctionReferenced(Param->getLocation(), Destructor);
14296 DiagnoseUseOfDecl(Destructor, Param->getLocation());
14297 }
14298 }
14299 }
14300
14301 // Parameters with the pass_object_size attribute only need to be marked
14302 // constant at function definitions. Because we lack information about
14303 // whether we're on a declaration or definition when we're instantiating the
14304 // attribute, we need to check for constness here.
14305 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14306 if (!Param->getType().isConstQualified())
14307 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14308 << Attr->getSpelling() << 1;
14309
14310 // Check for parameter names shadowing fields from the class.
14311 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14312 // The owning context for the parameter should be the function, but we
14313 // want to see if this function's declaration context is a record.
14314 DeclContext *DC = Param->getDeclContext();
14315 if (DC && DC->isFunctionOrMethod()) {
14316 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14317 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14318 RD, /*DeclIsField*/ false);
14319 }
14320 }
14321
14322 if (!Param->isInvalidDecl() &&
14323 Param->getOriginalType()->isWebAssemblyTableType()) {
14324 Param->setInvalidDecl();
14325 HasInvalidParm = true;
14326 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
14327 }
14328 }
14329
14330 return HasInvalidParm;
14331}
14332
14333std::optional<std::pair<
14335 *E,
14337 &Ctx);
14338
14339/// Compute the alignment and offset of the base class object given the
14340/// derived-to-base cast expression and the alignment and offset of the derived
14341/// class object.
14342static std::pair<CharUnits, CharUnits>
14344 CharUnits BaseAlignment, CharUnits Offset,
14345 ASTContext &Ctx) {
14346 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14347 ++PathI) {
14348 const CXXBaseSpecifier *Base = *PathI;
14349 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14350 if (Base->isVirtual()) {
14351 // The complete object may have a lower alignment than the non-virtual
14352 // alignment of the base, in which case the base may be misaligned. Choose
14353 // the smaller of the non-virtual alignment and BaseAlignment, which is a
14354 // conservative lower bound of the complete object alignment.
14355 CharUnits NonVirtualAlignment =
14357 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14358 Offset = CharUnits::Zero();
14359 } else {
14360 const ASTRecordLayout &RL =
14361 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14362 Offset += RL.getBaseClassOffset(BaseDecl);
14363 }
14364 DerivedType = Base->getType();
14365 }
14366
14367 return std::make_pair(BaseAlignment, Offset);
14368}
14369
14370/// Compute the alignment and offset of a binary additive operator.
14371static std::optional<std::pair<CharUnits, CharUnits>>
14373 bool IsSub, ASTContext &Ctx) {
14374 QualType PointeeType = PtrE->getType()->getPointeeType();
14375
14376 if (!PointeeType->isConstantSizeType())
14377 return std::nullopt;
14378
14379 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14380
14381 if (!P)
14382 return std::nullopt;
14383
14384 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14385 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14386 CharUnits Offset = EltSize * IdxRes->getExtValue();
14387 if (IsSub)
14388 Offset = -Offset;
14389 return std::make_pair(P->first, P->second + Offset);
14390 }
14391
14392 // If the integer expression isn't a constant expression, compute the lower
14393 // bound of the alignment using the alignment and offset of the pointer
14394 // expression and the element size.
14395 return std::make_pair(
14396 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14397 CharUnits::Zero());
14398}
14399
14400/// This helper function takes an lvalue expression and returns the alignment of
14401/// a VarDecl and a constant offset from the VarDecl.
14402std::optional<std::pair<
14403 CharUnits,
14405 ASTContext &Ctx) {
14406 E = E->IgnoreParens();
14407 switch (E->getStmtClass()) {
14408 default:
14409 break;
14410 case Stmt::CStyleCastExprClass:
14411 case Stmt::CXXStaticCastExprClass:
14412 case Stmt::ImplicitCastExprClass: {
14413 auto *CE = cast<CastExpr>(E);
14414 const Expr *From = CE->getSubExpr();
14415 switch (CE->getCastKind()) {
14416 default:
14417 break;
14418 case CK_NoOp:
14419 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14420 case CK_UncheckedDerivedToBase:
14421 case CK_DerivedToBase: {
14422 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14423 if (!P)
14424 break;
14425 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14426 P->second, Ctx);
14427 }
14428 }
14429 break;
14430 }
14431 case Stmt::ArraySubscriptExprClass: {
14432 auto *ASE = cast<ArraySubscriptExpr>(E);
14434 false, Ctx);
14435 }
14436 case Stmt::DeclRefExprClass: {
14437 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14438 // FIXME: If VD is captured by copy or is an escaping __block variable,
14439 // use the alignment of VD's type.
14440 if (!VD->getType()->isReferenceType()) {
14441 // Dependent alignment cannot be resolved -> bail out.
14442 if (VD->hasDependentAlignment())
14443 break;
14444 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14445 }
14446 if (VD->hasInit())
14447 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14448 }
14449 break;
14450 }
14451 case Stmt::MemberExprClass: {
14452 auto *ME = cast<MemberExpr>(E);
14453 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14454 if (!FD || FD->getType()->isReferenceType() ||
14455 FD->getParent()->isInvalidDecl())
14456 break;
14457 std::optional<std::pair<CharUnits, CharUnits>> P;
14458 if (ME->isArrow())
14459 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14460 else
14461 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14462 if (!P)
14463 break;
14464 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14465 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14466 return std::make_pair(P->first,
14467 P->second + CharUnits::fromQuantity(Offset));
14468 }
14469 case Stmt::UnaryOperatorClass: {
14470 auto *UO = cast<UnaryOperator>(E);
14471 switch (UO->getOpcode()) {
14472 default:
14473 break;
14474 case UO_Deref:
14476 }
14477 break;
14478 }
14479 case Stmt::BinaryOperatorClass: {
14480 auto *BO = cast<BinaryOperator>(E);
14481 auto Opcode = BO->getOpcode();
14482 switch (Opcode) {
14483 default:
14484 break;
14485 case BO_Comma:
14487 }
14488 break;
14489 }
14490 }
14491 return std::nullopt;
14492}
14493
14494/// This helper function takes a pointer expression and returns the alignment of
14495/// a VarDecl and a constant offset from the VarDecl.
14496std::optional<std::pair<
14498 *E,
14500 &Ctx) {
14501 E = E->IgnoreParens();
14502 switch (E->getStmtClass()) {
14503 default:
14504 break;
14505 case Stmt::CStyleCastExprClass:
14506 case Stmt::CXXStaticCastExprClass:
14507 case Stmt::ImplicitCastExprClass: {
14508 auto *CE = cast<CastExpr>(E);
14509 const Expr *From = CE->getSubExpr();
14510 switch (CE->getCastKind()) {
14511 default:
14512 break;
14513 case CK_NoOp:
14514 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14515 case CK_ArrayToPointerDecay:
14516 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14517 case CK_UncheckedDerivedToBase:
14518 case CK_DerivedToBase: {
14519 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14520 if (!P)
14521 break;
14523 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14524 }
14525 }
14526 break;
14527 }
14528 case Stmt::CXXThisExprClass: {
14529 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14531 return std::make_pair(Alignment, CharUnits::Zero());
14532 }
14533 case Stmt::UnaryOperatorClass: {
14534 auto *UO = cast<UnaryOperator>(E);
14535 if (UO->getOpcode() == UO_AddrOf)
14537 break;
14538 }
14539 case Stmt::BinaryOperatorClass: {
14540 auto *BO = cast<BinaryOperator>(E);
14541 auto Opcode = BO->getOpcode();
14542 switch (Opcode) {
14543 default:
14544 break;
14545 case BO_Add:
14546 case BO_Sub: {
14547 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14548 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14549 std::swap(LHS, RHS);
14550 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14551 Ctx);
14552 }
14553 case BO_Comma:
14554 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14555 }
14556 break;
14557 }
14558 }
14559 return std::nullopt;
14560}
14561
14563 // See if we can compute the alignment of a VarDecl and an offset from it.
14564 std::optional<std::pair<CharUnits, CharUnits>> P =
14566
14567 if (P)
14568 return P->first.alignmentAtOffset(P->second);
14569
14570 // If that failed, return the type's alignment.
14572}
14573
14575 // This is actually a lot of work to potentially be doing on every
14576 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14577 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14578 return;
14579
14580 // Ignore dependent types.
14581 if (T->isDependentType() || Op->getType()->isDependentType())
14582 return;
14583
14584 // Require that the destination be a pointer type.
14585 const PointerType *DestPtr = T->getAs<PointerType>();
14586 if (!DestPtr) return;
14587
14588 // If the destination has alignment 1, we're done.
14589 QualType DestPointee = DestPtr->getPointeeType();
14590 if (DestPointee->isIncompleteType()) return;
14591 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14592 if (DestAlign.isOne()) return;
14593
14594 // Require that the source be a pointer type.
14595 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14596 if (!SrcPtr) return;
14597 QualType SrcPointee = SrcPtr->getPointeeType();
14598
14599 // Explicitly allow casts from cv void*. We already implicitly
14600 // allowed casts to cv void*, since they have alignment 1.
14601 // Also allow casts involving incomplete types, which implicitly
14602 // includes 'void'.
14603 if (SrcPointee->isIncompleteType()) return;
14604
14605 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14606
14607 if (SrcAlign >= DestAlign) return;
14608
14609 Diag(TRange.getBegin(), diag::warn_cast_align)
14610 << Op->getType() << T
14611 << static_cast<unsigned>(SrcAlign.getQuantity())
14612 << static_cast<unsigned>(DestAlign.getQuantity())
14613 << TRange << Op->getSourceRange();
14614}
14615
14616void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14617 const ArraySubscriptExpr *ASE,
14618 bool AllowOnePastEnd, bool IndexNegated) {
14619 // Already diagnosed by the constant evaluator.
14621 return;
14622
14623 IndexExpr = IndexExpr->IgnoreParenImpCasts();
14624 if (IndexExpr->isValueDependent())
14625 return;
14626
14627 const Type *EffectiveType =
14629 BaseExpr = BaseExpr->IgnoreParenCasts();
14630 const ConstantArrayType *ArrayTy =
14632
14634 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
14635
14636 const Type *BaseType =
14637 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14638 bool IsUnboundedArray =
14639 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
14640 Context, StrictFlexArraysLevel,
14641 /*IgnoreTemplateOrMacroSubstitution=*/true);
14642 if (EffectiveType->isDependentType() ||
14643 (!IsUnboundedArray && BaseType->isDependentType()))
14644 return;
14645
14648 return;
14649
14650 llvm::APSInt index = Result.Val.getInt();
14651 if (IndexNegated) {
14652 index.setIsUnsigned(false);
14653 index = -index;
14654 }
14655
14656 if (IsUnboundedArray) {
14657 if (EffectiveType->isFunctionType())
14658 return;
14659 if (index.isUnsigned() || !index.isNegative()) {
14660 const auto &ASTC = getASTContext();
14661 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
14662 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
14663 if (index.getBitWidth() < AddrBits)
14664 index = index.zext(AddrBits);
14665 std::optional<CharUnits> ElemCharUnits =
14666 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14667 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14668 // pointer) bounds-checking isn't meaningful.
14669 if (!ElemCharUnits || ElemCharUnits->isZero())
14670 return;
14671 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14672 // If index has more active bits than address space, we already know
14673 // we have a bounds violation to warn about. Otherwise, compute
14674 // address of (index + 1)th element, and warn about bounds violation
14675 // only if that address exceeds address space.
14676 if (index.getActiveBits() <= AddrBits) {
14677 bool Overflow;
14678 llvm::APInt Product(index);
14679 Product += 1;
14680 Product = Product.umul_ov(ElemBytes, Overflow);
14681 if (!Overflow && Product.getActiveBits() <= AddrBits)
14682 return;
14683 }
14684
14685 // Need to compute max possible elements in address space, since that
14686 // is included in diag message.
14687 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
14688 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
14689 MaxElems += 1;
14690 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
14691 MaxElems = MaxElems.udiv(ElemBytes);
14692
14693 unsigned DiagID =
14694 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
14695 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
14696
14697 // Diag message shows element size in bits and in "bytes" (platform-
14698 // dependent CharUnits)
14699 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14700 PDiag(DiagID)
14701 << toString(index, 10, true) << AddrBits
14702 << (unsigned)ASTC.toBits(*ElemCharUnits)
14703 << toString(ElemBytes, 10, false)
14704 << toString(MaxElems, 10, false)
14705 << (unsigned)MaxElems.getLimitedValue(~0U)
14706 << IndexExpr->getSourceRange());
14707
14708 const NamedDecl *ND = nullptr;
14709 // Try harder to find a NamedDecl to point at in the note.
14710 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14711 BaseExpr = ASE->getBase()->IgnoreParenCasts();
14712 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14713 ND = DRE->getDecl();
14714 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14715 ND = ME->getMemberDecl();
14716
14717 if (ND)
14718 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14719 PDiag(diag::note_array_declared_here) << ND);
14720 }
14721 return;
14722 }
14723
14724 if (index.isUnsigned() || !index.isNegative()) {
14725 // It is possible that the type of the base expression after
14726 // IgnoreParenCasts is incomplete, even though the type of the base
14727 // expression before IgnoreParenCasts is complete (see PR39746 for an
14728 // example). In this case we have no information about whether the array
14729 // access exceeds the array bounds. However we can still diagnose an array
14730 // access which precedes the array bounds.
14731 if (BaseType->isIncompleteType())
14732 return;
14733
14734 llvm::APInt size = ArrayTy->getSize();
14735
14736 if (BaseType != EffectiveType) {
14737 // Make sure we're comparing apples to apples when comparing index to
14738 // size.
14739 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14740 uint64_t array_typesize = Context.getTypeSize(BaseType);
14741
14742 // Handle ptrarith_typesize being zero, such as when casting to void*.
14743 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
14744 if (!ptrarith_typesize)
14745 ptrarith_typesize = Context.getCharWidth();
14746
14747 if (ptrarith_typesize != array_typesize) {
14748 // There's a cast to a different size type involved.
14749 uint64_t ratio = array_typesize / ptrarith_typesize;
14750
14751 // TODO: Be smarter about handling cases where array_typesize is not a
14752 // multiple of ptrarith_typesize.
14753 if (ptrarith_typesize * ratio == array_typesize)
14754 size *= llvm::APInt(size.getBitWidth(), ratio);
14755 }
14756 }
14757
14758 if (size.getBitWidth() > index.getBitWidth())
14759 index = index.zext(size.getBitWidth());
14760 else if (size.getBitWidth() < index.getBitWidth())
14761 size = size.zext(index.getBitWidth());
14762
14763 // For array subscripting the index must be less than size, but for pointer
14764 // arithmetic also allow the index (offset) to be equal to size since
14765 // computing the next address after the end of the array is legal and
14766 // commonly done e.g. in C++ iterators and range-based for loops.
14767 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14768 return;
14769
14770 // Suppress the warning if the subscript expression (as identified by the
14771 // ']' location) and the index expression are both from macro expansions
14772 // within a system header.
14773 if (ASE) {
14775 ASE->getRBracketLoc());
14776 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14777 SourceLocation IndexLoc =
14778 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14779 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14780 return;
14781 }
14782 }
14783
14784 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
14785 : diag::warn_ptr_arith_exceeds_bounds;
14786 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
14787 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
14788
14790 BaseExpr->getBeginLoc(), BaseExpr,
14791 PDiag(DiagID) << toString(index, 10, true) << ArrayTy->desugar()
14792 << CastMsg << CastMsgTy << IndexExpr->getSourceRange());
14793 } else {
14794 unsigned DiagID = diag::warn_array_index_precedes_bounds;
14795 if (!ASE) {
14796 DiagID = diag::warn_ptr_arith_precedes_bounds;
14797 if (index.isNegative()) index = -index;
14798 }
14799
14800 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14801 PDiag(DiagID) << toString(index, 10, true)
14802 << IndexExpr->getSourceRange());
14803 }
14804
14805 const NamedDecl *ND = nullptr;
14806 // Try harder to find a NamedDecl to point at in the note.
14807 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14808 BaseExpr = ASE->getBase()->IgnoreParenCasts();
14809 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14810 ND = DRE->getDecl();
14811 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14812 ND = ME->getMemberDecl();
14813
14814 if (ND)
14815 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14816 PDiag(diag::note_array_declared_here) << ND);
14817}
14818
14819void Sema::CheckArrayAccess(const Expr *expr) {
14820 int AllowOnePastEnd = 0;
14821 while (expr) {
14822 expr = expr->IgnoreParenImpCasts();
14823 switch (expr->getStmtClass()) {
14824 case Stmt::ArraySubscriptExprClass: {
14825 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
14826 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
14827 AllowOnePastEnd > 0);
14828 expr = ASE->getBase();
14829 break;
14830 }
14831 case Stmt::MemberExprClass: {
14832 expr = cast<MemberExpr>(expr)->getBase();
14833 break;
14834 }
14835 case Stmt::ArraySectionExprClass: {
14836 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
14837 // FIXME: We should probably be checking all of the elements to the
14838 // 'length' here as well.
14839 if (ASE->getLowerBound())
14840 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
14841 /*ASE=*/nullptr, AllowOnePastEnd > 0);
14842 return;
14843 }
14844 case Stmt::UnaryOperatorClass: {
14845 // Only unwrap the * and & unary operators
14846 const UnaryOperator *UO = cast<UnaryOperator>(expr);
14847 expr = UO->getSubExpr();
14848 switch (UO->getOpcode()) {
14849 case UO_AddrOf:
14850 AllowOnePastEnd++;
14851 break;
14852 case UO_Deref:
14853 AllowOnePastEnd--;
14854 break;
14855 default:
14856 return;
14857 }
14858 break;
14859 }
14860 case Stmt::ConditionalOperatorClass: {
14861 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
14862 if (const Expr *lhs = cond->getLHS())
14863 CheckArrayAccess(lhs);
14864 if (const Expr *rhs = cond->getRHS())
14865 CheckArrayAccess(rhs);
14866 return;
14867 }
14868 case Stmt::CXXOperatorCallExprClass: {
14869 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
14870 for (const auto *Arg : OCE->arguments())
14871 CheckArrayAccess(Arg);
14872 return;
14873 }
14874 default:
14875 return;
14876 }
14877 }
14878}
14879
14881 Expr *RHS, bool isProperty) {
14882 // Check if RHS is an Objective-C object literal, which also can get
14883 // immediately zapped in a weak reference. Note that we explicitly
14884 // allow ObjCStringLiterals, since those are designed to never really die.
14885 RHS = RHS->IgnoreParenImpCasts();
14886
14887 // This enum needs to match with the 'select' in
14888 // warn_objc_arc_literal_assign (off-by-1).
14890 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
14891 return false;
14892
14893 S.Diag(Loc, diag::warn_arc_literal_assign)
14894 << (unsigned) Kind
14895 << (isProperty ? 0 : 1)
14896 << RHS->getSourceRange();
14897
14898 return true;
14899}
14900
14903 Expr *RHS, bool isProperty) {
14904 // Strip off any implicit cast added to get to the one ARC-specific.
14905 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14906 if (cast->getCastKind() == CK_ARCConsumeObject) {
14907 S.Diag(Loc, diag::warn_arc_retained_assign)
14909 << (isProperty ? 0 : 1)
14910 << RHS->getSourceRange();
14911 return true;
14912 }
14913 RHS = cast->getSubExpr();
14914 }
14915
14916 if (LT == Qualifiers::OCL_Weak &&
14917 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
14918 return true;
14919
14920 return false;
14921}
14922
14924 QualType LHS, Expr *RHS) {
14926
14928 return false;
14929
14930 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
14931 return true;
14932
14933 return false;
14934}
14935
14937 Expr *LHS, Expr *RHS) {
14938 QualType LHSType;
14939 // PropertyRef on LHS type need be directly obtained from
14940 // its declaration as it has a PseudoType.
14942 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
14943 if (PRE && !PRE->isImplicitProperty()) {
14944 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14945 if (PD)
14946 LHSType = PD->getType();
14947 }
14948
14949 if (LHSType.isNull())
14950 LHSType = LHS->getType();
14951
14953
14954 if (LT == Qualifiers::OCL_Weak) {
14955 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
14957 }
14958
14959 if (checkUnsafeAssigns(Loc, LHSType, RHS))
14960 return;
14961
14962 // FIXME. Check for other life times.
14963 if (LT != Qualifiers::OCL_None)
14964 return;
14965
14966 if (PRE) {
14967 if (PRE->isImplicitProperty())
14968 return;
14969 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14970 if (!PD)
14971 return;
14972
14973 unsigned Attributes = PD->getPropertyAttributes();
14974 if (Attributes & ObjCPropertyAttribute::kind_assign) {
14975 // when 'assign' attribute was not explicitly specified
14976 // by user, ignore it and rely on property type itself
14977 // for lifetime info.
14978 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
14979 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
14980 LHSType->isObjCRetainableType())
14981 return;
14982
14983 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14984 if (cast->getCastKind() == CK_ARCConsumeObject) {
14985 Diag(Loc, diag::warn_arc_retained_property_assign)
14986 << RHS->getSourceRange();
14987 return;
14988 }
14989 RHS = cast->getSubExpr();
14990 }
14991 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
14992 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
14993 return;
14994 }
14995 }
14996}
14997
14998//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
14999
15000static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15001 SourceLocation StmtLoc,
15002 const NullStmt *Body) {
15003 // Do not warn if the body is a macro that expands to nothing, e.g:
15004 //
15005 // #define CALL(x)
15006 // if (condition)
15007 // CALL(0);
15008 if (Body->hasLeadingEmptyMacro())
15009 return false;
15010
15011 // Get line numbers of statement and body.
15012 bool StmtLineInvalid;
15013 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15014 &StmtLineInvalid);
15015 if (StmtLineInvalid)
15016 return false;
15017
15018 bool BodyLineInvalid;
15019 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15020 &BodyLineInvalid);
15021 if (BodyLineInvalid)
15022 return false;
15023
15024 // Warn if null statement and body are on the same line.
15025 if (StmtLine != BodyLine)
15026 return false;
15027
15028 return true;
15029}
15030
15032 const Stmt *Body,
15033 unsigned DiagID) {
15034 // Since this is a syntactic check, don't emit diagnostic for template
15035 // instantiations, this just adds noise.
15037 return;
15038
15039 // The body should be a null statement.
15040 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15041 if (!NBody)
15042 return;
15043
15044 // Do the usual checks.
15045 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15046 return;
15047
15048 Diag(NBody->getSemiLoc(), DiagID);
15049 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15050}
15051
15053 const Stmt *PossibleBody) {
15054 assert(!CurrentInstantiationScope); // Ensured by caller
15055
15056 SourceLocation StmtLoc;
15057 const Stmt *Body;
15058 unsigned DiagID;
15059 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15060 StmtLoc = FS->getRParenLoc();
15061 Body = FS->getBody();
15062 DiagID = diag::warn_empty_for_body;
15063 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15064 StmtLoc = WS->getRParenLoc();
15065 Body = WS->getBody();
15066 DiagID = diag::warn_empty_while_body;
15067 } else
15068 return; // Neither `for' nor `while'.
15069
15070 // The body should be a null statement.
15071 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15072 if (!NBody)
15073 return;
15074
15075 // Skip expensive checks if diagnostic is disabled.
15076 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15077 return;
15078
15079 // Do the usual checks.
15080 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15081 return;
15082
15083 // `for(...);' and `while(...);' are popular idioms, so in order to keep
15084 // noise level low, emit diagnostics only if for/while is followed by a
15085 // CompoundStmt, e.g.:
15086 // for (int i = 0; i < n; i++);
15087 // {
15088 // a(i);
15089 // }
15090 // or if for/while is followed by a statement with more indentation
15091 // than for/while itself:
15092 // for (int i = 0; i < n; i++);
15093 // a(i);
15094 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15095 if (!ProbableTypo) {
15096 bool BodyColInvalid;
15097 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15098 PossibleBody->getBeginLoc(), &BodyColInvalid);
15099 if (BodyColInvalid)
15100 return;
15101
15102 bool StmtColInvalid;
15103 unsigned StmtCol =
15104 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15105 if (StmtColInvalid)
15106 return;
15107
15108 if (BodyCol > StmtCol)
15109 ProbableTypo = true;
15110 }
15111
15112 if (ProbableTypo) {
15113 Diag(NBody->getSemiLoc(), DiagID);
15114 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15115 }
15116}
15117
15118//===--- CHECK: Warn on self move with std::move. -------------------------===//
15119
15120void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15121 SourceLocation OpLoc) {
15122 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15123 return;
15124
15126 return;
15127
15128 // Strip parens and casts away.
15129 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15130 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15131
15132 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
15133 // which we can treat as an inlined std::move
15134 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
15135 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
15136 RHSExpr = CE->getArg(0);
15137 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
15138 CXXSCE && CXXSCE->isXValue())
15139 RHSExpr = CXXSCE->getSubExpr();
15140 else
15141 return;
15142
15143 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15144 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15145
15146 // Two DeclRefExpr's, check that the decls are the same.
15147 if (LHSDeclRef && RHSDeclRef) {
15148 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15149 return;
15150 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15151 RHSDeclRef->getDecl()->getCanonicalDecl())
15152 return;
15153
15154 auto D = Diag(OpLoc, diag::warn_self_move)
15155 << LHSExpr->getType() << LHSExpr->getSourceRange()
15156 << RHSExpr->getSourceRange();
15157 if (const FieldDecl *F =
15159 D << 1 << F
15160 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15161 else
15162 D << 0;
15163 return;
15164 }
15165
15166 // Member variables require a different approach to check for self moves.
15167 // MemberExpr's are the same if every nested MemberExpr refers to the same
15168 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15169 // the base Expr's are CXXThisExpr's.
15170 const Expr *LHSBase = LHSExpr;
15171 const Expr *RHSBase = RHSExpr;
15172 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15173 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15174 if (!LHSME || !RHSME)
15175 return;
15176
15177 while (LHSME && RHSME) {
15178 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15179 RHSME->getMemberDecl()->getCanonicalDecl())
15180 return;
15181
15182 LHSBase = LHSME->getBase();
15183 RHSBase = RHSME->getBase();
15184 LHSME = dyn_cast<MemberExpr>(LHSBase);
15185 RHSME = dyn_cast<MemberExpr>(RHSBase);
15186 }
15187
15188 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15189 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15190 if (LHSDeclRef && RHSDeclRef) {
15191 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15192 return;
15193 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15194 RHSDeclRef->getDecl()->getCanonicalDecl())
15195 return;
15196
15197 Diag(OpLoc, diag::warn_self_move)
15198 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15199 << RHSExpr->getSourceRange();
15200 return;
15201 }
15202
15203 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15204 Diag(OpLoc, diag::warn_self_move)
15205 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15206 << RHSExpr->getSourceRange();
15207}
15208
15209//===--- Layout compatibility ----------------------------------------------//
15210
15211static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
15212
15213/// Check if two enumeration types are layout-compatible.
15214static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
15215 const EnumDecl *ED2) {
15216 // C++11 [dcl.enum] p8:
15217 // Two enumeration types are layout-compatible if they have the same
15218 // underlying type.
15219 return ED1->isComplete() && ED2->isComplete() &&
15220 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15221}
15222
15223/// Check if two fields are layout-compatible.
15224/// Can be used on union members, which are exempt from alignment requirement
15225/// of common initial sequence.
15226static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
15227 const FieldDecl *Field2,
15228 bool AreUnionMembers = false) {
15229#ifndef NDEBUG
15230 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
15231 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
15232 assert(((Field1Parent->isStructureOrClassType() &&
15233 Field2Parent->isStructureOrClassType()) ||
15234 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
15235 "Can't evaluate layout compatibility between a struct field and a "
15236 "union field.");
15237 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
15238 (AreUnionMembers && Field1Parent->isUnionType())) &&
15239 "AreUnionMembers should be 'true' for union fields (only).");
15240#endif
15241
15242 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15243 return false;
15244
15245 if (Field1->isBitField() != Field2->isBitField())
15246 return false;
15247
15248 if (Field1->isBitField()) {
15249 // Make sure that the bit-fields are the same length.
15250 unsigned Bits1 = Field1->getBitWidthValue();
15251 unsigned Bits2 = Field2->getBitWidthValue();
15252
15253 if (Bits1 != Bits2)
15254 return false;
15255 }
15256
15257 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
15258 Field2->hasAttr<clang::NoUniqueAddressAttr>())
15259 return false;
15260
15261 if (!AreUnionMembers &&
15262 Field1->getMaxAlignment() != Field2->getMaxAlignment())
15263 return false;
15264
15265 return true;
15266}
15267
15268/// Check if two standard-layout structs are layout-compatible.
15269/// (C++11 [class.mem] p17)
15270static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
15271 const RecordDecl *RD2) {
15272 // Get to the class where the fields are declared
15273 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
15274 RD1 = D1CXX->getStandardLayoutBaseWithFields();
15275
15276 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
15277 RD2 = D2CXX->getStandardLayoutBaseWithFields();
15278
15279 // Check the fields.
15280 return llvm::equal(RD1->fields(), RD2->fields(),
15281 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
15282 return isLayoutCompatible(C, F1, F2);
15283 });
15284}
15285
15286/// Check if two standard-layout unions are layout-compatible.
15287/// (C++11 [class.mem] p18)
15288static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
15289 const RecordDecl *RD2) {
15290 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
15291 RD2->fields());
15292
15293 for (auto *Field1 : RD1->fields()) {
15294 auto I = UnmatchedFields.begin();
15295 auto E = UnmatchedFields.end();
15296
15297 for ( ; I != E; ++I) {
15298 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
15299 bool Result = UnmatchedFields.erase(*I);
15300 (void) Result;
15301 assert(Result);
15302 break;
15303 }
15304 }
15305 if (I == E)
15306 return false;
15307 }
15308
15309 return UnmatchedFields.empty();
15310}
15311
15312static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
15313 const RecordDecl *RD2) {
15314 if (RD1->isUnion() != RD2->isUnion())
15315 return false;
15316
15317 if (RD1->isUnion())
15318 return isLayoutCompatibleUnion(C, RD1, RD2);
15319 else
15320 return isLayoutCompatibleStruct(C, RD1, RD2);
15321}
15322
15323/// Check if two types are layout-compatible in C++11 sense.
15324static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
15325 if (T1.isNull() || T2.isNull())
15326 return false;
15327
15328 // C++20 [basic.types] p11:
15329 // Two types cv1 T1 and cv2 T2 are layout-compatible types
15330 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
15331 // or layout-compatible standard-layout class types (11.4).
15334
15335 if (C.hasSameType(T1, T2))
15336 return true;
15337
15338 const Type::TypeClass TC1 = T1->getTypeClass();
15339 const Type::TypeClass TC2 = T2->getTypeClass();
15340
15341 if (TC1 != TC2)
15342 return false;
15343
15344 if (TC1 == Type::Enum)
15345 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
15346 if (TC1 == Type::Record) {
15347 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15348 return false;
15349
15351 T2->castAsRecordDecl());
15352 }
15353
15354 return false;
15355}
15356
15358 return isLayoutCompatible(getASTContext(), T1, T2);
15359}
15360
15361//===-------------- Pointer interconvertibility ----------------------------//
15362
15364 const TypeSourceInfo *Derived) {
15365 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
15366 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
15367
15368 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
15369 getASTContext().hasSameType(BaseT, DerivedT))
15370 return true;
15371
15372 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
15373 return false;
15374
15375 // Per [basic.compound]/4.3, containing object has to be standard-layout.
15376 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
15377 return true;
15378
15379 return false;
15380}
15381
15382//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15383
15384/// Given a type tag expression find the type tag itself.
15385///
15386/// \param TypeExpr Type tag expression, as it appears in user's code.
15387///
15388/// \param VD Declaration of an identifier that appears in a type tag.
15389///
15390/// \param MagicValue Type tag magic value.
15391///
15392/// \param isConstantEvaluated whether the evalaution should be performed in
15393
15394/// constant context.
15395static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15396 const ValueDecl **VD, uint64_t *MagicValue,
15397 bool isConstantEvaluated) {
15398 while(true) {
15399 if (!TypeExpr)
15400 return false;
15401
15402 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15403
15404 switch (TypeExpr->getStmtClass()) {
15405 case Stmt::UnaryOperatorClass: {
15406 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15407 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15408 TypeExpr = UO->getSubExpr();
15409 continue;
15410 }
15411 return false;
15412 }
15413
15414 case Stmt::DeclRefExprClass: {
15415 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15416 *VD = DRE->getDecl();
15417 return true;
15418 }
15419
15420 case Stmt::IntegerLiteralClass: {
15421 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15422 llvm::APInt MagicValueAPInt = IL->getValue();
15423 if (MagicValueAPInt.getActiveBits() <= 64) {
15424 *MagicValue = MagicValueAPInt.getZExtValue();
15425 return true;
15426 } else
15427 return false;
15428 }
15429
15430 case Stmt::BinaryConditionalOperatorClass:
15431 case Stmt::ConditionalOperatorClass: {
15432 const AbstractConditionalOperator *ACO =
15433 cast<AbstractConditionalOperator>(TypeExpr);
15434 bool Result;
15435 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15436 isConstantEvaluated)) {
15437 if (Result)
15438 TypeExpr = ACO->getTrueExpr();
15439 else
15440 TypeExpr = ACO->getFalseExpr();
15441 continue;
15442 }
15443 return false;
15444 }
15445
15446 case Stmt::BinaryOperatorClass: {
15447 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15448 if (BO->getOpcode() == BO_Comma) {
15449 TypeExpr = BO->getRHS();
15450 continue;
15451 }
15452 return false;
15453 }
15454
15455 default:
15456 return false;
15457 }
15458 }
15459}
15460
15461/// Retrieve the C type corresponding to type tag TypeExpr.
15462///
15463/// \param TypeExpr Expression that specifies a type tag.
15464///
15465/// \param MagicValues Registered magic values.
15466///
15467/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15468/// kind.
15469///
15470/// \param TypeInfo Information about the corresponding C type.
15471///
15472/// \param isConstantEvaluated whether the evalaution should be performed in
15473/// constant context.
15474///
15475/// \returns true if the corresponding C type was found.
15477 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15478 const ASTContext &Ctx,
15479 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15480 *MagicValues,
15481 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15482 bool isConstantEvaluated) {
15483 FoundWrongKind = false;
15484
15485 // Variable declaration that has type_tag_for_datatype attribute.
15486 const ValueDecl *VD = nullptr;
15487
15488 uint64_t MagicValue;
15489
15490 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15491 return false;
15492
15493 if (VD) {
15494 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15495 if (I->getArgumentKind() != ArgumentKind) {
15496 FoundWrongKind = true;
15497 return false;
15498 }
15499 TypeInfo.Type = I->getMatchingCType();
15500 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15501 TypeInfo.MustBeNull = I->getMustBeNull();
15502 return true;
15503 }
15504 return false;
15505 }
15506
15507 if (!MagicValues)
15508 return false;
15509
15510 llvm::DenseMap<Sema::TypeTagMagicValue,
15511 Sema::TypeTagData>::const_iterator I =
15512 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15513 if (I == MagicValues->end())
15514 return false;
15515
15516 TypeInfo = I->second;
15517 return true;
15518}
15519
15521 uint64_t MagicValue, QualType Type,
15522 bool LayoutCompatible,
15523 bool MustBeNull) {
15524 if (!TypeTagForDatatypeMagicValues)
15525 TypeTagForDatatypeMagicValues.reset(
15526 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15527
15528 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15529 (*TypeTagForDatatypeMagicValues)[Magic] =
15530 TypeTagData(Type, LayoutCompatible, MustBeNull);
15531}
15532
15533static bool IsSameCharType(QualType T1, QualType T2) {
15534 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15535 if (!BT1)
15536 return false;
15537
15538 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15539 if (!BT2)
15540 return false;
15541
15542 BuiltinType::Kind T1Kind = BT1->getKind();
15543 BuiltinType::Kind T2Kind = BT2->getKind();
15544
15545 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
15546 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
15547 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15548 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15549}
15550
15551void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15552 const ArrayRef<const Expr *> ExprArgs,
15553 SourceLocation CallSiteLoc) {
15554 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15555 bool IsPointerAttr = Attr->getIsPointer();
15556
15557 // Retrieve the argument representing the 'type_tag'.
15558 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15559 if (TypeTagIdxAST >= ExprArgs.size()) {
15560 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15561 << 0 << Attr->getTypeTagIdx().getSourceIndex();
15562 return;
15563 }
15564 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15565 bool FoundWrongKind;
15566 TypeTagData TypeInfo;
15567 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15568 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15570 if (FoundWrongKind)
15571 Diag(TypeTagExpr->getExprLoc(),
15572 diag::warn_type_tag_for_datatype_wrong_kind)
15573 << TypeTagExpr->getSourceRange();
15574 return;
15575 }
15576
15577 // Retrieve the argument representing the 'arg_idx'.
15578 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15579 if (ArgumentIdxAST >= ExprArgs.size()) {
15580 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15581 << 1 << Attr->getArgumentIdx().getSourceIndex();
15582 return;
15583 }
15584 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15585 if (IsPointerAttr) {
15586 // Skip implicit cast of pointer to `void *' (as a function argument).
15587 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15588 if (ICE->getType()->isVoidPointerType() &&
15589 ICE->getCastKind() == CK_BitCast)
15590 ArgumentExpr = ICE->getSubExpr();
15591 }
15592 QualType ArgumentType = ArgumentExpr->getType();
15593
15594 // Passing a `void*' pointer shouldn't trigger a warning.
15595 if (IsPointerAttr && ArgumentType->isVoidPointerType())
15596 return;
15597
15598 if (TypeInfo.MustBeNull) {
15599 // Type tag with matching void type requires a null pointer.
15600 if (!ArgumentExpr->isNullPointerConstant(Context,
15602 Diag(ArgumentExpr->getExprLoc(),
15603 diag::warn_type_safety_null_pointer_required)
15604 << ArgumentKind->getName()
15605 << ArgumentExpr->getSourceRange()
15606 << TypeTagExpr->getSourceRange();
15607 }
15608 return;
15609 }
15610
15611 QualType RequiredType = TypeInfo.Type;
15612 if (IsPointerAttr)
15613 RequiredType = Context.getPointerType(RequiredType);
15614
15615 bool mismatch = false;
15616 if (!TypeInfo.LayoutCompatible) {
15617 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15618
15619 // C++11 [basic.fundamental] p1:
15620 // Plain char, signed char, and unsigned char are three distinct types.
15621 //
15622 // But we treat plain `char' as equivalent to `signed char' or `unsigned
15623 // char' depending on the current char signedness mode.
15624 if (mismatch)
15625 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15626 RequiredType->getPointeeType())) ||
15627 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15628 mismatch = false;
15629 } else
15630 if (IsPointerAttr)
15631 mismatch = !isLayoutCompatible(Context,
15632 ArgumentType->getPointeeType(),
15633 RequiredType->getPointeeType());
15634 else
15635 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15636
15637 if (mismatch)
15638 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15639 << ArgumentType << ArgumentKind
15640 << TypeInfo.LayoutCompatible << RequiredType
15641 << ArgumentExpr->getSourceRange()
15642 << TypeTagExpr->getSourceRange();
15643}
15644
15645void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15646 CharUnits Alignment) {
15647 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
15648 Alignment);
15649}
15650
15652 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
15653 const NamedDecl *ND = m.RD;
15654 if (ND->getName().empty()) {
15655 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15656 ND = TD;
15657 }
15658 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15659 << m.MD << ND << m.E->getSourceRange();
15660 }
15662}
15663
15665 E = E->IgnoreParens();
15666 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
15667 return;
15668 if (isa<UnaryOperator>(E) &&
15669 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15670 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15671 if (isa<MemberExpr>(Op)) {
15672 auto &MisalignedMembersForExpr =
15674 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
15675 if (MA != MisalignedMembersForExpr.end() &&
15676 (T->isDependentType() || T->isIntegerType() ||
15679 T->getPointeeType()) <= MA->Alignment))))
15680 MisalignedMembersForExpr.erase(MA);
15681 }
15682 }
15683}
15684
15686 Expr *E,
15687 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15688 Action) {
15689 const auto *ME = dyn_cast<MemberExpr>(E);
15690 if (!ME)
15691 return;
15692
15693 // No need to check expressions with an __unaligned-qualified type.
15695 return;
15696
15697 // For a chain of MemberExpr like "a.b.c.d" this list
15698 // will keep FieldDecl's like [d, c, b].
15699 SmallVector<FieldDecl *, 4> ReverseMemberChain;
15700 const MemberExpr *TopME = nullptr;
15701 bool AnyIsPacked = false;
15702 do {
15703 QualType BaseType = ME->getBase()->getType();
15704 if (BaseType->isDependentType())
15705 return;
15706 if (ME->isArrow())
15707 BaseType = BaseType->getPointeeType();
15708 auto *RD = BaseType->castAsRecordDecl();
15709 if (RD->isInvalidDecl())
15710 return;
15711
15712 ValueDecl *MD = ME->getMemberDecl();
15713 auto *FD = dyn_cast<FieldDecl>(MD);
15714 // We do not care about non-data members.
15715 if (!FD || FD->isInvalidDecl())
15716 return;
15717
15718 AnyIsPacked =
15719 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15720 ReverseMemberChain.push_back(FD);
15721
15722 TopME = ME;
15723 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15724 } while (ME);
15725 assert(TopME && "We did not compute a topmost MemberExpr!");
15726
15727 // Not the scope of this diagnostic.
15728 if (!AnyIsPacked)
15729 return;
15730
15731 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15732 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15733 // TODO: The innermost base of the member expression may be too complicated.
15734 // For now, just disregard these cases. This is left for future
15735 // improvement.
15736 if (!DRE && !isa<CXXThisExpr>(TopBase))
15737 return;
15738
15739 // Alignment expected by the whole expression.
15740 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15741
15742 // No need to do anything else with this case.
15743 if (ExpectedAlignment.isOne())
15744 return;
15745
15746 // Synthesize offset of the whole access.
15747 CharUnits Offset;
15748 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
15750
15751 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15752 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15753 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
15754
15755 // The base expression of the innermost MemberExpr may give
15756 // stronger guarantees than the class containing the member.
15757 if (DRE && !TopME->isArrow()) {
15758 const ValueDecl *VD = DRE->getDecl();
15759 if (!VD->getType()->isReferenceType())
15760 CompleteObjectAlignment =
15761 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15762 }
15763
15764 // Check if the synthesized offset fulfills the alignment.
15765 if (Offset % ExpectedAlignment != 0 ||
15766 // It may fulfill the offset it but the effective alignment may still be
15767 // lower than the expected expression alignment.
15768 CompleteObjectAlignment < ExpectedAlignment) {
15769 // If this happens, we want to determine a sensible culprit of this.
15770 // Intuitively, watching the chain of member expressions from right to
15771 // left, we start with the required alignment (as required by the field
15772 // type) but some packed attribute in that chain has reduced the alignment.
15773 // It may happen that another packed structure increases it again. But if
15774 // we are here such increase has not been enough. So pointing the first
15775 // FieldDecl that either is packed or else its RecordDecl is,
15776 // seems reasonable.
15777 FieldDecl *FD = nullptr;
15778 CharUnits Alignment;
15779 for (FieldDecl *FDI : ReverseMemberChain) {
15780 if (FDI->hasAttr<PackedAttr>() ||
15781 FDI->getParent()->hasAttr<PackedAttr>()) {
15782 FD = FDI;
15783 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
15786 break;
15787 }
15788 }
15789 assert(FD && "We did not find a packed FieldDecl!");
15790 Action(E, FD->getParent(), FD, Alignment);
15791 }
15792}
15793
15794void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15795 using namespace std::placeholders;
15796
15798 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15799 _2, _3, _4));
15800}
15801
15802// Performs a similar job to Sema::UsualUnaryConversions, but without any
15803// implicit promotion of integral/enumeration types.
15805 // First, convert to an r-value.
15807 if (Res.isInvalid())
15808 return ExprError();
15809
15810 // Promote floating-point types.
15811 return S.UsualUnaryFPConversions(Res.get());
15812}
15813
15815 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
15816 if (checkArgCount(TheCall, 1))
15817 return true;
15818
15819 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
15820 if (A.isInvalid())
15821 return true;
15822
15823 TheCall->setArg(0, A.get());
15824 QualType TyA = A.get()->getType();
15825
15826 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
15827 ArgTyRestr, 1))
15828 return true;
15829
15830 TheCall->setType(TyA);
15831 return false;
15832}
15833
15834bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
15835 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
15836 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
15837 TheCall->setType(*Res);
15838 return false;
15839 }
15840 return true;
15841}
15842
15844 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
15845 if (!Res)
15846 return true;
15847
15848 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
15849 TheCall->setType(VecTy0->getElementType());
15850 else
15851 TheCall->setType(*Res);
15852
15853 return false;
15854}
15855
15859 R = RHS->getEnumCoercedType(S.Context);
15860 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
15862 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
15863 << LHS->getSourceRange() << RHS->getSourceRange()
15864 << /*Arithmetic Between*/ 0 << L << R;
15865 }
15866 return false;
15867}
15868
15869/// Check if all arguments have the same type. If the types don't match, emit an
15870/// error message and return true. Otherwise return false.
15871///
15872/// For scalars we directly compare their unqualified types. But even if we
15873/// compare unqualified vector types, a difference in qualifiers in the element
15874/// types can make the vector types be considered not equal. For example,
15875/// vector of 4 'const float' values vs vector of 4 'float' values.
15876/// So we compare unqualified types of their elements and number of elements.
15878 ArrayRef<Expr *> Args) {
15879 assert(!Args.empty() && "Should have at least one argument.");
15880
15881 Expr *Arg0 = Args.front();
15882 QualType Ty0 = Arg0->getType();
15883
15884 auto EmitError = [&](Expr *ArgI) {
15885 SemaRef.Diag(Arg0->getBeginLoc(),
15886 diag::err_typecheck_call_different_arg_types)
15887 << Arg0->getType() << ArgI->getType();
15888 };
15889
15890 // Compare scalar types.
15891 if (!Ty0->isVectorType()) {
15892 for (Expr *ArgI : Args.drop_front())
15893 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
15894 EmitError(ArgI);
15895 return true;
15896 }
15897
15898 return false;
15899 }
15900
15901 // Compare vector types.
15902 const auto *Vec0 = Ty0->castAs<VectorType>();
15903 for (Expr *ArgI : Args.drop_front()) {
15904 const auto *VecI = ArgI->getType()->getAs<VectorType>();
15905 if (!VecI ||
15906 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
15907 VecI->getElementType()) ||
15908 Vec0->getNumElements() != VecI->getNumElements()) {
15909 EmitError(ArgI);
15910 return true;
15911 }
15912 }
15913
15914 return false;
15915}
15916
15917std::optional<QualType>
15919 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
15920 if (checkArgCount(TheCall, 2))
15921 return std::nullopt;
15922
15924 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
15925 return std::nullopt;
15926
15927 Expr *Args[2];
15928 for (int I = 0; I < 2; ++I) {
15929 ExprResult Converted =
15930 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
15931 if (Converted.isInvalid())
15932 return std::nullopt;
15933 Args[I] = Converted.get();
15934 }
15935
15936 SourceLocation LocA = Args[0]->getBeginLoc();
15937 QualType TyA = Args[0]->getType();
15938
15939 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
15940 return std::nullopt;
15941
15942 if (checkBuiltinVectorMathArgTypes(*this, Args))
15943 return std::nullopt;
15944
15945 TheCall->setArg(0, Args[0]);
15946 TheCall->setArg(1, Args[1]);
15947 return TyA;
15948}
15949
15951 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
15952 if (checkArgCount(TheCall, 3))
15953 return true;
15954
15955 SourceLocation Loc = TheCall->getExprLoc();
15956 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
15957 TheCall->getArg(1), Loc) ||
15958 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
15959 TheCall->getArg(2), Loc))
15960 return true;
15961
15962 Expr *Args[3];
15963 for (int I = 0; I < 3; ++I) {
15964 ExprResult Converted =
15965 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
15966 if (Converted.isInvalid())
15967 return true;
15968 Args[I] = Converted.get();
15969 }
15970
15971 int ArgOrdinal = 1;
15972 for (Expr *Arg : Args) {
15973 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
15974 ArgTyRestr, ArgOrdinal++))
15975 return true;
15976 }
15977
15978 if (checkBuiltinVectorMathArgTypes(*this, Args))
15979 return true;
15980
15981 for (int I = 0; I < 3; ++I)
15982 TheCall->setArg(I, Args[I]);
15983
15984 TheCall->setType(Args[0]->getType());
15985 return false;
15986}
15987
15988bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
15989 if (checkArgCount(TheCall, 1))
15990 return true;
15991
15992 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
15993 if (A.isInvalid())
15994 return true;
15995
15996 TheCall->setArg(0, A.get());
15997 return false;
15998}
15999
16000bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
16001 if (checkArgCount(TheCall, 1))
16002 return true;
16003
16004 ExprResult Arg = TheCall->getArg(0);
16005 QualType TyArg = Arg.get()->getType();
16006
16007 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
16008 return Diag(TheCall->getArg(0)->getBeginLoc(),
16009 diag::err_builtin_invalid_arg_type)
16010 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
16011
16012 TheCall->setType(TyArg);
16013 return false;
16014}
16015
16016ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
16017 ExprResult CallResult) {
16018 if (checkArgCount(TheCall, 1))
16019 return ExprError();
16020
16021 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16022 if (MatrixArg.isInvalid())
16023 return MatrixArg;
16024 Expr *Matrix = MatrixArg.get();
16025
16026 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16027 if (!MType) {
16028 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16029 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
16030 << Matrix->getType();
16031 return ExprError();
16032 }
16033
16034 // Create returned matrix type by swapping rows and columns of the argument
16035 // matrix type.
16037 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16038
16039 // Change the return type to the type of the returned matrix.
16040 TheCall->setType(ResultType);
16041
16042 // Update call argument to use the possibly converted matrix argument.
16043 TheCall->setArg(0, Matrix);
16044 return CallResult;
16045}
16046
16047// Get and verify the matrix dimensions.
16048static std::optional<unsigned>
16050 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
16051 if (!Value) {
16052 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16053 << Name;
16054 return {};
16055 }
16056 uint64_t Dim = Value->getZExtValue();
16058 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16060 return {};
16061 }
16062 return Dim;
16063}
16064
16065ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16066 ExprResult CallResult) {
16067 if (!getLangOpts().MatrixTypes) {
16068 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16069 return ExprError();
16070 }
16071
16072 if (checkArgCount(TheCall, 4))
16073 return ExprError();
16074
16075 unsigned PtrArgIdx = 0;
16076 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16077 Expr *RowsExpr = TheCall->getArg(1);
16078 Expr *ColumnsExpr = TheCall->getArg(2);
16079 Expr *StrideExpr = TheCall->getArg(3);
16080
16081 bool ArgError = false;
16082
16083 // Check pointer argument.
16084 {
16086 if (PtrConv.isInvalid())
16087 return PtrConv;
16088 PtrExpr = PtrConv.get();
16089 TheCall->setArg(0, PtrExpr);
16090 if (PtrExpr->isTypeDependent()) {
16091 TheCall->setType(Context.DependentTy);
16092 return TheCall;
16093 }
16094 }
16095
16096 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16097 QualType ElementTy;
16098 if (!PtrTy) {
16099 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16100 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
16101 << PtrExpr->getType();
16102 ArgError = true;
16103 } else {
16104 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16105
16107 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16108 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
16109 << /* no fp */ 0 << PtrExpr->getType();
16110 ArgError = true;
16111 }
16112 }
16113
16114 // Apply default Lvalue conversions and convert the expression to size_t.
16115 auto ApplyArgumentConversions = [this](Expr *E) {
16117 if (Conv.isInvalid())
16118 return Conv;
16119
16120 return tryConvertExprToType(Conv.get(), Context.getSizeType());
16121 };
16122
16123 // Apply conversion to row and column expressions.
16124 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16125 if (!RowsConv.isInvalid()) {
16126 RowsExpr = RowsConv.get();
16127 TheCall->setArg(1, RowsExpr);
16128 } else
16129 RowsExpr = nullptr;
16130
16131 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16132 if (!ColumnsConv.isInvalid()) {
16133 ColumnsExpr = ColumnsConv.get();
16134 TheCall->setArg(2, ColumnsExpr);
16135 } else
16136 ColumnsExpr = nullptr;
16137
16138 // If any part of the result matrix type is still pending, just use
16139 // Context.DependentTy, until all parts are resolved.
16140 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16141 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16142 TheCall->setType(Context.DependentTy);
16143 return CallResult;
16144 }
16145
16146 // Check row and column dimensions.
16147 std::optional<unsigned> MaybeRows;
16148 if (RowsExpr)
16149 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16150
16151 std::optional<unsigned> MaybeColumns;
16152 if (ColumnsExpr)
16153 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16154
16155 // Check stride argument.
16156 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16157 if (StrideConv.isInvalid())
16158 return ExprError();
16159 StrideExpr = StrideConv.get();
16160 TheCall->setArg(3, StrideExpr);
16161
16162 if (MaybeRows) {
16163 if (std::optional<llvm::APSInt> Value =
16164 StrideExpr->getIntegerConstantExpr(Context)) {
16165 uint64_t Stride = Value->getZExtValue();
16166 if (Stride < *MaybeRows) {
16167 Diag(StrideExpr->getBeginLoc(),
16168 diag::err_builtin_matrix_stride_too_small);
16169 ArgError = true;
16170 }
16171 }
16172 }
16173
16174 if (ArgError || !MaybeRows || !MaybeColumns)
16175 return ExprError();
16176
16177 TheCall->setType(
16178 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16179 return CallResult;
16180}
16181
16182ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16183 ExprResult CallResult) {
16184 if (checkArgCount(TheCall, 3))
16185 return ExprError();
16186
16187 unsigned PtrArgIdx = 1;
16188 Expr *MatrixExpr = TheCall->getArg(0);
16189 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16190 Expr *StrideExpr = TheCall->getArg(2);
16191
16192 bool ArgError = false;
16193
16194 {
16195 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16196 if (MatrixConv.isInvalid())
16197 return MatrixConv;
16198 MatrixExpr = MatrixConv.get();
16199 TheCall->setArg(0, MatrixExpr);
16200 }
16201 if (MatrixExpr->isTypeDependent()) {
16202 TheCall->setType(Context.DependentTy);
16203 return TheCall;
16204 }
16205
16206 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16207 if (!MatrixTy) {
16208 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16209 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
16210 ArgError = true;
16211 }
16212
16213 {
16215 if (PtrConv.isInvalid())
16216 return PtrConv;
16217 PtrExpr = PtrConv.get();
16218 TheCall->setArg(1, PtrExpr);
16219 if (PtrExpr->isTypeDependent()) {
16220 TheCall->setType(Context.DependentTy);
16221 return TheCall;
16222 }
16223 }
16224
16225 // Check pointer argument.
16226 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16227 if (!PtrTy) {
16228 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16229 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
16230 << PtrExpr->getType();
16231 ArgError = true;
16232 } else {
16233 QualType ElementTy = PtrTy->getPointeeType();
16234 if (ElementTy.isConstQualified()) {
16235 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16236 ArgError = true;
16237 }
16238 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16239 if (MatrixTy &&
16240 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16241 Diag(PtrExpr->getBeginLoc(),
16242 diag::err_builtin_matrix_pointer_arg_mismatch)
16243 << ElementTy << MatrixTy->getElementType();
16244 ArgError = true;
16245 }
16246 }
16247
16248 // Apply default Lvalue conversions and convert the stride expression to
16249 // size_t.
16250 {
16251 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16252 if (StrideConv.isInvalid())
16253 return StrideConv;
16254
16255 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16256 if (StrideConv.isInvalid())
16257 return StrideConv;
16258 StrideExpr = StrideConv.get();
16259 TheCall->setArg(2, StrideExpr);
16260 }
16261
16262 // Check stride argument.
16263 if (MatrixTy) {
16264 if (std::optional<llvm::APSInt> Value =
16265 StrideExpr->getIntegerConstantExpr(Context)) {
16266 uint64_t Stride = Value->getZExtValue();
16267 if (Stride < MatrixTy->getNumRows()) {
16268 Diag(StrideExpr->getBeginLoc(),
16269 diag::err_builtin_matrix_stride_too_small);
16270 ArgError = true;
16271 }
16272 }
16273 }
16274
16275 if (ArgError)
16276 return ExprError();
16277
16278 return CallResult;
16279}
16280
16282 const NamedDecl *Callee) {
16283 // This warning does not make sense in code that has no runtime behavior.
16285 return;
16286
16287 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
16288
16289 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
16290 return;
16291
16292 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16293 // all TCBs the callee is a part of.
16294 llvm::StringSet<> CalleeTCBs;
16295 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
16296 CalleeTCBs.insert(A->getTCBName());
16297 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
16298 CalleeTCBs.insert(A->getTCBName());
16299
16300 // Go through the TCBs the caller is a part of and emit warnings if Caller
16301 // is in a TCB that the Callee is not.
16302 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
16303 StringRef CallerTCB = A->getTCBName();
16304 if (CalleeTCBs.count(CallerTCB) == 0) {
16305 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
16306 << Callee << CallerTCB;
16307 }
16308 }
16309}
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:3420
Represents an enum.
Definition: Decl.h:4004
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4227
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4168
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:3157
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3260
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4693
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3393
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition: Decl.h:3273
const FieldDecl * findCountedByField() const
Find the FieldDecl specified in a FAM's "counted_by" attribute.
Definition: Decl.cpp:4796
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:2888
Represents a function declaration or definition.
Definition: Decl.h:1999
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition: Decl.cpp:4494
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2794
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3703
param_iterator param_end()
Definition: Decl.h:2784
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3806
QualType getReturnType() const
Definition: Decl.h:2842
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2771
param_iterator param_begin()
Definition: Decl.h:2783
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:4270
bool isStatic() const
Definition: Decl.h:2926
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:4085
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:4071
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3767
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:1683
bool hasLeadingEmptyMacro() const
Definition: Stmt.h:1697
SourceLocation getSemiLoc() const
Definition: Stmt.h:1694
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:4309
bool isNonTrivialToPrimitiveCopy() const
Definition: Decl.h:4395
field_range fields() const
Definition: Decl.h:4512
RecordDecl * getMostRecentDecl()
Definition: Decl.h:4335
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition: Decl.h:4387
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:14890
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:12936
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:16082
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:14496
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:16038
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:15239
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:21316
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:13791
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:20595
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:15539
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:12989
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:18401
@ 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:1472
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:3829
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3809
bool isUnion() const
Definition: Decl.h:3919
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 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 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:3559
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:2697
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:12953
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition: Sema.h:13051
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