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,
126 Context.getTargetInfo());
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 (const Expr *Arg : Call->arguments()) {
181 if (Arg->isValueDependent())
182 continue;
183
184 std::optional<std::string> ArgString = Arg->tryEvaluateString(S.Context);
185 int DiagMsgKind = -1;
186 // Arguments must be pointers to constant strings and cannot use '$'.
187 if (!ArgString.has_value())
188 DiagMsgKind = 0;
189 else if (ArgString->find('$') != std::string::npos)
190 DiagMsgKind = 1;
191
192 if (DiagMsgKind >= 0) {
193 S.Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg)
194 << DiagMsgKind << Arg->getSourceRange();
195 HasError = true;
196 }
197 }
198
199 return !HasError;
200}
201
203 if (Value->isTypeDependent())
204 return false;
205
206 InitializedEntity Entity =
208 ExprResult Result =
210 if (Result.isInvalid())
211 return true;
212 Value = Result.get();
213 return false;
214}
215
216/// Check that the first argument to __builtin_annotation is an integer
217/// and the second argument is a non-wide string literal.
218static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
219 if (S.checkArgCount(TheCall, 2))
220 return true;
221
222 // First argument should be an integer.
223 Expr *ValArg = TheCall->getArg(0);
224 QualType Ty = ValArg->getType();
225 if (!Ty->isIntegerType()) {
226 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
227 << ValArg->getSourceRange();
228 return true;
229 }
230
231 // Second argument should be a constant string.
232 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
233 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
234 if (!Literal || !Literal->isOrdinary()) {
235 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
236 << StrArg->getSourceRange();
237 return true;
238 }
239
240 TheCall->setType(Ty);
241 return false;
242}
243
244static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
245 // We need at least one argument.
246 if (TheCall->getNumArgs() < 1) {
247 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
248 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
249 << TheCall->getCallee()->getSourceRange();
250 return true;
251 }
252
253 // All arguments should be wide string literals.
254 for (Expr *Arg : TheCall->arguments()) {
255 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
256 if (!Literal || !Literal->isWide()) {
257 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
258 << Arg->getSourceRange();
259 return true;
260 }
261 }
262
263 return false;
264}
265
266/// Check that the argument to __builtin_addressof is a glvalue, and set the
267/// result type to the corresponding pointer type.
268static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
269 if (S.checkArgCount(TheCall, 1))
270 return true;
271
272 ExprResult Arg(TheCall->getArg(0));
273 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
274 if (ResultType.isNull())
275 return true;
276
277 TheCall->setArg(0, Arg.get());
278 TheCall->setType(ResultType);
279 return false;
280}
281
282/// Check that the argument to __builtin_function_start is a function.
283static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
284 if (S.checkArgCount(TheCall, 1))
285 return true;
286
287 if (TheCall->getArg(0)->containsErrors())
288 return true;
289
291 if (Arg.isInvalid())
292 return true;
293
294 TheCall->setArg(0, Arg.get());
295 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
297
298 if (!FD) {
299 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
300 << TheCall->getSourceRange();
301 return true;
302 }
303
304 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
305 TheCall->getBeginLoc());
306}
307
308/// Check the number of arguments and set the result type to
309/// the argument type.
310static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
311 if (S.checkArgCount(TheCall, 1))
312 return true;
313
314 TheCall->setType(TheCall->getArg(0)->getType());
315 return false;
316}
317
318/// Check that the value argument for __builtin_is_aligned(value, alignment) and
319/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
320/// type (but not a function pointer) and that the alignment is a power-of-two.
321static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
322 if (S.checkArgCount(TheCall, 2))
323 return true;
324
325 clang::Expr *Source = TheCall->getArg(0);
326 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
327
328 auto IsValidIntegerType = [](QualType Ty) {
329 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
330 };
331 QualType SrcTy = Source->getType();
332 // We should also be able to use it with arrays (but not functions!).
333 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
334 SrcTy = S.Context.getDecayedType(SrcTy);
335 }
336 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
337 SrcTy->isFunctionPointerType()) {
338 // FIXME: this is not quite the right error message since we don't allow
339 // floating point types, or member pointers.
340 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
341 << SrcTy;
342 return true;
343 }
344
345 clang::Expr *AlignOp = TheCall->getArg(1);
346 if (!IsValidIntegerType(AlignOp->getType())) {
347 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
348 << AlignOp->getType();
349 return true;
350 }
351 Expr::EvalResult AlignResult;
352 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
353 // We can't check validity of alignment if it is value dependent.
354 if (!AlignOp->isValueDependent() &&
355 AlignOp->EvaluateAsInt(AlignResult, S.Context,
357 llvm::APSInt AlignValue = AlignResult.Val.getInt();
358 llvm::APSInt MaxValue(
359 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
360 if (AlignValue < 1) {
361 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
362 return true;
363 }
364 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
365 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
366 << toString(MaxValue, 10);
367 return true;
368 }
369 if (!AlignValue.isPowerOf2()) {
370 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
371 return true;
372 }
373 if (AlignValue == 1) {
374 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
375 << IsBooleanAlignBuiltin;
376 }
377 }
378
381 SourceLocation(), Source);
382 if (SrcArg.isInvalid())
383 return true;
384 TheCall->setArg(0, SrcArg.get());
385 ExprResult AlignArg =
387 S.Context, AlignOp->getType(), false),
388 SourceLocation(), AlignOp);
389 if (AlignArg.isInvalid())
390 return true;
391 TheCall->setArg(1, AlignArg.get());
392 // For align_up/align_down, the return type is the same as the (potentially
393 // decayed) argument type including qualifiers. For is_aligned(), the result
394 // is always bool.
395 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
396 return false;
397}
398
399static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
400 if (S.checkArgCount(TheCall, 3))
401 return true;
402
403 std::pair<unsigned, const char *> Builtins[] = {
404 { Builtin::BI__builtin_add_overflow, "ckd_add" },
405 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
406 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
407 };
408
409 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
410 const char *> &P) {
411 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
413 S.getSourceManager(), S.getLangOpts()) == P.second;
414 });
415
416 auto ValidCkdIntType = [](QualType QT) {
417 // A valid checked integer type is an integer type other than a plain char,
418 // bool, a bit-precise type, or an enumeration type.
419 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
420 return (BT->getKind() >= BuiltinType::Short &&
421 BT->getKind() <= BuiltinType::Int128) || (
422 BT->getKind() >= BuiltinType::UShort &&
423 BT->getKind() <= BuiltinType::UInt128) ||
424 BT->getKind() == BuiltinType::UChar ||
425 BT->getKind() == BuiltinType::SChar;
426 return false;
427 };
428
429 // First two arguments should be integers.
430 for (unsigned I = 0; I < 2; ++I) {
432 if (Arg.isInvalid()) return true;
433 TheCall->setArg(I, Arg.get());
434
435 QualType Ty = Arg.get()->getType();
436 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
437 if (!IsValid) {
438 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
439 << CkdOperation << Ty << Arg.get()->getSourceRange();
440 return true;
441 }
442 }
443
444 // Third argument should be a pointer to a non-const integer.
445 // IRGen correctly handles volatile, restrict, and address spaces, and
446 // the other qualifiers aren't possible.
447 {
449 if (Arg.isInvalid()) return true;
450 TheCall->setArg(2, Arg.get());
451
452 QualType Ty = Arg.get()->getType();
453 const auto *PtrTy = Ty->getAs<PointerType>();
454 if (!PtrTy ||
455 !PtrTy->getPointeeType()->isIntegerType() ||
456 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
457 PtrTy->getPointeeType().isConstQualified()) {
458 S.Diag(Arg.get()->getBeginLoc(),
459 diag::err_overflow_builtin_must_be_ptr_int)
460 << CkdOperation << Ty << Arg.get()->getSourceRange();
461 return true;
462 }
463 }
464
465 // Disallow signed bit-precise integer args larger than 128 bits to mul
466 // function until we improve backend support.
467 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
468 for (unsigned I = 0; I < 3; ++I) {
469 const auto Arg = TheCall->getArg(I);
470 // Third argument will be a pointer.
471 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
472 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
473 S.getASTContext().getIntWidth(Ty) > 128)
474 return S.Diag(Arg->getBeginLoc(),
475 diag::err_overflow_builtin_bit_int_max_size)
476 << 128;
477 }
478 }
479
480 return false;
481}
482
483namespace {
484struct BuiltinDumpStructGenerator {
485 Sema &S;
486 CallExpr *TheCall;
487 SourceLocation Loc = TheCall->getBeginLoc();
488 SmallVector<Expr *, 32> Actions;
489 DiagnosticErrorTrap ErrorTracker;
490 PrintingPolicy Policy;
491
492 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
493 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
494 Policy(S.Context.getPrintingPolicy()) {
495 Policy.AnonymousTagLocations = false;
496 }
497
498 Expr *makeOpaqueValueExpr(Expr *Inner) {
499 auto *OVE = new (S.Context)
500 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
501 Inner->getObjectKind(), Inner);
502 Actions.push_back(OVE);
503 return OVE;
504 }
505
506 Expr *getStringLiteral(llvm::StringRef Str) {
508 // Wrap the literal in parentheses to attach a source location.
509 return new (S.Context) ParenExpr(Loc, Loc, Lit);
510 }
511
512 bool callPrintFunction(llvm::StringRef Format,
513 llvm::ArrayRef<Expr *> Exprs = {}) {
514 SmallVector<Expr *, 8> Args;
515 assert(TheCall->getNumArgs() >= 2);
516 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
517 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
518 Args.push_back(getStringLiteral(Format));
519 llvm::append_range(Args, Exprs);
520
521 // Register a note to explain why we're performing the call.
522 Sema::CodeSynthesisContext Ctx;
524 Ctx.PointOfInstantiation = Loc;
525 Ctx.CallArgs = Args.data();
526 Ctx.NumCallArgs = Args.size();
528
529 ExprResult RealCall =
530 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
531 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
532
534 if (!RealCall.isInvalid())
535 Actions.push_back(RealCall.get());
536 // Bail out if we've hit any errors, even if we managed to build the
537 // call. We don't want to produce more than one error.
538 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
539 }
540
541 Expr *getIndentString(unsigned Depth) {
542 if (!Depth)
543 return nullptr;
544
545 llvm::SmallString<32> Indent;
546 Indent.resize(Depth * Policy.Indentation, ' ');
547 return getStringLiteral(Indent);
548 }
549
550 Expr *getTypeString(QualType T) {
551 return getStringLiteral(T.getAsString(Policy));
552 }
553
554 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
555 llvm::raw_svector_ostream OS(Str);
556
557 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
558 // than trying to print a single character.
559 if (auto *BT = T->getAs<BuiltinType>()) {
560 switch (BT->getKind()) {
561 case BuiltinType::Bool:
562 OS << "%d";
563 return true;
564 case BuiltinType::Char_U:
565 case BuiltinType::UChar:
566 OS << "%hhu";
567 return true;
568 case BuiltinType::Char_S:
569 case BuiltinType::SChar:
570 OS << "%hhd";
571 return true;
572 default:
573 break;
574 }
575 }
576
577 analyze_printf::PrintfSpecifier Specifier;
578 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
579 // We were able to guess how to format this.
580 if (Specifier.getConversionSpecifier().getKind() ==
581 analyze_printf::PrintfConversionSpecifier::sArg) {
582 // Wrap double-quotes around a '%s' specifier and limit its maximum
583 // length. Ideally we'd also somehow escape special characters in the
584 // contents but printf doesn't support that.
585 // FIXME: '%s' formatting is not safe in general.
586 OS << '"';
587 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
588 Specifier.toString(OS);
589 OS << '"';
590 // FIXME: It would be nice to include a '...' if the string doesn't fit
591 // in the length limit.
592 } else {
593 Specifier.toString(OS);
594 }
595 return true;
596 }
597
598 if (T->isPointerType()) {
599 // Format all pointers with '%p'.
600 OS << "%p";
601 return true;
602 }
603
604 return false;
605 }
606
607 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
608 Expr *IndentLit = getIndentString(Depth);
609 Expr *TypeLit = getTypeString(S.Context.getCanonicalTagType(RD));
610 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
611 : callPrintFunction("%s", {TypeLit}))
612 return true;
613
614 return dumpRecordValue(RD, E, IndentLit, Depth);
615 }
616
617 // Dump a record value. E should be a pointer or lvalue referring to an RD.
618 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
619 unsigned Depth) {
620 // FIXME: Decide what to do if RD is a union. At least we should probably
621 // turn off printing `const char*` members with `%s`, because that is very
622 // likely to crash if that's not the active member. Whatever we decide, we
623 // should document it.
624
625 // Build an OpaqueValueExpr so we can refer to E more than once without
626 // triggering re-evaluation.
627 Expr *RecordArg = makeOpaqueValueExpr(E);
628 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
629
630 if (callPrintFunction(" {\n"))
631 return true;
632
633 // Dump each base class, regardless of whether they're aggregates.
634 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
635 for (const auto &Base : CXXRD->bases()) {
636 QualType BaseType =
637 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
638 : S.Context.getLValueReferenceType(Base.getType());
640 Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
641 RecordArg);
642 if (BasePtr.isInvalid() ||
643 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
644 Depth + 1))
645 return true;
646 }
647 }
648
649 Expr *FieldIndentArg = getIndentString(Depth + 1);
650
651 // Dump each field.
652 for (auto *D : RD->decls()) {
653 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
654 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
655 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
656 continue;
657
658 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
659 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
660 getTypeString(FD->getType()),
661 getStringLiteral(FD->getName())};
662
663 if (FD->isBitField()) {
664 Format += ": %zu ";
665 QualType SizeT = S.Context.getSizeType();
666 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
667 FD->getBitWidthValue());
668 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
669 }
670
671 Format += "=";
672
675 CXXScopeSpec(), Loc, IFD,
676 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
678 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
680 DeclarationNameInfo(FD->getDeclName(), Loc));
681 if (Field.isInvalid())
682 return true;
683
684 auto *InnerRD = FD->getType()->getAsRecordDecl();
685 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
686 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
687 // Recursively print the values of members of aggregate record type.
688 if (callPrintFunction(Format, Args) ||
689 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
690 return true;
691 } else {
692 Format += " ";
693 if (appendFormatSpecifier(FD->getType(), Format)) {
694 // We know how to print this field.
695 Args.push_back(Field.get());
696 } else {
697 // We don't know how to print this field. Print out its address
698 // with a format specifier that a smart tool will be able to
699 // recognize and treat specially.
700 Format += "*%p";
701 ExprResult FieldAddr =
702 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
703 if (FieldAddr.isInvalid())
704 return true;
705 Args.push_back(FieldAddr.get());
706 }
707 Format += "\n";
708 if (callPrintFunction(Format, Args))
709 return true;
710 }
711 }
712
713 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
714 : callPrintFunction("}\n");
715 }
716
717 Expr *buildWrapper() {
718 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
720 TheCall->setType(Wrapper->getType());
721 TheCall->setValueKind(Wrapper->getValueKind());
722 return Wrapper;
723 }
724};
725} // namespace
726
728 if (S.checkArgCountAtLeast(TheCall, 2))
729 return ExprError();
730
731 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
732 if (PtrArgResult.isInvalid())
733 return ExprError();
734 TheCall->setArg(0, PtrArgResult.get());
735
736 // First argument should be a pointer to a struct.
737 QualType PtrArgType = PtrArgResult.get()->getType();
738 if (!PtrArgType->isPointerType() ||
739 !PtrArgType->getPointeeType()->isRecordType()) {
740 S.Diag(PtrArgResult.get()->getBeginLoc(),
741 diag::err_expected_struct_pointer_argument)
742 << 1 << TheCall->getDirectCallee() << PtrArgType;
743 return ExprError();
744 }
745 QualType Pointee = PtrArgType->getPointeeType();
746 const RecordDecl *RD = Pointee->getAsRecordDecl();
747 // Try to instantiate the class template as appropriate; otherwise, access to
748 // its data() may lead to a crash.
749 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
750 diag::err_incomplete_type))
751 return ExprError();
752 // Second argument is a callable, but we can't fully validate it until we try
753 // calling it.
754 QualType FnArgType = TheCall->getArg(1)->getType();
755 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
756 !FnArgType->isBlockPointerType() &&
757 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
758 auto *BT = FnArgType->getAs<BuiltinType>();
759 switch (BT ? BT->getKind() : BuiltinType::Void) {
760 case BuiltinType::Dependent:
761 case BuiltinType::Overload:
762 case BuiltinType::BoundMember:
763 case BuiltinType::PseudoObject:
764 case BuiltinType::UnknownAny:
765 case BuiltinType::BuiltinFn:
766 // This might be a callable.
767 break;
768
769 default:
770 S.Diag(TheCall->getArg(1)->getBeginLoc(),
771 diag::err_expected_callable_argument)
772 << 2 << TheCall->getDirectCallee() << FnArgType;
773 return ExprError();
774 }
775 }
776
777 BuiltinDumpStructGenerator Generator(S, TheCall);
778
779 // Wrap parentheses around the given pointer. This is not necessary for
780 // correct code generation, but it means that when we pretty-print the call
781 // arguments in our diagnostics we will produce '(&s)->n' instead of the
782 // incorrect '&s->n'.
783 Expr *PtrArg = PtrArgResult.get();
784 PtrArg = new (S.Context)
785 ParenExpr(PtrArg->getBeginLoc(),
786 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
787 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
788 return ExprError();
789
790 return Generator.buildWrapper();
791}
792
793static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
794 if (S.checkArgCount(BuiltinCall, 2))
795 return true;
796
797 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
798 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
799 Expr *Call = BuiltinCall->getArg(0);
800 Expr *Chain = BuiltinCall->getArg(1);
801
802 if (Call->getStmtClass() != Stmt::CallExprClass) {
803 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
804 << Call->getSourceRange();
805 return true;
806 }
807
808 auto CE = cast<CallExpr>(Call);
809 if (CE->getCallee()->getType()->isBlockPointerType()) {
810 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
811 << Call->getSourceRange();
812 return true;
813 }
814
815 const Decl *TargetDecl = CE->getCalleeDecl();
816 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
817 if (FD->getBuiltinID()) {
818 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
819 << Call->getSourceRange();
820 return true;
821 }
822
823 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
824 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
825 << Call->getSourceRange();
826 return true;
827 }
828
829 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
830 if (ChainResult.isInvalid())
831 return true;
832 if (!ChainResult.get()->getType()->isPointerType()) {
833 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
834 << Chain->getSourceRange();
835 return true;
836 }
837
838 QualType ReturnTy = CE->getCallReturnType(S.Context);
839 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
840 QualType BuiltinTy = S.Context.getFunctionType(
841 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
842 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
843
844 Builtin =
845 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
846
847 BuiltinCall->setType(CE->getType());
848 BuiltinCall->setValueKind(CE->getValueKind());
849 BuiltinCall->setObjectKind(CE->getObjectKind());
850 BuiltinCall->setCallee(Builtin);
851 BuiltinCall->setArg(1, ChainResult.get());
852
853 return false;
854}
855
856namespace {
857
858class ScanfDiagnosticFormatHandler
860 // Accepts the argument index (relative to the first destination index) of the
861 // argument whose size we want.
862 using ComputeSizeFunction =
863 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
864
865 // Accepts the argument index (relative to the first destination index), the
866 // destination size, and the source size).
867 using DiagnoseFunction =
868 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
869
870 ComputeSizeFunction ComputeSizeArgument;
871 DiagnoseFunction Diagnose;
872
873public:
874 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
875 DiagnoseFunction Diagnose)
876 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
877
878 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
879 const char *StartSpecifier,
880 unsigned specifierLen) override {
881 if (!FS.consumesDataArgument())
882 return true;
883
884 unsigned NulByte = 0;
885 switch ((FS.getConversionSpecifier().getKind())) {
886 default:
887 return true;
890 NulByte = 1;
891 break;
893 break;
894 }
895
896 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
897 if (FW.getHowSpecified() !=
898 analyze_format_string::OptionalAmount::HowSpecified::Constant)
899 return true;
900
901 unsigned SourceSize = FW.getConstantAmount() + NulByte;
902
903 std::optional<llvm::APSInt> DestSizeAPS =
904 ComputeSizeArgument(FS.getArgIndex());
905 if (!DestSizeAPS)
906 return true;
907
908 unsigned DestSize = DestSizeAPS->getZExtValue();
909
910 if (DestSize < SourceSize)
911 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
912
913 return true;
914 }
915};
916
917class EstimateSizeFormatHandler
919 size_t Size;
920 /// Whether the format string contains Linux kernel's format specifier
921 /// extension.
922 bool IsKernelCompatible = true;
923
924public:
925 EstimateSizeFormatHandler(StringRef Format)
926 : Size(std::min(Format.find(0), Format.size()) +
927 1 /* null byte always written by sprintf */) {}
928
929 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
930 const char *, unsigned SpecifierLen,
931 const TargetInfo &) override {
932
933 const size_t FieldWidth = computeFieldWidth(FS);
934 const size_t Precision = computePrecision(FS);
935
936 // The actual format.
937 switch (FS.getConversionSpecifier().getKind()) {
938 // Just a char.
941 Size += std::max(FieldWidth, (size_t)1);
942 break;
943 // Just an integer.
953 Size += std::max(FieldWidth, Precision);
954 break;
955
956 // %g style conversion switches between %f or %e style dynamically.
957 // %g removes trailing zeros, and does not print decimal point if there are
958 // no digits that follow it. Thus %g can print a single digit.
959 // FIXME: If it is alternative form:
960 // For g and G conversions, trailing zeros are not removed from the result.
963 Size += 1;
964 break;
965
966 // Floating point number in the form '[+]ddd.ddd'.
969 Size += std::max(FieldWidth, 1 /* integer part */ +
970 (Precision ? 1 + Precision
971 : 0) /* period + decimal */);
972 break;
973
974 // Floating point number in the form '[-]d.ddde[+-]dd'.
977 Size +=
978 std::max(FieldWidth,
979 1 /* integer part */ +
980 (Precision ? 1 + Precision : 0) /* period + decimal */ +
981 1 /* e or E letter */ + 2 /* exponent */);
982 break;
983
984 // Floating point number in the form '[-]0xh.hhhhp±dd'.
987 Size +=
988 std::max(FieldWidth,
989 2 /* 0x */ + 1 /* integer part */ +
990 (Precision ? 1 + Precision : 0) /* period + decimal */ +
991 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
992 break;
993
994 // Just a string.
997 Size += FieldWidth;
998 break;
999
1000 // Just a pointer in the form '0xddd'.
1002 // Linux kernel has its own extesion for `%p` specifier.
1003 // Kernel Document:
1004 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1005 IsKernelCompatible = false;
1006 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
1007 break;
1008
1009 // A plain percent.
1011 Size += 1;
1012 break;
1013
1014 default:
1015 break;
1016 }
1017
1018 // If field width is specified, the sign/space is already accounted for
1019 // within the field width, so no additional size is needed.
1020 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1021 Size += 1;
1022
1023 if (FS.hasAlternativeForm()) {
1024 switch (FS.getConversionSpecifier().getKind()) {
1025 // For o conversion, it increases the precision, if and only if necessary,
1026 // to force the first digit of the result to be a zero
1027 // (if the value and precision are both 0, a single 0 is printed)
1029 // For b conversion, a nonzero result has 0b prefixed to it.
1031 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1032 // it.
1035 // Note: even when the prefix is added, if
1036 // (prefix_width <= FieldWidth - formatted_length) holds,
1037 // the prefix does not increase the format
1038 // size. e.g.(("%#3x", 0xf) is "0xf")
1039
1040 // If the result is zero, o, b, x, X adds nothing.
1041 break;
1042 // For a, A, e, E, f, F, g, and G conversions,
1043 // the result of converting a floating-point number always contains a
1044 // decimal-point
1053 Size += (Precision ? 0 : 1);
1054 break;
1055 // For other conversions, the behavior is undefined.
1056 default:
1057 break;
1058 }
1059 }
1060 assert(SpecifierLen <= Size && "no underflow");
1061 Size -= SpecifierLen;
1062 return true;
1063 }
1064
1065 size_t getSizeLowerBound() const { return Size; }
1066 bool isKernelCompatible() const { return IsKernelCompatible; }
1067
1068private:
1069 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1070 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1071 size_t FieldWidth = 0;
1073 FieldWidth = FW.getConstantAmount();
1074 return FieldWidth;
1075 }
1076
1077 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1078 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1079 size_t Precision = 0;
1080
1081 // See man 3 printf for default precision value based on the specifier.
1082 switch (FW.getHowSpecified()) {
1084 switch (FS.getConversionSpecifier().getKind()) {
1085 default:
1086 break;
1090 Precision = 1;
1091 break;
1098 Precision = 1;
1099 break;
1106 Precision = 6;
1107 break;
1109 Precision = 1;
1110 break;
1111 }
1112 break;
1114 Precision = FW.getConstantAmount();
1115 break;
1116 default:
1117 break;
1118 }
1119 return Precision;
1120 }
1121};
1122
1123} // namespace
1124
1125static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1126 StringRef &FormatStrRef, size_t &StrLen,
1127 ASTContext &Context) {
1128 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1129 Format && (Format->isOrdinary() || Format->isUTF8())) {
1130 FormatStrRef = Format->getString();
1131 const ConstantArrayType *T =
1132 Context.getAsConstantArrayType(Format->getType());
1133 assert(T && "String literal not of constant array type!");
1134 size_t TypeSize = T->getZExtSize();
1135 // In case there's a null byte somewhere.
1136 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1137 return true;
1138 }
1139 return false;
1140}
1141
1142void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1143 CallExpr *TheCall) {
1144 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1146 return;
1147
1148 bool UseDABAttr = false;
1149 const FunctionDecl *UseDecl = FD;
1150
1151 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1152 if (DABAttr) {
1153 UseDecl = DABAttr->getFunction();
1154 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1155 UseDABAttr = true;
1156 }
1157
1158 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1159
1160 if (!BuiltinID)
1161 return;
1162
1163 const TargetInfo &TI = getASTContext().getTargetInfo();
1164 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1165
1166 auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1167 // If we refer to a diagnose_as_builtin attribute, we need to change the
1168 // argument index to refer to the arguments of the called function. Unless
1169 // the index is out of bounds, which presumably means it's a variadic
1170 // function.
1171 if (!UseDABAttr)
1172 return Index;
1173 unsigned DABIndices = DABAttr->argIndices_size();
1174 unsigned NewIndex = Index < DABIndices
1175 ? DABAttr->argIndices_begin()[Index]
1176 : Index - DABIndices + FD->getNumParams();
1177 if (NewIndex >= TheCall->getNumArgs())
1178 return std::nullopt;
1179 return NewIndex;
1180 };
1181
1182 auto ComputeExplicitObjectSizeArgument =
1183 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1184 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1185 if (!IndexOptional)
1186 return std::nullopt;
1187 unsigned NewIndex = *IndexOptional;
1188 Expr::EvalResult Result;
1189 Expr *SizeArg = TheCall->getArg(NewIndex);
1190 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
1191 return std::nullopt;
1192 llvm::APSInt Integer = Result.Val.getInt();
1193 Integer.setIsUnsigned(true);
1194 return Integer;
1195 };
1196
1197 auto ComputeSizeArgument =
1198 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1199 // If the parameter has a pass_object_size attribute, then we should use its
1200 // (potentially) more strict checking mode. Otherwise, conservatively assume
1201 // type 0.
1202 int BOSType = 0;
1203 // This check can fail for variadic functions.
1204 if (Index < FD->getNumParams()) {
1205 if (const auto *POS =
1206 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1207 BOSType = POS->getType();
1208 }
1209
1210 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1211 if (!IndexOptional)
1212 return std::nullopt;
1213 unsigned NewIndex = *IndexOptional;
1214
1215 if (NewIndex >= TheCall->getNumArgs())
1216 return std::nullopt;
1217
1218 const Expr *ObjArg = TheCall->getArg(NewIndex);
1220 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
1221 return std::nullopt;
1222
1223 // Get the object size in the target's size_t width.
1224 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
1225 };
1226
1227 auto ComputeStrLenArgument =
1228 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1229 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1230 if (!IndexOptional)
1231 return std::nullopt;
1232 unsigned NewIndex = *IndexOptional;
1233
1234 const Expr *ObjArg = TheCall->getArg(NewIndex);
1236 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
1237 return std::nullopt;
1238 // Add 1 for null byte.
1239 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
1240 };
1241
1242 std::optional<llvm::APSInt> SourceSize;
1243 std::optional<llvm::APSInt> DestinationSize;
1244 unsigned DiagID = 0;
1245 bool IsChkVariant = false;
1246
1247 auto GetFunctionName = [&]() {
1248 std::string FunctionNameStr =
1249 getASTContext().BuiltinInfo.getName(BuiltinID);
1250 llvm::StringRef FunctionName = FunctionNameStr;
1251 // Skim off the details of whichever builtin was called to produce a better
1252 // diagnostic, as it's unlikely that the user wrote the __builtin
1253 // explicitly.
1254 if (IsChkVariant) {
1255 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
1256 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
1257 } else {
1258 FunctionName.consume_front("__builtin_");
1259 }
1260 return FunctionName.str();
1261 };
1262
1263 switch (BuiltinID) {
1264 default:
1265 return;
1266 case Builtin::BI__builtin_stpcpy:
1267 case Builtin::BIstpcpy:
1268 case Builtin::BI__builtin_strcpy:
1269 case Builtin::BIstrcpy: {
1270 DiagID = diag::warn_fortify_strlen_overflow;
1271 SourceSize = ComputeStrLenArgument(1);
1272 DestinationSize = ComputeSizeArgument(0);
1273 break;
1274 }
1275
1276 case Builtin::BI__builtin___stpcpy_chk:
1277 case Builtin::BI__builtin___strcpy_chk: {
1278 DiagID = diag::warn_fortify_strlen_overflow;
1279 SourceSize = ComputeStrLenArgument(1);
1280 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1281 IsChkVariant = true;
1282 break;
1283 }
1284
1285 case Builtin::BIscanf:
1286 case Builtin::BIfscanf:
1287 case Builtin::BIsscanf: {
1288 unsigned FormatIndex = 1;
1289 unsigned DataIndex = 2;
1290 if (BuiltinID == Builtin::BIscanf) {
1291 FormatIndex = 0;
1292 DataIndex = 1;
1293 }
1294
1295 const auto *FormatExpr =
1296 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1297
1298 StringRef FormatStrRef;
1299 size_t StrLen;
1300 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1301 return;
1302
1303 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1304 unsigned SourceSize) {
1305 DiagID = diag::warn_fortify_scanf_overflow;
1306 unsigned Index = ArgIndex + DataIndex;
1307 std::string FunctionName = GetFunctionName();
1308 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1309 PDiag(DiagID) << FunctionName << (Index + 1)
1310 << DestSize << SourceSize);
1311 };
1312
1313 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1314 return ComputeSizeArgument(Index + DataIndex);
1315 };
1316 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1317 const char *FormatBytes = FormatStrRef.data();
1319 FormatBytes + StrLen, getLangOpts(),
1320 Context.getTargetInfo());
1321
1322 // Unlike the other cases, in this one we have already issued the diagnostic
1323 // here, so no need to continue (because unlike the other cases, here the
1324 // diagnostic refers to the argument number).
1325 return;
1326 }
1327
1328 case Builtin::BIsprintf:
1329 case Builtin::BI__builtin___sprintf_chk: {
1330 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1331 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1332
1333 StringRef FormatStrRef;
1334 size_t StrLen;
1335 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1336 EstimateSizeFormatHandler H(FormatStrRef);
1337 const char *FormatBytes = FormatStrRef.data();
1339 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1340 Context.getTargetInfo(), false)) {
1341 DiagID = H.isKernelCompatible()
1342 ? diag::warn_format_overflow
1343 : diag::warn_format_overflow_non_kprintf;
1344 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1345 .extOrTrunc(SizeTypeWidth);
1346 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1347 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1348 IsChkVariant = true;
1349 } else {
1350 DestinationSize = ComputeSizeArgument(0);
1351 }
1352 break;
1353 }
1354 }
1355 return;
1356 }
1357 case Builtin::BI__builtin___memcpy_chk:
1358 case Builtin::BI__builtin___memmove_chk:
1359 case Builtin::BI__builtin___memset_chk:
1360 case Builtin::BI__builtin___strlcat_chk:
1361 case Builtin::BI__builtin___strlcpy_chk:
1362 case Builtin::BI__builtin___strncat_chk:
1363 case Builtin::BI__builtin___strncpy_chk:
1364 case Builtin::BI__builtin___stpncpy_chk:
1365 case Builtin::BI__builtin___memccpy_chk:
1366 case Builtin::BI__builtin___mempcpy_chk: {
1367 DiagID = diag::warn_builtin_chk_overflow;
1368 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1369 DestinationSize =
1370 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1371 IsChkVariant = true;
1372 break;
1373 }
1374
1375 case Builtin::BI__builtin___snprintf_chk:
1376 case Builtin::BI__builtin___vsnprintf_chk: {
1377 DiagID = diag::warn_builtin_chk_overflow;
1378 SourceSize = ComputeExplicitObjectSizeArgument(1);
1379 DestinationSize = ComputeExplicitObjectSizeArgument(3);
1380 IsChkVariant = true;
1381 break;
1382 }
1383
1384 case Builtin::BIstrncat:
1385 case Builtin::BI__builtin_strncat:
1386 case Builtin::BIstrncpy:
1387 case Builtin::BI__builtin_strncpy:
1388 case Builtin::BIstpncpy:
1389 case Builtin::BI__builtin_stpncpy: {
1390 // Whether these functions overflow depends on the runtime strlen of the
1391 // string, not just the buffer size, so emitting the "always overflow"
1392 // diagnostic isn't quite right. We should still diagnose passing a buffer
1393 // size larger than the destination buffer though; this is a runtime abort
1394 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1395 DiagID = diag::warn_fortify_source_size_mismatch;
1396 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1397 DestinationSize = ComputeSizeArgument(0);
1398 break;
1399 }
1400
1401 case Builtin::BImemcpy:
1402 case Builtin::BI__builtin_memcpy:
1403 case Builtin::BImemmove:
1404 case Builtin::BI__builtin_memmove:
1405 case Builtin::BImemset:
1406 case Builtin::BI__builtin_memset:
1407 case Builtin::BImempcpy:
1408 case Builtin::BI__builtin_mempcpy: {
1409 DiagID = diag::warn_fortify_source_overflow;
1410 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1411 DestinationSize = ComputeSizeArgument(0);
1412 break;
1413 }
1414 case Builtin::BIsnprintf:
1415 case Builtin::BI__builtin_snprintf:
1416 case Builtin::BIvsnprintf:
1417 case Builtin::BI__builtin_vsnprintf: {
1418 DiagID = diag::warn_fortify_source_size_mismatch;
1419 SourceSize = ComputeExplicitObjectSizeArgument(1);
1420 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1421 StringRef FormatStrRef;
1422 size_t StrLen;
1423 if (SourceSize &&
1424 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1425 EstimateSizeFormatHandler H(FormatStrRef);
1426 const char *FormatBytes = FormatStrRef.data();
1428 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1429 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1430 llvm::APSInt FormatSize =
1431 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1432 .extOrTrunc(SizeTypeWidth);
1433 if (FormatSize > *SourceSize && *SourceSize != 0) {
1434 unsigned TruncationDiagID =
1435 H.isKernelCompatible() ? diag::warn_format_truncation
1436 : diag::warn_format_truncation_non_kprintf;
1437 SmallString<16> SpecifiedSizeStr;
1438 SmallString<16> FormatSizeStr;
1439 SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1440 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1441 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1442 PDiag(TruncationDiagID)
1443 << GetFunctionName() << SpecifiedSizeStr
1444 << FormatSizeStr);
1445 }
1446 }
1447 }
1448 DestinationSize = ComputeSizeArgument(0);
1449 }
1450 }
1451
1452 if (!SourceSize || !DestinationSize ||
1453 llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1454 return;
1455
1456 std::string FunctionName = GetFunctionName();
1457
1458 SmallString<16> DestinationStr;
1459 SmallString<16> SourceStr;
1460 DestinationSize->toString(DestinationStr, /*Radix=*/10);
1461 SourceSize->toString(SourceStr, /*Radix=*/10);
1462 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1463 PDiag(DiagID)
1464 << FunctionName << DestinationStr << SourceStr);
1465}
1466
1467static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1468 Scope::ScopeFlags NeededScopeFlags,
1469 unsigned DiagID) {
1470 // Scopes aren't available during instantiation. Fortunately, builtin
1471 // functions cannot be template args so they cannot be formed through template
1472 // instantiation. Therefore checking once during the parse is sufficient.
1473 if (SemaRef.inTemplateInstantiation())
1474 return false;
1475
1476 Scope *S = SemaRef.getCurScope();
1477 while (S && !S->isSEHExceptScope())
1478 S = S->getParent();
1479 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1480 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1481 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1482 << DRE->getDecl()->getIdentifier();
1483 return true;
1484 }
1485
1486 return false;
1487}
1488
1489// In OpenCL, __builtin_alloca_* should return a pointer to address space
1490// that corresponds to the stack address space i.e private address space.
1491static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1492 QualType RT = TheCall->getType();
1493 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1494 "__builtin_alloca has invalid address space");
1495
1496 RT = RT->getPointeeType();
1498 TheCall->setType(S.Context.getPointerType(RT));
1499}
1500
1501namespace {
1502enum PointerAuthOpKind {
1503 PAO_Strip,
1504 PAO_Sign,
1505 PAO_Auth,
1506 PAO_SignGeneric,
1507 PAO_Discriminator,
1508 PAO_BlendPointer,
1509 PAO_BlendInteger
1510};
1511}
1512
1514 if (getLangOpts().PointerAuthIntrinsics)
1515 return false;
1516
1517 Diag(Loc, diag::err_ptrauth_disabled) << Range;
1518 return true;
1519}
1520
1521static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1523}
1524
1525static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1526 // Convert it to type 'int'.
1527 if (convertArgumentToType(S, Arg, S.Context.IntTy))
1528 return true;
1529
1530 // Value-dependent expressions are okay; wait for template instantiation.
1531 if (Arg->isValueDependent())
1532 return false;
1533
1534 unsigned KeyValue;
1535 return S.checkConstantPointerAuthKey(Arg, KeyValue);
1536}
1537
1539 // Attempt to constant-evaluate the expression.
1540 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
1541 if (!KeyValue) {
1542 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
1543 << 0 << Arg->getSourceRange();
1544 return true;
1545 }
1546
1547 // Ask the target to validate the key parameter.
1548 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
1550 {
1551 llvm::raw_svector_ostream Str(Value);
1552 Str << *KeyValue;
1553 }
1554
1555 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
1556 << Value << Arg->getSourceRange();
1557 return true;
1558 }
1559
1560 Result = KeyValue->getZExtValue();
1561 return false;
1562}
1563
1566 unsigned &IntVal) {
1567 if (!Arg) {
1568 IntVal = 0;
1569 return true;
1570 }
1571
1572 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
1573 if (!Result) {
1574 Diag(Arg->getExprLoc(), diag::err_ptrauth_arg_not_ice);
1575 return false;
1576 }
1577
1578 unsigned Max;
1579 bool IsAddrDiscArg = false;
1580
1581 switch (Kind) {
1583 Max = 1;
1584 IsAddrDiscArg = true;
1585 break;
1588 break;
1589 };
1590
1592 if (IsAddrDiscArg)
1593 Diag(Arg->getExprLoc(), diag::err_ptrauth_address_discrimination_invalid)
1594 << Result->getExtValue();
1595 else
1596 Diag(Arg->getExprLoc(), diag::err_ptrauth_extra_discriminator_invalid)
1597 << Result->getExtValue() << Max;
1598
1599 return false;
1600 };
1601
1602 IntVal = Result->getZExtValue();
1603 return true;
1604}
1605
1606static std::pair<const ValueDecl *, CharUnits>
1608 // Must evaluate as a pointer.
1609 Expr::EvalResult Result;
1610 if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())
1611 return {nullptr, CharUnits()};
1612
1613 const auto *BaseDecl =
1614 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1615 if (!BaseDecl)
1616 return {nullptr, CharUnits()};
1617
1618 return {BaseDecl, Result.Val.getLValueOffset()};
1619}
1620
1621static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1622 bool RequireConstant = false) {
1623 if (Arg->hasPlaceholderType()) {
1625 if (R.isInvalid())
1626 return true;
1627 Arg = R.get();
1628 }
1629
1630 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1631 return OpKind != PAO_BlendInteger;
1632 };
1633 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1634 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1635 OpKind == PAO_SignGeneric;
1636 };
1637
1638 // Require the value to have the right range of type.
1639 QualType ExpectedTy;
1640 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1641 ExpectedTy = Arg->getType().getUnqualifiedType();
1642 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1643 ExpectedTy = S.Context.VoidPtrTy;
1644 } else if (AllowsInteger(OpKind) &&
1646 ExpectedTy = S.Context.getUIntPtrType();
1647
1648 } else {
1649 // Diagnose the failures.
1650 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
1651 << unsigned(OpKind == PAO_Discriminator ? 1
1652 : OpKind == PAO_BlendPointer ? 2
1653 : OpKind == PAO_BlendInteger ? 3
1654 : 0)
1655 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1656 << Arg->getType() << Arg->getSourceRange();
1657 return true;
1658 }
1659
1660 // Convert to that type. This should just be an lvalue-to-rvalue
1661 // conversion.
1662 if (convertArgumentToType(S, Arg, ExpectedTy))
1663 return true;
1664
1665 if (!RequireConstant) {
1666 // Warn about null pointers for non-generic sign and auth operations.
1667 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1669 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
1670 ? diag::warn_ptrauth_sign_null_pointer
1671 : diag::warn_ptrauth_auth_null_pointer)
1672 << Arg->getSourceRange();
1673 }
1674
1675 return false;
1676 }
1677
1678 // Perform special checking on the arguments to ptrauth_sign_constant.
1679
1680 // The main argument.
1681 if (OpKind == PAO_Sign) {
1682 // Require the value we're signing to have a special form.
1683 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg);
1684 bool Invalid;
1685
1686 // Must be rooted in a declaration reference.
1687 if (!BaseDecl)
1688 Invalid = true;
1689
1690 // If it's a function declaration, we can't have an offset.
1691 else if (isa<FunctionDecl>(BaseDecl))
1692 Invalid = !Offset.isZero();
1693
1694 // Otherwise we're fine.
1695 else
1696 Invalid = false;
1697
1698 if (Invalid)
1699 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
1700 return Invalid;
1701 }
1702
1703 // The discriminator argument.
1704 assert(OpKind == PAO_Discriminator);
1705
1706 // Must be a pointer or integer or blend thereof.
1707 Expr *Pointer = nullptr;
1708 Expr *Integer = nullptr;
1709 if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {
1710 if (Call->getBuiltinCallee() ==
1711 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1712 Pointer = Call->getArg(0);
1713 Integer = Call->getArg(1);
1714 }
1715 }
1716 if (!Pointer && !Integer) {
1717 if (Arg->getType()->isPointerType())
1718 Pointer = Arg;
1719 else
1720 Integer = Arg;
1721 }
1722
1723 // Check the pointer.
1724 bool Invalid = false;
1725 if (Pointer) {
1726 assert(Pointer->getType()->isPointerType());
1727
1728 // TODO: if we're initializing a global, check that the address is
1729 // somehow related to what we're initializing. This probably will
1730 // never really be feasible and we'll have to catch it at link-time.
1731 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer);
1732 if (!BaseDecl || !isa<VarDecl>(BaseDecl))
1733 Invalid = true;
1734 }
1735
1736 // Check the integer.
1737 if (Integer) {
1738 assert(Integer->getType()->isIntegerType());
1739 if (!Integer->isEvaluatable(S.Context))
1740 Invalid = true;
1741 }
1742
1743 if (Invalid)
1744 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
1745 return Invalid;
1746}
1747
1749 if (S.checkArgCount(Call, 2))
1750 return ExprError();
1752 return ExprError();
1753 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
1754 checkPointerAuthKey(S, Call->getArgs()[1]))
1755 return ExprError();
1756
1757 Call->setType(Call->getArgs()[0]->getType());
1758 return Call;
1759}
1760
1762 if (S.checkArgCount(Call, 2))
1763 return ExprError();
1765 return ExprError();
1766 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
1767 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
1768 return ExprError();
1769
1770 Call->setType(S.Context.getUIntPtrType());
1771 return Call;
1772}
1773
1775 if (S.checkArgCount(Call, 2))
1776 return ExprError();
1778 return ExprError();
1779 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
1780 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
1781 return ExprError();
1782
1783 Call->setType(S.Context.getUIntPtrType());
1784 return Call;
1785}
1786
1788 PointerAuthOpKind OpKind,
1789 bool RequireConstant) {
1790 if (S.checkArgCount(Call, 3))
1791 return ExprError();
1793 return ExprError();
1794 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||
1795 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1796 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,
1797 RequireConstant))
1798 return ExprError();
1799
1800 Call->setType(Call->getArgs()[0]->getType());
1801 return Call;
1802}
1803
1805 if (S.checkArgCount(Call, 5))
1806 return ExprError();
1808 return ExprError();
1809 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1810 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1811 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1812 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1813 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
1814 return ExprError();
1815
1816 Call->setType(Call->getArgs()[0]->getType());
1817 return Call;
1818}
1819
1822 return ExprError();
1823
1824 // We've already performed normal call type-checking.
1825 const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();
1826
1827 // Operand must be an ordinary or UTF-8 string literal.
1828 const auto *Literal = dyn_cast<StringLiteral>(Arg);
1829 if (!Literal || Literal->getCharByteWidth() != 1) {
1830 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)
1831 << (Literal ? 1 : 0) << Arg->getSourceRange();
1832 return ExprError();
1833 }
1834
1835 return Call;
1836}
1837
1839 if (S.checkArgCount(Call, 1))
1840 return ExprError();
1841 Expr *FirstArg = Call->getArg(0);
1842 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(FirstArg);
1843 if (FirstValue.isInvalid())
1844 return ExprError();
1845 Call->setArg(0, FirstValue.get());
1846 QualType FirstArgType = FirstArg->getType();
1847 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
1848 FirstArgType = S.Context.getDecayedType(FirstArgType);
1849
1850 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
1851 if (!FirstArgRecord) {
1852 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1853 << /*isPolymorphic=*/0 << FirstArgType;
1854 return ExprError();
1855 }
1856 if (S.RequireCompleteType(
1857 FirstArg->getBeginLoc(), FirstArgType->getPointeeType(),
1858 diag::err_get_vtable_pointer_requires_complete_type)) {
1859 return ExprError();
1860 }
1861
1862 if (!FirstArgRecord->isPolymorphic()) {
1863 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1864 << /*isPolymorphic=*/1 << FirstArgRecord;
1865 return ExprError();
1866 }
1868 Call->setType(ReturnType);
1869 return Call;
1870}
1871
1873 if (S.checkArgCount(TheCall, 1))
1874 return ExprError();
1875
1876 // Compute __builtin_launder's parameter type from the argument.
1877 // The parameter type is:
1878 // * The type of the argument if it's not an array or function type,
1879 // Otherwise,
1880 // * The decayed argument type.
1881 QualType ParamTy = [&]() {
1882 QualType ArgTy = TheCall->getArg(0)->getType();
1883 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1884 return S.Context.getPointerType(Ty->getElementType());
1885 if (ArgTy->isFunctionType()) {
1886 return S.Context.getPointerType(ArgTy);
1887 }
1888 return ArgTy;
1889 }();
1890
1891 TheCall->setType(ParamTy);
1892
1893 auto DiagSelect = [&]() -> std::optional<unsigned> {
1894 if (!ParamTy->isPointerType())
1895 return 0;
1896 if (ParamTy->isFunctionPointerType())
1897 return 1;
1898 if (ParamTy->isVoidPointerType())
1899 return 2;
1900 return std::optional<unsigned>{};
1901 }();
1902 if (DiagSelect) {
1903 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1904 << *DiagSelect << TheCall->getSourceRange();
1905 return ExprError();
1906 }
1907
1908 // We either have an incomplete class type, or we have a class template
1909 // whose instantiation has not been forced. Example:
1910 //
1911 // template <class T> struct Foo { T value; };
1912 // Foo<int> *p = nullptr;
1913 // auto *d = __builtin_launder(p);
1914 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1915 diag::err_incomplete_type))
1916 return ExprError();
1917
1918 assert(ParamTy->getPointeeType()->isObjectType() &&
1919 "Unhandled non-object pointer case");
1920
1921 InitializedEntity Entity =
1923 ExprResult Arg =
1924 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1925 if (Arg.isInvalid())
1926 return ExprError();
1927 TheCall->setArg(0, Arg.get());
1928
1929 return TheCall;
1930}
1931
1933 if (S.checkArgCount(TheCall, 1))
1934 return ExprError();
1935
1937 if (Arg.isInvalid())
1938 return ExprError();
1939 QualType ParamTy = Arg.get()->getType();
1940 TheCall->setArg(0, Arg.get());
1941 TheCall->setType(S.Context.BoolTy);
1942
1943 // Only accept pointers to objects as arguments, which should have object
1944 // pointer or void pointer types.
1945 if (const auto *PT = ParamTy->getAs<PointerType>()) {
1946 // LWG4138: Function pointer types not allowed
1947 if (PT->getPointeeType()->isFunctionType()) {
1948 S.Diag(TheCall->getArg(0)->getExprLoc(),
1949 diag::err_builtin_is_within_lifetime_invalid_arg)
1950 << 1;
1951 return ExprError();
1952 }
1953 // Disallow VLAs too since those shouldn't be able to
1954 // be a template parameter for `std::is_within_lifetime`
1955 if (PT->getPointeeType()->isVariableArrayType()) {
1956 S.Diag(TheCall->getArg(0)->getExprLoc(), diag::err_vla_unsupported)
1957 << 1 << "__builtin_is_within_lifetime";
1958 return ExprError();
1959 }
1960 } else {
1961 S.Diag(TheCall->getArg(0)->getExprLoc(),
1962 diag::err_builtin_is_within_lifetime_invalid_arg)
1963 << 0;
1964 return ExprError();
1965 }
1966 return TheCall;
1967}
1968
1970 if (S.checkArgCount(TheCall, 3))
1971 return ExprError();
1972
1973 QualType Dest = TheCall->getArg(0)->getType();
1974 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
1975 S.Diag(TheCall->getArg(0)->getExprLoc(),
1976 diag::err_builtin_trivially_relocate_invalid_arg_type)
1977 << /*a pointer*/ 0;
1978 return ExprError();
1979 }
1980
1981 QualType T = Dest->getPointeeType();
1982 if (S.RequireCompleteType(TheCall->getBeginLoc(), T,
1983 diag::err_incomplete_type))
1984 return ExprError();
1985
1986 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
1987 T->isIncompleteArrayType()) {
1988 S.Diag(TheCall->getArg(0)->getExprLoc(),
1989 diag::err_builtin_trivially_relocate_invalid_arg_type)
1990 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
1991 return ExprError();
1992 }
1993
1994 TheCall->setType(Dest);
1995
1996 QualType Src = TheCall->getArg(1)->getType();
1997 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
1998 S.Diag(TheCall->getArg(1)->getExprLoc(),
1999 diag::err_builtin_trivially_relocate_invalid_arg_type)
2000 << /*the same*/ 3;
2001 return ExprError();
2002 }
2003
2004 Expr *SizeExpr = TheCall->getArg(2);
2005 ExprResult Size = S.DefaultLvalueConversion(SizeExpr);
2006 if (Size.isInvalid())
2007 return ExprError();
2008
2009 Size = S.tryConvertExprToType(Size.get(), S.getASTContext().getSizeType());
2010 if (Size.isInvalid())
2011 return ExprError();
2012 SizeExpr = Size.get();
2013 TheCall->setArg(2, SizeExpr);
2014
2015 return TheCall;
2016}
2017
2018// Emit an error and return true if the current object format type is in the
2019// list of unsupported types.
2021 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2022 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2023 llvm::Triple::ObjectFormatType CurObjFormat =
2024 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2025 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2026 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2027 << TheCall->getSourceRange();
2028 return true;
2029 }
2030 return false;
2031}
2032
2033// Emit an error and return true if the current architecture is not in the list
2034// of supported architectures.
2035static bool
2037 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2038 llvm::Triple::ArchType CurArch =
2039 S.getASTContext().getTargetInfo().getTriple().getArch();
2040 if (llvm::is_contained(SupportedArchs, CurArch))
2041 return false;
2042 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2043 << TheCall->getSourceRange();
2044 return true;
2045}
2046
2047static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2048 SourceLocation CallSiteLoc);
2049
2050bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2051 CallExpr *TheCall) {
2052 switch (TI.getTriple().getArch()) {
2053 default:
2054 // Some builtins don't require additional checking, so just consider these
2055 // acceptable.
2056 return false;
2057 case llvm::Triple::arm:
2058 case llvm::Triple::armeb:
2059 case llvm::Triple::thumb:
2060 case llvm::Triple::thumbeb:
2061 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2062 case llvm::Triple::aarch64:
2063 case llvm::Triple::aarch64_32:
2064 case llvm::Triple::aarch64_be:
2065 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2066 case llvm::Triple::bpfeb:
2067 case llvm::Triple::bpfel:
2068 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2069 case llvm::Triple::dxil:
2070 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2071 case llvm::Triple::hexagon:
2072 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2073 case llvm::Triple::mips:
2074 case llvm::Triple::mipsel:
2075 case llvm::Triple::mips64:
2076 case llvm::Triple::mips64el:
2077 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2078 case llvm::Triple::spirv:
2079 case llvm::Triple::spirv32:
2080 case llvm::Triple::spirv64:
2081 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2082 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2083 return false;
2084 case llvm::Triple::systemz:
2085 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2086 case llvm::Triple::x86:
2087 case llvm::Triple::x86_64:
2088 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2089 case llvm::Triple::ppc:
2090 case llvm::Triple::ppcle:
2091 case llvm::Triple::ppc64:
2092 case llvm::Triple::ppc64le:
2093 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2094 case llvm::Triple::amdgcn:
2095 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
2096 case llvm::Triple::riscv32:
2097 case llvm::Triple::riscv64:
2098 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2099 case llvm::Triple::loongarch32:
2100 case llvm::Triple::loongarch64:
2101 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2102 TheCall);
2103 case llvm::Triple::wasm32:
2104 case llvm::Triple::wasm64:
2105 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2106 case llvm::Triple::nvptx:
2107 case llvm::Triple::nvptx64:
2108 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2109 }
2110}
2111
2112// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2113// not a valid type, emit an error message and return true. Otherwise return
2114// false.
2115static bool
2118 int ArgOrdinal) {
2119 QualType EltTy = ArgTy;
2120 if (auto *VecTy = EltTy->getAs<VectorType>())
2121 EltTy = VecTy->getElementType();
2122
2123 switch (ArgTyRestr) {
2125 if (!ArgTy->getAs<VectorType>() &&
2127 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2128 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2129 << ArgTy;
2130 }
2131 break;
2133 if (!EltTy->isRealFloatingType()) {
2134 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2135 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2136 << /* floating-point */ 1 << ArgTy;
2137 }
2138 break;
2140 if (!EltTy->isIntegerType()) {
2141 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2142 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2143 << /* no fp */ 0 << ArgTy;
2144 }
2145 break;
2147 if (EltTy->isUnsignedIntegerType()) {
2148 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2149 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2150 << /* or fp */ 1 << ArgTy;
2151 }
2152 break;
2153 }
2154
2155 return false;
2156}
2157
2158/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2159/// This checks that the target supports the builtin and that the string
2160/// argument is constant and valid.
2161static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2162 const TargetInfo *AuxTI, unsigned BuiltinID) {
2163 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2164 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2165 "Expecting __builtin_cpu_...");
2166
2167 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2168 const TargetInfo *TheTI = &TI;
2169 auto SupportsBI = [=](const TargetInfo *TInfo) {
2170 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2171 (!IsCPUSupports && TInfo->supportsCpuIs()));
2172 };
2173 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2174 TheTI = AuxTI;
2175
2176 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2177 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2178 return S.Diag(TheCall->getBeginLoc(),
2179 TI.getTriple().isOSAIX()
2180 ? diag::err_builtin_aix_os_unsupported
2181 : diag::err_builtin_target_unsupported)
2182 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2183
2184 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2185 // Check if the argument is a string literal.
2186 if (!isa<StringLiteral>(Arg))
2187 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2188 << Arg->getSourceRange();
2189
2190 // Check the contents of the string.
2191 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2192 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2193 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2194 << Arg->getSourceRange();
2195 return false;
2196 }
2197 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2198 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2199 << Arg->getSourceRange();
2200 return false;
2201}
2202
2203/// Checks that __builtin_popcountg was called with a single argument, which is
2204/// an unsigned integer.
2205static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2206 if (S.checkArgCount(TheCall, 1))
2207 return true;
2208
2209 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2210 if (ArgRes.isInvalid())
2211 return true;
2212
2213 Expr *Arg = ArgRes.get();
2214 TheCall->setArg(0, Arg);
2215
2216 QualType ArgTy = Arg->getType();
2217
2218 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2219 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2220 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2221 << ArgTy;
2222 return true;
2223 }
2224 return false;
2225}
2226
2227/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2228/// an unsigned integer, and an optional second argument, which is promoted to
2229/// an 'int'.
2230static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2231 if (S.checkArgCountRange(TheCall, 1, 2))
2232 return true;
2233
2234 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2235 if (Arg0Res.isInvalid())
2236 return true;
2237
2238 Expr *Arg0 = Arg0Res.get();
2239 TheCall->setArg(0, Arg0);
2240
2241 QualType Arg0Ty = Arg0->getType();
2242
2243 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2244 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2245 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2246 << Arg0Ty;
2247 return true;
2248 }
2249
2250 if (TheCall->getNumArgs() > 1) {
2251 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2252 if (Arg1Res.isInvalid())
2253 return true;
2254
2255 Expr *Arg1 = Arg1Res.get();
2256 TheCall->setArg(1, Arg1);
2257
2258 QualType Arg1Ty = Arg1->getType();
2259
2260 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2261 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2262 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2263 return true;
2264 }
2265 }
2266
2267 return false;
2268}
2269
2270static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2271 unsigned Pos, bool AllowConst,
2272 bool AllowAS) {
2273 QualType MaskTy = MaskArg->getType();
2274 if (!MaskTy->isExtVectorBoolType())
2275 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2276 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2277 << MaskTy;
2278
2279 QualType PtrTy = PtrArg->getType();
2280 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2281 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2282 << Pos << "scalar pointer";
2283
2284 QualType PointeeTy = PtrTy->getPointeeType();
2285 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2286 (!AllowConst && PointeeTy.isConstQualified()) ||
2287 (!AllowAS && PointeeTy.hasAddressSpace())) {
2290 return S.Diag(PtrArg->getExprLoc(),
2291 diag::err_typecheck_convert_incompatible)
2292 << PtrTy << Target << /*different qualifiers=*/5
2293 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2294 << PtrTy << Target;
2295 }
2296 return false;
2297}
2298
2299static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2300 bool TypeDependent = false;
2301 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2302 ExprResult Converted =
2304 if (Converted.isInvalid())
2305 return true;
2306 TheCall->setArg(Arg, Converted.get());
2307 TypeDependent |= Converted.get()->isTypeDependent();
2308 }
2309
2310 if (TypeDependent)
2311 TheCall->setType(S.Context.DependentTy);
2312 return false;
2313}
2314
2316 if (S.checkArgCountRange(TheCall, 2, 3))
2317 return ExprError();
2318
2319 if (ConvertMaskedBuiltinArgs(S, TheCall))
2320 return ExprError();
2321
2322 Expr *MaskArg = TheCall->getArg(0);
2323 Expr *PtrArg = TheCall->getArg(1);
2324 if (TheCall->isTypeDependent())
2325 return TheCall;
2326
2327 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 2, /*AllowConst=*/true,
2328 TheCall->getBuiltinCallee() ==
2329 Builtin::BI__builtin_masked_load))
2330 return ExprError();
2331
2332 QualType MaskTy = MaskArg->getType();
2333 QualType PtrTy = PtrArg->getType();
2334 QualType PointeeTy = PtrTy->getPointeeType();
2335 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2336
2338 MaskVecTy->getNumElements());
2339 if (TheCall->getNumArgs() == 3) {
2340 Expr *PassThruArg = TheCall->getArg(2);
2341 QualType PassThruTy = PassThruArg->getType();
2342 if (!S.Context.hasSameType(PassThruTy, RetTy))
2343 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2344 << /* third argument */ 3 << RetTy;
2345 }
2346
2347 TheCall->setType(RetTy);
2348 return TheCall;
2349}
2350
2352 if (S.checkArgCount(TheCall, 3))
2353 return ExprError();
2354
2355 if (ConvertMaskedBuiltinArgs(S, TheCall))
2356 return ExprError();
2357
2358 Expr *MaskArg = TheCall->getArg(0);
2359 Expr *ValArg = TheCall->getArg(1);
2360 Expr *PtrArg = TheCall->getArg(2);
2361 if (TheCall->isTypeDependent())
2362 return TheCall;
2363
2364 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/false,
2365 TheCall->getBuiltinCallee() ==
2366 Builtin::BI__builtin_masked_store))
2367 return ExprError();
2368
2369 QualType MaskTy = MaskArg->getType();
2370 QualType PtrTy = PtrArg->getType();
2371 QualType ValTy = ValArg->getType();
2372 if (!ValTy->isVectorType())
2373 return ExprError(
2374 S.Diag(ValArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2375 << 2 << "vector");
2376
2377 QualType PointeeTy = PtrTy->getPointeeType();
2378 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2379 QualType MemoryTy = S.Context.getExtVectorType(PointeeTy.getUnqualifiedType(),
2380 MaskVecTy->getNumElements());
2381 if (!S.Context.hasSameType(ValTy.getUnqualifiedType(),
2382 MemoryTy.getUnqualifiedType()))
2383 return ExprError(S.Diag(TheCall->getBeginLoc(),
2384 diag::err_vec_builtin_incompatible_vector)
2385 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2386 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2387 TheCall->getArg(1)->getEndLoc()));
2388
2389 TheCall->setType(S.Context.VoidTy);
2390 return TheCall;
2391}
2392
2394 if (S.checkArgCountRange(TheCall, 3, 4))
2395 return ExprError();
2396
2397 if (ConvertMaskedBuiltinArgs(S, TheCall))
2398 return ExprError();
2399
2400 Expr *MaskArg = TheCall->getArg(0);
2401 Expr *IdxArg = TheCall->getArg(1);
2402 Expr *PtrArg = TheCall->getArg(2);
2403 if (TheCall->isTypeDependent())
2404 return TheCall;
2405
2406 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/true,
2407 /*AllowAS=*/true))
2408 return ExprError();
2409
2410 QualType IdxTy = IdxArg->getType();
2411 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2412 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2413 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2414 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2415 << IdxTy;
2416
2417 QualType MaskTy = MaskArg->getType();
2418 QualType PtrTy = PtrArg->getType();
2419 QualType PointeeTy = PtrTy->getPointeeType();
2420 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2421 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2422 return ExprError(
2423 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2425 TheCall->getBuiltinCallee())
2426 << MaskTy << IdxTy);
2427
2429 MaskVecTy->getNumElements());
2430 if (TheCall->getNumArgs() == 4) {
2431 Expr *PassThruArg = TheCall->getArg(3);
2432 QualType PassThruTy = PassThruArg->getType();
2433 if (!S.Context.hasSameType(PassThruTy, RetTy))
2434 return S.Diag(PassThruArg->getExprLoc(),
2435 diag::err_vec_masked_load_store_ptr)
2436 << /* fourth argument */ 4 << RetTy;
2437 }
2438
2439 TheCall->setType(RetTy);
2440 return TheCall;
2441}
2442
2444 if (S.checkArgCount(TheCall, 4))
2445 return ExprError();
2446
2447 if (ConvertMaskedBuiltinArgs(S, TheCall))
2448 return ExprError();
2449
2450 Expr *MaskArg = TheCall->getArg(0);
2451 Expr *IdxArg = TheCall->getArg(1);
2452 Expr *ValArg = TheCall->getArg(2);
2453 Expr *PtrArg = TheCall->getArg(3);
2454 if (TheCall->isTypeDependent())
2455 return TheCall;
2456
2457 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 4, /*AllowConst=*/false,
2458 /*AllowAS=*/true))
2459 return ExprError();
2460
2461 QualType IdxTy = IdxArg->getType();
2462 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2463 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2464 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2465 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2466 << IdxTy;
2467
2468 QualType ValTy = ValArg->getType();
2469 QualType MaskTy = MaskArg->getType();
2470 QualType PtrTy = PtrArg->getType();
2471 QualType PointeeTy = PtrTy->getPointeeType();
2472
2473 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2474 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2475 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2476 return ExprError(
2477 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2479 TheCall->getBuiltinCallee())
2480 << MaskTy << IdxTy);
2481 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2482 return ExprError(
2483 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2485 TheCall->getBuiltinCallee())
2486 << MaskTy << ValTy);
2487
2489 MaskVecTy->getNumElements());
2490 if (!S.Context.hasSameType(ValTy.getUnqualifiedType(), ArgTy))
2491 return ExprError(S.Diag(TheCall->getBeginLoc(),
2492 diag::err_vec_builtin_incompatible_vector)
2493 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2494 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2495 TheCall->getArg(1)->getEndLoc()));
2496
2497 TheCall->setType(S.Context.VoidTy);
2498 return TheCall;
2499}
2500
2502 SourceLocation Loc = TheCall->getBeginLoc();
2503 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2504 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2505
2506 if (Args.size() == 0) {
2507 S.Diag(TheCall->getBeginLoc(),
2508 diag::err_typecheck_call_too_few_args_at_least)
2509 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2510 << /*is_non_object=*/0 << TheCall->getSourceRange();
2511 return ExprError();
2512 }
2513
2514 QualType FuncT = Args[0]->getType();
2515
2516 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2517 if (Args.size() < 2) {
2518 S.Diag(TheCall->getBeginLoc(),
2519 diag::err_typecheck_call_too_few_args_at_least)
2520 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2521 << /*is_non_object=*/0 << TheCall->getSourceRange();
2522 return ExprError();
2523 }
2524
2525 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2526 QualType ObjectT = Args[1]->getType();
2527
2528 if (MPT->isMemberDataPointer() && S.checkArgCount(TheCall, 2))
2529 return ExprError();
2530
2531 ExprResult ObjectArg = [&]() -> ExprResult {
2532 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2533 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2534 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2535 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2536 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2537 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2538 if (S.Context.hasSameType(QualType(MemPtrClass, 0),
2539 S.BuiltinRemoveCVRef(ObjectT, Loc)) ||
2540 S.BuiltinIsBaseOf(Args[1]->getBeginLoc(), QualType(MemPtrClass, 0),
2541 S.BuiltinRemoveCVRef(ObjectT, Loc))) {
2542 return Args[1];
2543 }
2544
2545 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2546 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2547 // reference_wrapper;
2548 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2549 if (RD->isInStdNamespace() &&
2550 RD->getDeclName().getAsString() == "reference_wrapper") {
2551 CXXScopeSpec SS;
2552 IdentifierInfo *GetName = &S.Context.Idents.get("get");
2553 UnqualifiedId GetID;
2554 GetID.setIdentifier(GetName, Loc);
2555
2557 S.getCurScope(), Args[1], Loc, tok::period, SS,
2558 /*TemplateKWLoc=*/SourceLocation(), GetID, nullptr);
2559
2560 if (MemExpr.isInvalid())
2561 return ExprError();
2562
2563 return S.ActOnCallExpr(S.getCurScope(), MemExpr.get(), Loc, {}, Loc);
2564 }
2565 }
2566
2567 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
2568 // class T and t1 does not satisfy the previous two items;
2569
2570 return S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, Args[1]);
2571 }();
2572
2573 if (ObjectArg.isInvalid())
2574 return ExprError();
2575
2576 ExprResult BinOp = S.ActOnBinOp(S.getCurScope(), TheCall->getBeginLoc(),
2577 tok::periodstar, ObjectArg.get(), Args[0]);
2578 if (BinOp.isInvalid())
2579 return ExprError();
2580
2581 if (MPT->isMemberDataPointer())
2582 return BinOp;
2583
2584 auto *MemCall = new (S.Context)
2586
2587 return S.ActOnCallExpr(S.getCurScope(), MemCall, TheCall->getBeginLoc(),
2588 Args.drop_front(2), TheCall->getRParenLoc());
2589 }
2590 return S.ActOnCallExpr(S.getCurScope(), Args.front(), TheCall->getBeginLoc(),
2591 Args.drop_front(), TheCall->getRParenLoc());
2592}
2593
2595Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2596 CallExpr *TheCall) {
2597 ExprResult TheCallResult(TheCall);
2598
2599 // Find out if any arguments are required to be integer constant expressions.
2600 unsigned ICEArguments = 0;
2602 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
2604 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2605
2606 // If any arguments are required to be ICE's, check and diagnose.
2607 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2608 // Skip arguments not required to be ICE's.
2609 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2610
2611 llvm::APSInt Result;
2612 // If we don't have enough arguments, continue so we can issue better
2613 // diagnostic in checkArgCount(...)
2614 if (ArgNo < TheCall->getNumArgs() &&
2615 BuiltinConstantArg(TheCall, ArgNo, Result))
2616 return true;
2617 ICEArguments &= ~(1 << ArgNo);
2618 }
2619
2620 FPOptions FPO;
2621 switch (BuiltinID) {
2622 case Builtin::BI__builtin_cpu_supports:
2623 case Builtin::BI__builtin_cpu_is:
2624 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
2625 Context.getAuxTargetInfo(), BuiltinID))
2626 return ExprError();
2627 break;
2628 case Builtin::BI__builtin_cpu_init:
2629 if (!Context.getTargetInfo().supportsCpuInit()) {
2630 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2631 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2632 return ExprError();
2633 }
2634 break;
2635 case Builtin::BI__builtin___CFStringMakeConstantString:
2636 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2637 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2639 *this, BuiltinID, TheCall,
2640 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2641 return ExprError();
2642 assert(TheCall->getNumArgs() == 1 &&
2643 "Wrong # arguments to builtin CFStringMakeConstantString");
2644 if (ObjC().CheckObjCString(TheCall->getArg(0)))
2645 return ExprError();
2646 break;
2647 case Builtin::BI__builtin_ms_va_start:
2648 case Builtin::BI__builtin_stdarg_start:
2649 case Builtin::BI__builtin_va_start:
2650 case Builtin::BI__builtin_c23_va_start:
2651 if (BuiltinVAStart(BuiltinID, TheCall))
2652 return ExprError();
2653 break;
2654 case Builtin::BI__va_start: {
2655 switch (Context.getTargetInfo().getTriple().getArch()) {
2656 case llvm::Triple::aarch64:
2657 case llvm::Triple::arm:
2658 case llvm::Triple::thumb:
2659 if (BuiltinVAStartARMMicrosoft(TheCall))
2660 return ExprError();
2661 break;
2662 default:
2663 if (BuiltinVAStart(BuiltinID, TheCall))
2664 return ExprError();
2665 break;
2666 }
2667 break;
2668 }
2669
2670 // The acquire, release, and no fence variants are ARM and AArch64 only.
2671 case Builtin::BI_interlockedbittestandset_acq:
2672 case Builtin::BI_interlockedbittestandset_rel:
2673 case Builtin::BI_interlockedbittestandset_nf:
2674 case Builtin::BI_interlockedbittestandreset_acq:
2675 case Builtin::BI_interlockedbittestandreset_rel:
2676 case Builtin::BI_interlockedbittestandreset_nf:
2678 *this, TheCall,
2679 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2680 return ExprError();
2681 break;
2682
2683 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2684 case Builtin::BI_bittest64:
2685 case Builtin::BI_bittestandcomplement64:
2686 case Builtin::BI_bittestandreset64:
2687 case Builtin::BI_bittestandset64:
2688 case Builtin::BI_interlockedbittestandreset64:
2689 case Builtin::BI_interlockedbittestandset64:
2691 *this, TheCall,
2692 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
2693 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2694 return ExprError();
2695 break;
2696
2697 // The 64-bit acquire, release, and no fence variants are AArch64 only.
2698 case Builtin::BI_interlockedbittestandreset64_acq:
2699 case Builtin::BI_interlockedbittestandreset64_rel:
2700 case Builtin::BI_interlockedbittestandreset64_nf:
2701 case Builtin::BI_interlockedbittestandset64_acq:
2702 case Builtin::BI_interlockedbittestandset64_rel:
2703 case Builtin::BI_interlockedbittestandset64_nf:
2704 if (CheckBuiltinTargetInSupported(*this, TheCall, {llvm::Triple::aarch64}))
2705 return ExprError();
2706 break;
2707
2708 case Builtin::BI__builtin_set_flt_rounds:
2710 *this, TheCall,
2711 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
2712 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn,
2713 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
2714 llvm::Triple::ppc64le}))
2715 return ExprError();
2716 break;
2717
2718 case Builtin::BI__builtin_isgreater:
2719 case Builtin::BI__builtin_isgreaterequal:
2720 case Builtin::BI__builtin_isless:
2721 case Builtin::BI__builtin_islessequal:
2722 case Builtin::BI__builtin_islessgreater:
2723 case Builtin::BI__builtin_isunordered:
2724 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
2725 return ExprError();
2726 break;
2727 case Builtin::BI__builtin_fpclassify:
2728 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
2729 return ExprError();
2730 break;
2731 case Builtin::BI__builtin_isfpclass:
2732 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
2733 return ExprError();
2734 break;
2735 case Builtin::BI__builtin_isfinite:
2736 case Builtin::BI__builtin_isinf:
2737 case Builtin::BI__builtin_isinf_sign:
2738 case Builtin::BI__builtin_isnan:
2739 case Builtin::BI__builtin_issignaling:
2740 case Builtin::BI__builtin_isnormal:
2741 case Builtin::BI__builtin_issubnormal:
2742 case Builtin::BI__builtin_iszero:
2743 case Builtin::BI__builtin_signbit:
2744 case Builtin::BI__builtin_signbitf:
2745 case Builtin::BI__builtin_signbitl:
2746 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
2747 return ExprError();
2748 break;
2749 case Builtin::BI__builtin_shufflevector:
2750 return BuiltinShuffleVector(TheCall);
2751 // TheCall will be freed by the smart pointer here, but that's fine, since
2752 // BuiltinShuffleVector guts it, but then doesn't release it.
2753 case Builtin::BI__builtin_masked_load:
2754 case Builtin::BI__builtin_masked_expand_load:
2755 return BuiltinMaskedLoad(*this, TheCall);
2756 case Builtin::BI__builtin_masked_store:
2757 case Builtin::BI__builtin_masked_compress_store:
2758 return BuiltinMaskedStore(*this, TheCall);
2759 case Builtin::BI__builtin_masked_gather:
2760 return BuiltinMaskedGather(*this, TheCall);
2761 case Builtin::BI__builtin_masked_scatter:
2762 return BuiltinMaskedScatter(*this, TheCall);
2763 case Builtin::BI__builtin_invoke:
2764 return BuiltinInvoke(*this, TheCall);
2765 case Builtin::BI__builtin_prefetch:
2766 if (BuiltinPrefetch(TheCall))
2767 return ExprError();
2768 break;
2769 case Builtin::BI__builtin_alloca_with_align:
2770 case Builtin::BI__builtin_alloca_with_align_uninitialized:
2771 if (BuiltinAllocaWithAlign(TheCall))
2772 return ExprError();
2773 [[fallthrough]];
2774 case Builtin::BI__builtin_alloca:
2775 case Builtin::BI__builtin_alloca_uninitialized:
2776 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
2777 << TheCall->getDirectCallee();
2778 if (getLangOpts().OpenCL) {
2779 builtinAllocaAddrSpace(*this, TheCall);
2780 }
2781 break;
2782 case Builtin::BI__arithmetic_fence:
2783 if (BuiltinArithmeticFence(TheCall))
2784 return ExprError();
2785 break;
2786 case Builtin::BI__assume:
2787 case Builtin::BI__builtin_assume:
2788 if (BuiltinAssume(TheCall))
2789 return ExprError();
2790 break;
2791 case Builtin::BI__builtin_assume_aligned:
2792 if (BuiltinAssumeAligned(TheCall))
2793 return ExprError();
2794 break;
2795 case Builtin::BI__builtin_dynamic_object_size:
2796 case Builtin::BI__builtin_object_size:
2797 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
2798 return ExprError();
2799 break;
2800 case Builtin::BI__builtin_longjmp:
2801 if (BuiltinLongjmp(TheCall))
2802 return ExprError();
2803 break;
2804 case Builtin::BI__builtin_setjmp:
2805 if (BuiltinSetjmp(TheCall))
2806 return ExprError();
2807 break;
2808 case Builtin::BI__builtin_classify_type:
2809 if (checkArgCount(TheCall, 1))
2810 return true;
2811 TheCall->setType(Context.IntTy);
2812 break;
2813 case Builtin::BI__builtin_complex:
2814 if (BuiltinComplex(TheCall))
2815 return ExprError();
2816 break;
2817 case Builtin::BI__builtin_constant_p: {
2818 if (checkArgCount(TheCall, 1))
2819 return true;
2821 if (Arg.isInvalid()) return true;
2822 TheCall->setArg(0, Arg.get());
2823 TheCall->setType(Context.IntTy);
2824 break;
2825 }
2826 case Builtin::BI__builtin_launder:
2827 return BuiltinLaunder(*this, TheCall);
2828 case Builtin::BI__builtin_is_within_lifetime:
2829 return BuiltinIsWithinLifetime(*this, TheCall);
2830 case Builtin::BI__builtin_trivially_relocate:
2831 return BuiltinTriviallyRelocate(*this, TheCall);
2832
2833 case Builtin::BI__sync_fetch_and_add:
2834 case Builtin::BI__sync_fetch_and_add_1:
2835 case Builtin::BI__sync_fetch_and_add_2:
2836 case Builtin::BI__sync_fetch_and_add_4:
2837 case Builtin::BI__sync_fetch_and_add_8:
2838 case Builtin::BI__sync_fetch_and_add_16:
2839 case Builtin::BI__sync_fetch_and_sub:
2840 case Builtin::BI__sync_fetch_and_sub_1:
2841 case Builtin::BI__sync_fetch_and_sub_2:
2842 case Builtin::BI__sync_fetch_and_sub_4:
2843 case Builtin::BI__sync_fetch_and_sub_8:
2844 case Builtin::BI__sync_fetch_and_sub_16:
2845 case Builtin::BI__sync_fetch_and_or:
2846 case Builtin::BI__sync_fetch_and_or_1:
2847 case Builtin::BI__sync_fetch_and_or_2:
2848 case Builtin::BI__sync_fetch_and_or_4:
2849 case Builtin::BI__sync_fetch_and_or_8:
2850 case Builtin::BI__sync_fetch_and_or_16:
2851 case Builtin::BI__sync_fetch_and_and:
2852 case Builtin::BI__sync_fetch_and_and_1:
2853 case Builtin::BI__sync_fetch_and_and_2:
2854 case Builtin::BI__sync_fetch_and_and_4:
2855 case Builtin::BI__sync_fetch_and_and_8:
2856 case Builtin::BI__sync_fetch_and_and_16:
2857 case Builtin::BI__sync_fetch_and_xor:
2858 case Builtin::BI__sync_fetch_and_xor_1:
2859 case Builtin::BI__sync_fetch_and_xor_2:
2860 case Builtin::BI__sync_fetch_and_xor_4:
2861 case Builtin::BI__sync_fetch_and_xor_8:
2862 case Builtin::BI__sync_fetch_and_xor_16:
2863 case Builtin::BI__sync_fetch_and_nand:
2864 case Builtin::BI__sync_fetch_and_nand_1:
2865 case Builtin::BI__sync_fetch_and_nand_2:
2866 case Builtin::BI__sync_fetch_and_nand_4:
2867 case Builtin::BI__sync_fetch_and_nand_8:
2868 case Builtin::BI__sync_fetch_and_nand_16:
2869 case Builtin::BI__sync_add_and_fetch:
2870 case Builtin::BI__sync_add_and_fetch_1:
2871 case Builtin::BI__sync_add_and_fetch_2:
2872 case Builtin::BI__sync_add_and_fetch_4:
2873 case Builtin::BI__sync_add_and_fetch_8:
2874 case Builtin::BI__sync_add_and_fetch_16:
2875 case Builtin::BI__sync_sub_and_fetch:
2876 case Builtin::BI__sync_sub_and_fetch_1:
2877 case Builtin::BI__sync_sub_and_fetch_2:
2878 case Builtin::BI__sync_sub_and_fetch_4:
2879 case Builtin::BI__sync_sub_and_fetch_8:
2880 case Builtin::BI__sync_sub_and_fetch_16:
2881 case Builtin::BI__sync_and_and_fetch:
2882 case Builtin::BI__sync_and_and_fetch_1:
2883 case Builtin::BI__sync_and_and_fetch_2:
2884 case Builtin::BI__sync_and_and_fetch_4:
2885 case Builtin::BI__sync_and_and_fetch_8:
2886 case Builtin::BI__sync_and_and_fetch_16:
2887 case Builtin::BI__sync_or_and_fetch:
2888 case Builtin::BI__sync_or_and_fetch_1:
2889 case Builtin::BI__sync_or_and_fetch_2:
2890 case Builtin::BI__sync_or_and_fetch_4:
2891 case Builtin::BI__sync_or_and_fetch_8:
2892 case Builtin::BI__sync_or_and_fetch_16:
2893 case Builtin::BI__sync_xor_and_fetch:
2894 case Builtin::BI__sync_xor_and_fetch_1:
2895 case Builtin::BI__sync_xor_and_fetch_2:
2896 case Builtin::BI__sync_xor_and_fetch_4:
2897 case Builtin::BI__sync_xor_and_fetch_8:
2898 case Builtin::BI__sync_xor_and_fetch_16:
2899 case Builtin::BI__sync_nand_and_fetch:
2900 case Builtin::BI__sync_nand_and_fetch_1:
2901 case Builtin::BI__sync_nand_and_fetch_2:
2902 case Builtin::BI__sync_nand_and_fetch_4:
2903 case Builtin::BI__sync_nand_and_fetch_8:
2904 case Builtin::BI__sync_nand_and_fetch_16:
2905 case Builtin::BI__sync_val_compare_and_swap:
2906 case Builtin::BI__sync_val_compare_and_swap_1:
2907 case Builtin::BI__sync_val_compare_and_swap_2:
2908 case Builtin::BI__sync_val_compare_and_swap_4:
2909 case Builtin::BI__sync_val_compare_and_swap_8:
2910 case Builtin::BI__sync_val_compare_and_swap_16:
2911 case Builtin::BI__sync_bool_compare_and_swap:
2912 case Builtin::BI__sync_bool_compare_and_swap_1:
2913 case Builtin::BI__sync_bool_compare_and_swap_2:
2914 case Builtin::BI__sync_bool_compare_and_swap_4:
2915 case Builtin::BI__sync_bool_compare_and_swap_8:
2916 case Builtin::BI__sync_bool_compare_and_swap_16:
2917 case Builtin::BI__sync_lock_test_and_set:
2918 case Builtin::BI__sync_lock_test_and_set_1:
2919 case Builtin::BI__sync_lock_test_and_set_2:
2920 case Builtin::BI__sync_lock_test_and_set_4:
2921 case Builtin::BI__sync_lock_test_and_set_8:
2922 case Builtin::BI__sync_lock_test_and_set_16:
2923 case Builtin::BI__sync_lock_release:
2924 case Builtin::BI__sync_lock_release_1:
2925 case Builtin::BI__sync_lock_release_2:
2926 case Builtin::BI__sync_lock_release_4:
2927 case Builtin::BI__sync_lock_release_8:
2928 case Builtin::BI__sync_lock_release_16:
2929 case Builtin::BI__sync_swap:
2930 case Builtin::BI__sync_swap_1:
2931 case Builtin::BI__sync_swap_2:
2932 case Builtin::BI__sync_swap_4:
2933 case Builtin::BI__sync_swap_8:
2934 case Builtin::BI__sync_swap_16:
2935 return BuiltinAtomicOverloaded(TheCallResult);
2936 case Builtin::BI__sync_synchronize:
2937 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
2938 << TheCall->getCallee()->getSourceRange();
2939 break;
2940 case Builtin::BI__builtin_nontemporal_load:
2941 case Builtin::BI__builtin_nontemporal_store:
2942 return BuiltinNontemporalOverloaded(TheCallResult);
2943 case Builtin::BI__builtin_memcpy_inline: {
2944 clang::Expr *SizeOp = TheCall->getArg(2);
2945 // We warn about copying to or from `nullptr` pointers when `size` is
2946 // greater than 0. When `size` is value dependent we cannot evaluate its
2947 // value so we bail out.
2948 if (SizeOp->isValueDependent())
2949 break;
2950 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
2951 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2952 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
2953 }
2954 break;
2955 }
2956 case Builtin::BI__builtin_memset_inline: {
2957 clang::Expr *SizeOp = TheCall->getArg(2);
2958 // We warn about filling to `nullptr` pointers when `size` is greater than
2959 // 0. When `size` is value dependent we cannot evaluate its value so we bail
2960 // out.
2961 if (SizeOp->isValueDependent())
2962 break;
2963 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
2964 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2965 break;
2966 }
2967#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
2968 case Builtin::BI##ID: \
2969 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
2970#include "clang/Basic/Builtins.inc"
2971 case Builtin::BI__annotation:
2972 if (BuiltinMSVCAnnotation(*this, TheCall))
2973 return ExprError();
2974 break;
2975 case Builtin::BI__builtin_annotation:
2976 if (BuiltinAnnotation(*this, TheCall))
2977 return ExprError();
2978 break;
2979 case Builtin::BI__builtin_addressof:
2980 if (BuiltinAddressof(*this, TheCall))
2981 return ExprError();
2982 break;
2983 case Builtin::BI__builtin_function_start:
2984 if (BuiltinFunctionStart(*this, TheCall))
2985 return ExprError();
2986 break;
2987 case Builtin::BI__builtin_is_aligned:
2988 case Builtin::BI__builtin_align_up:
2989 case Builtin::BI__builtin_align_down:
2990 if (BuiltinAlignment(*this, TheCall, BuiltinID))
2991 return ExprError();
2992 break;
2993 case Builtin::BI__builtin_add_overflow:
2994 case Builtin::BI__builtin_sub_overflow:
2995 case Builtin::BI__builtin_mul_overflow:
2996 if (BuiltinOverflow(*this, TheCall, BuiltinID))
2997 return ExprError();
2998 break;
2999 case Builtin::BI__builtin_operator_new:
3000 case Builtin::BI__builtin_operator_delete: {
3001 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3002 ExprResult Res =
3003 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3004 return Res;
3005 }
3006 case Builtin::BI__builtin_dump_struct:
3007 return BuiltinDumpStruct(*this, TheCall);
3008 case Builtin::BI__builtin_expect_with_probability: {
3009 // We first want to ensure we are called with 3 arguments
3010 if (checkArgCount(TheCall, 3))
3011 return ExprError();
3012 // then check probability is constant float in range [0.0, 1.0]
3013 const Expr *ProbArg = TheCall->getArg(2);
3014 SmallVector<PartialDiagnosticAt, 8> Notes;
3015 Expr::EvalResult Eval;
3016 Eval.Diag = &Notes;
3017 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
3018 !Eval.Val.isFloat()) {
3019 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
3020 << ProbArg->getSourceRange();
3021 for (const PartialDiagnosticAt &PDiag : Notes)
3022 Diag(PDiag.first, PDiag.second);
3023 return ExprError();
3024 }
3025 llvm::APFloat Probability = Eval.Val.getFloat();
3026 bool LoseInfo = false;
3027 Probability.convert(llvm::APFloat::IEEEdouble(),
3028 llvm::RoundingMode::Dynamic, &LoseInfo);
3029 if (!(Probability >= llvm::APFloat(0.0) &&
3030 Probability <= llvm::APFloat(1.0))) {
3031 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
3032 << ProbArg->getSourceRange();
3033 return ExprError();
3034 }
3035 break;
3036 }
3037 case Builtin::BI__builtin_preserve_access_index:
3038 if (BuiltinPreserveAI(*this, TheCall))
3039 return ExprError();
3040 break;
3041 case Builtin::BI__builtin_call_with_static_chain:
3042 if (BuiltinCallWithStaticChain(*this, TheCall))
3043 return ExprError();
3044 break;
3045 case Builtin::BI__exception_code:
3046 case Builtin::BI_exception_code:
3047 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
3048 diag::err_seh___except_block))
3049 return ExprError();
3050 break;
3051 case Builtin::BI__exception_info:
3052 case Builtin::BI_exception_info:
3053 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
3054 diag::err_seh___except_filter))
3055 return ExprError();
3056 break;
3057 case Builtin::BI__GetExceptionInfo:
3058 if (checkArgCount(TheCall, 1))
3059 return ExprError();
3060
3062 TheCall->getBeginLoc(),
3063 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
3064 TheCall))
3065 return ExprError();
3066
3067 TheCall->setType(Context.VoidPtrTy);
3068 break;
3069 case Builtin::BIaddressof:
3070 case Builtin::BI__addressof:
3071 case Builtin::BIforward:
3072 case Builtin::BIforward_like:
3073 case Builtin::BImove:
3074 case Builtin::BImove_if_noexcept:
3075 case Builtin::BIas_const: {
3076 // These are all expected to be of the form
3077 // T &/&&/* f(U &/&&)
3078 // where T and U only differ in qualification.
3079 if (checkArgCount(TheCall, 1))
3080 return ExprError();
3081 QualType Param = FDecl->getParamDecl(0)->getType();
3082 QualType Result = FDecl->getReturnType();
3083 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3084 BuiltinID == Builtin::BI__addressof;
3085 if (!(Param->isReferenceType() &&
3086 (ReturnsPointer ? Result->isAnyPointerType()
3087 : Result->isReferenceType()) &&
3088 Context.hasSameUnqualifiedType(Param->getPointeeType(),
3089 Result->getPointeeType()))) {
3090 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
3091 << FDecl;
3092 return ExprError();
3093 }
3094 break;
3095 }
3096 case Builtin::BI__builtin_ptrauth_strip:
3097 return PointerAuthStrip(*this, TheCall);
3098 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3099 return PointerAuthBlendDiscriminator(*this, TheCall);
3100 case Builtin::BI__builtin_ptrauth_sign_constant:
3101 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3102 /*RequireConstant=*/true);
3103 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3104 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3105 /*RequireConstant=*/false);
3106 case Builtin::BI__builtin_ptrauth_auth:
3107 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
3108 /*RequireConstant=*/false);
3109 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3110 return PointerAuthSignGenericData(*this, TheCall);
3111 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3112 return PointerAuthAuthAndResign(*this, TheCall);
3113 case Builtin::BI__builtin_ptrauth_string_discriminator:
3114 return PointerAuthStringDiscriminator(*this, TheCall);
3115
3116 case Builtin::BI__builtin_get_vtable_pointer:
3117 return GetVTablePointer(*this, TheCall);
3118
3119 // OpenCL v2.0, s6.13.16 - Pipe functions
3120 case Builtin::BIread_pipe:
3121 case Builtin::BIwrite_pipe:
3122 // Since those two functions are declared with var args, we need a semantic
3123 // check for the argument.
3124 if (OpenCL().checkBuiltinRWPipe(TheCall))
3125 return ExprError();
3126 break;
3127 case Builtin::BIreserve_read_pipe:
3128 case Builtin::BIreserve_write_pipe:
3129 case Builtin::BIwork_group_reserve_read_pipe:
3130 case Builtin::BIwork_group_reserve_write_pipe:
3131 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
3132 return ExprError();
3133 break;
3134 case Builtin::BIsub_group_reserve_read_pipe:
3135 case Builtin::BIsub_group_reserve_write_pipe:
3136 if (OpenCL().checkSubgroupExt(TheCall) ||
3137 OpenCL().checkBuiltinReserveRWPipe(TheCall))
3138 return ExprError();
3139 break;
3140 case Builtin::BIcommit_read_pipe:
3141 case Builtin::BIcommit_write_pipe:
3142 case Builtin::BIwork_group_commit_read_pipe:
3143 case Builtin::BIwork_group_commit_write_pipe:
3144 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
3145 return ExprError();
3146 break;
3147 case Builtin::BIsub_group_commit_read_pipe:
3148 case Builtin::BIsub_group_commit_write_pipe:
3149 if (OpenCL().checkSubgroupExt(TheCall) ||
3150 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3151 return ExprError();
3152 break;
3153 case Builtin::BIget_pipe_num_packets:
3154 case Builtin::BIget_pipe_max_packets:
3155 if (OpenCL().checkBuiltinPipePackets(TheCall))
3156 return ExprError();
3157 break;
3158 case Builtin::BIto_global:
3159 case Builtin::BIto_local:
3160 case Builtin::BIto_private:
3161 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3162 return ExprError();
3163 break;
3164 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3165 case Builtin::BIenqueue_kernel:
3166 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3167 return ExprError();
3168 break;
3169 case Builtin::BIget_kernel_work_group_size:
3170 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3171 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3172 return ExprError();
3173 break;
3174 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3175 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3176 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3177 return ExprError();
3178 break;
3179 case Builtin::BI__builtin_os_log_format:
3180 Cleanup.setExprNeedsCleanups(true);
3181 [[fallthrough]];
3182 case Builtin::BI__builtin_os_log_format_buffer_size:
3183 if (BuiltinOSLogFormat(TheCall))
3184 return ExprError();
3185 break;
3186 case Builtin::BI__builtin_frame_address:
3187 case Builtin::BI__builtin_return_address: {
3188 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3189 return ExprError();
3190
3191 // -Wframe-address warning if non-zero passed to builtin
3192 // return/frame address.
3193 Expr::EvalResult Result;
3194 if (!TheCall->getArg(0)->isValueDependent() &&
3195 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3196 Result.Val.getInt() != 0)
3197 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3198 << ((BuiltinID == Builtin::BI__builtin_return_address)
3199 ? "__builtin_return_address"
3200 : "__builtin_frame_address")
3201 << TheCall->getSourceRange();
3202 break;
3203 }
3204
3205 case Builtin::BI__builtin_nondeterministic_value: {
3206 if (BuiltinNonDeterministicValue(TheCall))
3207 return ExprError();
3208 break;
3209 }
3210
3211 // __builtin_elementwise_abs restricts the element type to signed integers or
3212 // floating point types only.
3213 case Builtin::BI__builtin_elementwise_abs:
3216 return ExprError();
3217 break;
3218
3219 // These builtins restrict the element type to floating point
3220 // types only.
3221 case Builtin::BI__builtin_elementwise_acos:
3222 case Builtin::BI__builtin_elementwise_asin:
3223 case Builtin::BI__builtin_elementwise_atan:
3224 case Builtin::BI__builtin_elementwise_ceil:
3225 case Builtin::BI__builtin_elementwise_cos:
3226 case Builtin::BI__builtin_elementwise_cosh:
3227 case Builtin::BI__builtin_elementwise_exp:
3228 case Builtin::BI__builtin_elementwise_exp2:
3229 case Builtin::BI__builtin_elementwise_exp10:
3230 case Builtin::BI__builtin_elementwise_floor:
3231 case Builtin::BI__builtin_elementwise_log:
3232 case Builtin::BI__builtin_elementwise_log2:
3233 case Builtin::BI__builtin_elementwise_log10:
3234 case Builtin::BI__builtin_elementwise_roundeven:
3235 case Builtin::BI__builtin_elementwise_round:
3236 case Builtin::BI__builtin_elementwise_rint:
3237 case Builtin::BI__builtin_elementwise_nearbyint:
3238 case Builtin::BI__builtin_elementwise_sin:
3239 case Builtin::BI__builtin_elementwise_sinh:
3240 case Builtin::BI__builtin_elementwise_sqrt:
3241 case Builtin::BI__builtin_elementwise_tan:
3242 case Builtin::BI__builtin_elementwise_tanh:
3243 case Builtin::BI__builtin_elementwise_trunc:
3244 case Builtin::BI__builtin_elementwise_canonicalize:
3247 return ExprError();
3248 break;
3249 case Builtin::BI__builtin_elementwise_fma:
3250 if (BuiltinElementwiseTernaryMath(TheCall))
3251 return ExprError();
3252 break;
3253
3254 // These builtins restrict the element type to floating point
3255 // types only, and take in two arguments.
3256 case Builtin::BI__builtin_elementwise_minnum:
3257 case Builtin::BI__builtin_elementwise_maxnum:
3258 case Builtin::BI__builtin_elementwise_minimum:
3259 case Builtin::BI__builtin_elementwise_maximum:
3260 case Builtin::BI__builtin_elementwise_minimumnum:
3261 case Builtin::BI__builtin_elementwise_maximumnum:
3262 case Builtin::BI__builtin_elementwise_atan2:
3263 case Builtin::BI__builtin_elementwise_fmod:
3264 case Builtin::BI__builtin_elementwise_pow:
3265 if (BuiltinElementwiseMath(TheCall,
3267 return ExprError();
3268 break;
3269 // These builtins restrict the element type to integer
3270 // types only.
3271 case Builtin::BI__builtin_elementwise_add_sat:
3272 case Builtin::BI__builtin_elementwise_sub_sat:
3273 if (BuiltinElementwiseMath(TheCall,
3275 return ExprError();
3276 break;
3277 case Builtin::BI__builtin_elementwise_fshl:
3278 case Builtin::BI__builtin_elementwise_fshr:
3281 return ExprError();
3282 break;
3283 case Builtin::BI__builtin_elementwise_min:
3284 case Builtin::BI__builtin_elementwise_max:
3285 if (BuiltinElementwiseMath(TheCall))
3286 return ExprError();
3287 break;
3288 case Builtin::BI__builtin_elementwise_popcount:
3289 case Builtin::BI__builtin_elementwise_bitreverse:
3292 return ExprError();
3293 break;
3294 case Builtin::BI__builtin_elementwise_copysign: {
3295 if (checkArgCount(TheCall, 2))
3296 return ExprError();
3297
3298 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
3299 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
3300 if (Magnitude.isInvalid() || Sign.isInvalid())
3301 return ExprError();
3302
3303 QualType MagnitudeTy = Magnitude.get()->getType();
3304 QualType SignTy = Sign.get()->getType();
3306 *this, TheCall->getArg(0)->getBeginLoc(), MagnitudeTy,
3309 *this, TheCall->getArg(1)->getBeginLoc(), SignTy,
3311 return ExprError();
3312 }
3313
3314 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3315 return Diag(Sign.get()->getBeginLoc(),
3316 diag::err_typecheck_call_different_arg_types)
3317 << MagnitudeTy << SignTy;
3318 }
3319
3320 TheCall->setArg(0, Magnitude.get());
3321 TheCall->setArg(1, Sign.get());
3322 TheCall->setType(Magnitude.get()->getType());
3323 break;
3324 }
3325 case Builtin::BI__builtin_elementwise_clzg:
3326 case Builtin::BI__builtin_elementwise_ctzg:
3327 // These builtins can be unary or binary. Note for empty calls we call the
3328 // unary checker in order to not emit an error that says the function
3329 // expects 2 arguments, which would be misleading.
3330 if (TheCall->getNumArgs() <= 1) {
3333 return ExprError();
3334 } else if (BuiltinElementwiseMath(
3336 return ExprError();
3337 break;
3338 case Builtin::BI__builtin_reduce_max:
3339 case Builtin::BI__builtin_reduce_min: {
3340 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3341 return ExprError();
3342
3343 const Expr *Arg = TheCall->getArg(0);
3344 const auto *TyA = Arg->getType()->getAs<VectorType>();
3345
3346 QualType ElTy;
3347 if (TyA)
3348 ElTy = TyA->getElementType();
3349 else if (Arg->getType()->isSizelessVectorType())
3351
3352 if (ElTy.isNull()) {
3353 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3354 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3355 << Arg->getType();
3356 return ExprError();
3357 }
3358
3359 TheCall->setType(ElTy);
3360 break;
3361 }
3362 case Builtin::BI__builtin_reduce_maximum:
3363 case Builtin::BI__builtin_reduce_minimum: {
3364 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3365 return ExprError();
3366
3367 const Expr *Arg = TheCall->getArg(0);
3368 const auto *TyA = Arg->getType()->getAs<VectorType>();
3369
3370 QualType ElTy;
3371 if (TyA)
3372 ElTy = TyA->getElementType();
3373 else if (Arg->getType()->isSizelessVectorType())
3375
3376 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3377 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3378 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3379 << Arg->getType();
3380 return ExprError();
3381 }
3382
3383 TheCall->setType(ElTy);
3384 break;
3385 }
3386
3387 // These builtins support vectors of integers only.
3388 // TODO: ADD/MUL should support floating-point types.
3389 case Builtin::BI__builtin_reduce_add:
3390 case Builtin::BI__builtin_reduce_mul:
3391 case Builtin::BI__builtin_reduce_xor:
3392 case Builtin::BI__builtin_reduce_or:
3393 case Builtin::BI__builtin_reduce_and: {
3394 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3395 return ExprError();
3396
3397 const Expr *Arg = TheCall->getArg(0);
3398 const auto *TyA = Arg->getType()->getAs<VectorType>();
3399
3400 QualType ElTy;
3401 if (TyA)
3402 ElTy = TyA->getElementType();
3403 else if (Arg->getType()->isSizelessVectorType())
3405
3406 if (ElTy.isNull() || !ElTy->isIntegerType()) {
3407 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3408 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
3409 << Arg->getType();
3410 return ExprError();
3411 }
3412
3413 TheCall->setType(ElTy);
3414 break;
3415 }
3416
3417 case Builtin::BI__builtin_matrix_transpose:
3418 return BuiltinMatrixTranspose(TheCall, TheCallResult);
3419
3420 case Builtin::BI__builtin_matrix_column_major_load:
3421 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
3422
3423 case Builtin::BI__builtin_matrix_column_major_store:
3424 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
3425
3426 case Builtin::BI__builtin_verbose_trap:
3427 if (!checkBuiltinVerboseTrap(TheCall, *this))
3428 return ExprError();
3429 break;
3430
3431 case Builtin::BI__builtin_get_device_side_mangled_name: {
3432 auto Check = [](CallExpr *TheCall) {
3433 if (TheCall->getNumArgs() != 1)
3434 return false;
3435 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
3436 if (!DRE)
3437 return false;
3438 auto *D = DRE->getDecl();
3439 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
3440 return false;
3441 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3442 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
3443 };
3444 if (!Check(TheCall)) {
3445 Diag(TheCall->getBeginLoc(),
3446 diag::err_hip_invalid_args_builtin_mangled_name);
3447 return ExprError();
3448 }
3449 break;
3450 }
3451 case Builtin::BI__builtin_popcountg:
3452 if (BuiltinPopcountg(*this, TheCall))
3453 return ExprError();
3454 break;
3455 case Builtin::BI__builtin_clzg:
3456 case Builtin::BI__builtin_ctzg:
3457 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
3458 return ExprError();
3459 break;
3460
3461 case Builtin::BI__builtin_allow_runtime_check: {
3462 Expr *Arg = TheCall->getArg(0);
3463 // Check if the argument is a string literal.
3465 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3466 << Arg->getSourceRange();
3467 return ExprError();
3468 }
3469 break;
3470 }
3471 case Builtin::BI__builtin_counted_by_ref:
3472 if (BuiltinCountedByRef(TheCall))
3473 return ExprError();
3474 break;
3475 }
3476
3477 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
3478 return ExprError();
3479
3480 // Since the target specific builtins for each arch overlap, only check those
3481 // of the arch we are compiling for.
3482 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
3483 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
3484 assert(Context.getAuxTargetInfo() &&
3485 "Aux Target Builtin, but not an aux target?");
3486
3487 if (CheckTSBuiltinFunctionCall(
3488 *Context.getAuxTargetInfo(),
3489 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
3490 return ExprError();
3491 } else {
3492 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
3493 TheCall))
3494 return ExprError();
3495 }
3496 }
3497
3498 return TheCallResult;
3499}
3500
3501bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3502 llvm::APSInt Result;
3503 // We can't check the value of a dependent argument.
3504 Expr *Arg = TheCall->getArg(ArgNum);
3505 if (Arg->isTypeDependent() || Arg->isValueDependent())
3506 return false;
3507
3508 // Check constant-ness first.
3509 if (BuiltinConstantArg(TheCall, ArgNum, Result))
3510 return true;
3511
3512 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3513 if (Result.isShiftedMask() || (~Result).isShiftedMask())
3514 return false;
3515
3516 return Diag(TheCall->getBeginLoc(),
3517 diag::err_argument_not_contiguous_bit_field)
3518 << ArgNum << Arg->getSourceRange();
3519}
3520
3521bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
3522 unsigned FirstArg, FormatStringInfo *FSI) {
3523 bool IsCXXMember = false;
3524 if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
3525 IsCXXMember = MD->isInstance();
3526 bool IsVariadic = false;
3527 if (const FunctionType *FnTy = D->getFunctionType())
3528 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
3529 else if (const auto *BD = dyn_cast<BlockDecl>(D))
3530 IsVariadic = BD->isVariadic();
3531 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
3532 IsVariadic = OMD->isVariadic();
3533
3534 return getFormatStringInfo(FormatIdx, FirstArg, IsCXXMember, IsVariadic, FSI);
3535}
3536
3537bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
3538 bool IsCXXMember, bool IsVariadic,
3539 FormatStringInfo *FSI) {
3540 if (FirstArg == 0)
3542 else if (IsVariadic)
3544 else
3546 FSI->FormatIdx = FormatIdx - 1;
3547 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
3548
3549 // The way the format attribute works in GCC, the implicit this argument
3550 // of member functions is counted. However, it doesn't appear in our own
3551 // lists, so decrement format_idx in that case.
3552 if (IsCXXMember) {
3553 if(FSI->FormatIdx == 0)
3554 return false;
3555 --FSI->FormatIdx;
3556 if (FSI->FirstDataArg != 0)
3557 --FSI->FirstDataArg;
3558 }
3559 return true;
3560}
3561
3562/// Checks if a the given expression evaluates to null.
3563///
3564/// Returns true if the value evaluates to null.
3565static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3566 // Treat (smart) pointers constructed from nullptr as null, whether we can
3567 // const-evaluate them or not.
3568 // This must happen first: the smart pointer expr might have _Nonnull type!
3572 return true;
3573
3574 // If the expression has non-null type, it doesn't evaluate to null.
3575 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
3576 if (*nullability == NullabilityKind::NonNull)
3577 return false;
3578 }
3579
3580 // As a special case, transparent unions initialized with zero are
3581 // considered null for the purposes of the nonnull attribute.
3582 if (const RecordType *UT = Expr->getType()->getAsUnionType();
3583 UT &&
3584 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
3585 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
3586 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
3587 Expr = ILE->getInit(0);
3588 }
3589
3590 bool Result;
3591 return (!Expr->isValueDependent() &&
3593 !Result);
3594}
3595
3597 const Expr *ArgExpr,
3598 SourceLocation CallSiteLoc) {
3599 if (CheckNonNullExpr(S, ArgExpr))
3600 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3601 S.PDiag(diag::warn_null_arg)
3602 << ArgExpr->getSourceRange());
3603}
3604
3605/// Determine whether the given type has a non-null nullability annotation.
3607 if (auto nullability = type->getNullability())
3608 return *nullability == NullabilityKind::NonNull;
3609
3610 return false;
3611}
3612
3614 const NamedDecl *FDecl,
3615 const FunctionProtoType *Proto,
3617 SourceLocation CallSiteLoc) {
3618 assert((FDecl || Proto) && "Need a function declaration or prototype");
3619
3620 // Already checked by constant evaluator.
3622 return;
3623 // Check the attributes attached to the method/function itself.
3624 llvm::SmallBitVector NonNullArgs;
3625 if (FDecl) {
3626 // Handle the nonnull attribute on the function/method declaration itself.
3627 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3628 if (!NonNull->args_size()) {
3629 // Easy case: all pointer arguments are nonnull.
3630 for (const auto *Arg : Args)
3631 if (S.isValidPointerAttrType(Arg->getType()))
3632 CheckNonNullArgument(S, Arg, CallSiteLoc);
3633 return;
3634 }
3635
3636 for (const ParamIdx &Idx : NonNull->args()) {
3637 unsigned IdxAST = Idx.getASTIndex();
3638 if (IdxAST >= Args.size())
3639 continue;
3640 if (NonNullArgs.empty())
3641 NonNullArgs.resize(Args.size());
3642 NonNullArgs.set(IdxAST);
3643 }
3644 }
3645 }
3646
3647 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3648 // Handle the nonnull attribute on the parameters of the
3649 // function/method.
3651 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3652 parms = FD->parameters();
3653 else
3654 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3655
3656 unsigned ParamIndex = 0;
3657 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3658 I != E; ++I, ++ParamIndex) {
3659 const ParmVarDecl *PVD = *I;
3660 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
3661 if (NonNullArgs.empty())
3662 NonNullArgs.resize(Args.size());
3663
3664 NonNullArgs.set(ParamIndex);
3665 }
3666 }
3667 } else {
3668 // If we have a non-function, non-method declaration but no
3669 // function prototype, try to dig out the function prototype.
3670 if (!Proto) {
3671 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3672 QualType type = VD->getType().getNonReferenceType();
3673 if (auto pointerType = type->getAs<PointerType>())
3674 type = pointerType->getPointeeType();
3675 else if (auto blockType = type->getAs<BlockPointerType>())
3676 type = blockType->getPointeeType();
3677 // FIXME: data member pointers?
3678
3679 // Dig out the function prototype, if there is one.
3680 Proto = type->getAs<FunctionProtoType>();
3681 }
3682 }
3683
3684 // Fill in non-null argument information from the nullability
3685 // information on the parameter types (if we have them).
3686 if (Proto) {
3687 unsigned Index = 0;
3688 for (auto paramType : Proto->getParamTypes()) {
3689 if (isNonNullType(paramType)) {
3690 if (NonNullArgs.empty())
3691 NonNullArgs.resize(Args.size());
3692
3693 NonNullArgs.set(Index);
3694 }
3695
3696 ++Index;
3697 }
3698 }
3699 }
3700
3701 // Check for non-null arguments.
3702 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3703 ArgIndex != ArgIndexEnd; ++ArgIndex) {
3704 if (NonNullArgs[ArgIndex])
3705 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
3706 }
3707}
3708
3709void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
3710 StringRef ParamName, QualType ArgTy,
3711 QualType ParamTy) {
3712
3713 // If a function accepts a pointer or reference type
3714 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
3715 return;
3716
3717 // If the parameter is a pointer type, get the pointee type for the
3718 // argument too. If the parameter is a reference type, don't try to get
3719 // the pointee type for the argument.
3720 if (ParamTy->isPointerType())
3721 ArgTy = ArgTy->getPointeeType();
3722
3723 // Remove reference or pointer
3724 ParamTy = ParamTy->getPointeeType();
3725
3726 // Find expected alignment, and the actual alignment of the passed object.
3727 // getTypeAlignInChars requires complete types
3728 if (ArgTy.isNull() || ParamTy->isDependentType() ||
3729 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
3730 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
3731 return;
3732
3733 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
3734 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
3735
3736 // If the argument is less aligned than the parameter, there is a
3737 // potential alignment issue.
3738 if (ArgAlign < ParamAlign)
3739 Diag(Loc, diag::warn_param_mismatched_alignment)
3740 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
3741 << ParamName << (FDecl != nullptr) << FDecl;
3742}
3743
3744void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
3745 const Expr *ThisArg,
3747 if (!FD || Args.empty())
3748 return;
3749 auto GetArgAt = [&](int Idx) -> const Expr * {
3750 if (Idx == LifetimeCaptureByAttr::Global ||
3751 Idx == LifetimeCaptureByAttr::Unknown)
3752 return nullptr;
3753 if (IsMemberFunction && Idx == 0)
3754 return ThisArg;
3755 return Args[Idx - IsMemberFunction];
3756 };
3757 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
3758 unsigned ArgIdx) {
3759 if (!Attr)
3760 return;
3761
3762 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
3763 for (int CapturingParamIdx : Attr->params()) {
3764 // lifetime_capture_by(this) case is handled in the lifetimebound expr
3765 // initialization codepath.
3766 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
3768 continue;
3769 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
3770 CapturingEntity CE{Capturing};
3771 // Ensure that 'Captured' outlives the 'Capturing' entity.
3772 checkCaptureByLifetime(*this, CE, Captured);
3773 }
3774 };
3775 for (unsigned I = 0; I < FD->getNumParams(); ++I)
3776 HandleCaptureByAttr(FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>(),
3777 I + IsMemberFunction);
3778 // Check when the implicit object param is captured.
3779 if (IsMemberFunction) {
3780 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
3781 if (!TSI)
3782 return;
3784 for (TypeLoc TL = TSI->getTypeLoc();
3785 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
3786 TL = ATL.getModifiedLoc())
3787 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
3788 }
3789}
3790
3792 const Expr *ThisArg, ArrayRef<const Expr *> Args,
3793 bool IsMemberFunction, SourceLocation Loc,
3794 SourceRange Range, VariadicCallType CallType) {
3795 // FIXME: We should check as much as we can in the template definition.
3796 if (CurContext->isDependentContext())
3797 return;
3798
3799 // Printf and scanf checking.
3800 llvm::SmallBitVector CheckedVarArgs;
3801 if (FDecl) {
3802 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
3803 // Only create vector if there are format attributes.
3804 CheckedVarArgs.resize(Args.size());
3805 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
3806 CheckedVarArgs);
3807 }
3808
3809 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3810 CheckedVarArgs.resize(Args.size());
3811 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
3812 CheckedVarArgs);
3813 }
3814 }
3815
3816 // Refuse POD arguments that weren't caught by the format string
3817 // checks above.
3818 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3819 if (CallType != VariadicCallType::DoesNotApply &&
3820 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
3821 unsigned NumParams = Proto ? Proto->getNumParams()
3822 : isa_and_nonnull<FunctionDecl>(FDecl)
3823 ? cast<FunctionDecl>(FDecl)->getNumParams()
3824 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
3825 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3826 : 0;
3827
3828 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
3829 // Args[ArgIdx] can be null in malformed code.
3830 if (const Expr *Arg = Args[ArgIdx]) {
3831 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3832 checkVariadicArgument(Arg, CallType);
3833 }
3834 }
3835 }
3836 if (FD)
3837 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
3838 if (FDecl || Proto) {
3839 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
3840
3841 // Type safety checking.
3842 if (FDecl) {
3843 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
3844 CheckArgumentWithTypeTag(I, Args, Loc);
3845 }
3846 }
3847
3848 // Check that passed arguments match the alignment of original arguments.
3849 // Try to get the missing prototype from the declaration.
3850 if (!Proto && FDecl) {
3851 const auto *FT = FDecl->getFunctionType();
3852 if (isa_and_nonnull<FunctionProtoType>(FT))
3853 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
3854 }
3855 if (Proto) {
3856 // For variadic functions, we may have more args than parameters.
3857 // For some K&R functions, we may have less args than parameters.
3858 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
3859 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
3860 bool IsScalableArg = false;
3861 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
3862 // Args[ArgIdx] can be null in malformed code.
3863 if (const Expr *Arg = Args[ArgIdx]) {
3864 if (Arg->containsErrors())
3865 continue;
3866
3867 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
3868 FDecl->hasLinkage() &&
3869 FDecl->getFormalLinkage() != Linkage::Internal &&
3871 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
3872
3873 QualType ParamTy = Proto->getParamType(ArgIdx);
3874 if (ParamTy->isSizelessVectorType())
3875 IsScalableArg = true;
3876 QualType ArgTy = Arg->getType();
3877 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
3878 ArgTy, ParamTy);
3879 }
3880 }
3881
3882 // If the callee has an AArch64 SME attribute to indicate that it is an
3883 // __arm_streaming function, then the caller requires SME to be available.
3886 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
3887 llvm::StringMap<bool> CallerFeatureMap;
3888 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
3889 if (!CallerFeatureMap.contains("sme"))
3890 Diag(Loc, diag::err_sme_call_in_non_sme_target);
3891 } else if (!Context.getTargetInfo().hasFeature("sme")) {
3892 Diag(Loc, diag::err_sme_call_in_non_sme_target);
3893 }
3894 }
3895
3896 // If the call requires a streaming-mode change and has scalable vector
3897 // arguments or return values, then warn the user that the streaming and
3898 // non-streaming vector lengths may be different.
3899 // When both streaming and non-streaming vector lengths are defined and
3900 // mismatched, produce an error.
3901 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
3902 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
3903 (IsScalableArg || IsScalableRet)) {
3904 bool IsCalleeStreaming =
3906 bool IsCalleeStreamingCompatible =
3907 ExtInfo.AArch64SMEAttributes &
3909 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
3910 if (!IsCalleeStreamingCompatible &&
3911 (CallerFnType == SemaARM::ArmStreamingCompatible ||
3912 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
3913 const LangOptions &LO = getLangOpts();
3914 unsigned VL = LO.VScaleMin * 128;
3915 unsigned SVL = LO.VScaleStreamingMin * 128;
3916 bool IsVLMismatch = VL && SVL && VL != SVL;
3917
3918 auto EmitDiag = [&](bool IsArg) {
3919 if (IsVLMismatch) {
3920 if (CallerFnType == SemaARM::ArmStreamingCompatible)
3921 // Emit warning for streaming-compatible callers
3922 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
3923 << IsArg << IsCalleeStreaming << SVL << VL;
3924 else
3925 // Emit error otherwise
3926 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
3927 << IsArg << SVL << VL;
3928 } else
3929 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
3930 << IsArg;
3931 };
3932
3933 if (IsScalableArg)
3934 EmitDiag(true);
3935 if (IsScalableRet)
3936 EmitDiag(false);
3937 }
3938 }
3939
3940 FunctionType::ArmStateValue CalleeArmZAState =
3942 FunctionType::ArmStateValue CalleeArmZT0State =
3944 if (CalleeArmZAState != FunctionType::ARM_None ||
3945 CalleeArmZT0State != FunctionType::ARM_None) {
3946 bool CallerHasZAState = false;
3947 bool CallerHasZT0State = false;
3948 if (CallerFD) {
3949 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
3950 if (Attr && Attr->isNewZA())
3951 CallerHasZAState = true;
3952 if (Attr && Attr->isNewZT0())
3953 CallerHasZT0State = true;
3954 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
3955 CallerHasZAState |=
3957 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
3959 CallerHasZT0State |=
3961 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
3963 }
3964 }
3965
3966 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
3967 Diag(Loc, diag::err_sme_za_call_no_za_state);
3968
3969 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
3970 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
3971
3972 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
3973 CalleeArmZT0State != FunctionType::ARM_None) {
3974 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
3975 Diag(Loc, diag::note_sme_use_preserves_za);
3976 }
3977 }
3978 }
3979
3980 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
3981 auto *AA = FDecl->getAttr<AllocAlignAttr>();
3982 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
3983 if (!Arg->isValueDependent()) {
3984 Expr::EvalResult Align;
3985 if (Arg->EvaluateAsInt(Align, Context)) {
3986 const llvm::APSInt &I = Align.Val.getInt();
3987 if (!I.isPowerOf2())
3988 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
3989 << Arg->getSourceRange();
3990
3991 if (I > Sema::MaximumAlignment)
3992 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
3993 << Arg->getSourceRange() << Sema::MaximumAlignment;
3994 }
3995 }
3996 }
3997
3998 if (FD)
3999 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4000}
4001
4002void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4003 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
4004 DiagnoseUseOfDecl(Decl, Loc);
4005 }
4006}
4007
4008void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4010 const FunctionProtoType *Proto,
4011 SourceLocation Loc) {
4012 VariadicCallType CallType = Proto->isVariadic()
4015
4016 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4017 CheckArgAlignment(
4018 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4019 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4020
4021 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4022 Loc, SourceRange(), CallType);
4023}
4024
4026 const FunctionProtoType *Proto) {
4027 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4028 isa<CXXMethodDecl>(FDecl);
4029 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4030 IsMemberOperatorCall;
4031 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4032 TheCall->getCallee());
4033 Expr** Args = TheCall->getArgs();
4034 unsigned NumArgs = TheCall->getNumArgs();
4035
4036 Expr *ImplicitThis = nullptr;
4037 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4038 // If this is a call to a member operator, hide the first
4039 // argument from checkCall.
4040 // FIXME: Our choice of AST representation here is less than ideal.
4041 ImplicitThis = Args[0];
4042 ++Args;
4043 --NumArgs;
4044 } else if (IsMemberFunction && !FDecl->isStatic() &&
4046 ImplicitThis =
4047 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4048
4049 if (ImplicitThis) {
4050 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4051 // used.
4052 QualType ThisType = ImplicitThis->getType();
4053 if (!ThisType->isPointerType()) {
4054 assert(!ThisType->isReferenceType());
4055 ThisType = Context.getPointerType(ThisType);
4056 }
4057
4058 QualType ThisTypeFromDecl = Context.getPointerType(
4059 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
4060
4061 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4062 ThisTypeFromDecl);
4063 }
4064
4065 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
4066 IsMemberFunction, TheCall->getRParenLoc(),
4067 TheCall->getCallee()->getSourceRange(), CallType);
4068
4069 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4070 // None of the checks below are needed for functions that don't have
4071 // simple names (e.g., C++ conversion functions).
4072 if (!FnInfo)
4073 return false;
4074
4075 // Enforce TCB except for builtin calls, which are always allowed.
4076 if (FDecl->getBuiltinID() == 0)
4077 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
4078
4079 CheckAbsoluteValueFunction(TheCall, FDecl);
4080 CheckMaxUnsignedZero(TheCall, FDecl);
4081 CheckInfNaNFunction(TheCall, FDecl);
4082
4083 if (getLangOpts().ObjC)
4084 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4085
4086 unsigned CMId = FDecl->getMemoryFunctionKind();
4087
4088 // Handle memory setting and copying functions.
4089 switch (CMId) {
4090 case 0:
4091 return false;
4092 case Builtin::BIstrlcpy: // fallthrough
4093 case Builtin::BIstrlcat:
4094 CheckStrlcpycatArguments(TheCall, FnInfo);
4095 break;
4096 case Builtin::BIstrncat:
4097 CheckStrncatArguments(TheCall, FnInfo);
4098 break;
4099 case Builtin::BIfree:
4100 CheckFreeArguments(TheCall);
4101 break;
4102 default:
4103 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4104 }
4105
4106 return false;
4107}
4108
4109bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4110 const FunctionProtoType *Proto) {
4111 QualType Ty;
4112 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4113 Ty = V->getType().getNonReferenceType();
4114 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4115 Ty = F->getType().getNonReferenceType();
4116 else
4117 return false;
4118
4119 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4120 !Ty->isFunctionProtoType())
4121 return false;
4122
4123 VariadicCallType CallType;
4124 if (!Proto || !Proto->isVariadic()) {
4126 } else if (Ty->isBlockPointerType()) {
4127 CallType = VariadicCallType::Block;
4128 } else { // Ty->isFunctionPointerType()
4129 CallType = VariadicCallType::Function;
4130 }
4131
4132 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4133 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4134 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4135 TheCall->getCallee()->getSourceRange(), CallType);
4136
4137 return false;
4138}
4139
4140bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4141 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4142 TheCall->getCallee());
4143 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4144 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4145 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4146 TheCall->getCallee()->getSourceRange(), CallType);
4147
4148 return false;
4149}
4150
4151static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4152 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4153 return false;
4154
4155 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4156 switch (Op) {
4157 case AtomicExpr::AO__c11_atomic_init:
4158 case AtomicExpr::AO__opencl_atomic_init:
4159 llvm_unreachable("There is no ordering argument for an init");
4160
4161 case AtomicExpr::AO__c11_atomic_load:
4162 case AtomicExpr::AO__opencl_atomic_load:
4163 case AtomicExpr::AO__hip_atomic_load:
4164 case AtomicExpr::AO__atomic_load_n:
4165 case AtomicExpr::AO__atomic_load:
4166 case AtomicExpr::AO__scoped_atomic_load_n:
4167 case AtomicExpr::AO__scoped_atomic_load:
4168 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4169 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4170
4171 case AtomicExpr::AO__c11_atomic_store:
4172 case AtomicExpr::AO__opencl_atomic_store:
4173 case AtomicExpr::AO__hip_atomic_store:
4174 case AtomicExpr::AO__atomic_store:
4175 case AtomicExpr::AO__atomic_store_n:
4176 case AtomicExpr::AO__scoped_atomic_store:
4177 case AtomicExpr::AO__scoped_atomic_store_n:
4178 case AtomicExpr::AO__atomic_clear:
4179 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4180 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4181 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4182
4183 default:
4184 return true;
4185 }
4186}
4187
4188ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4190 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4191 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4192 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4193 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4194 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4195 Op);
4196}
4197
4199 SourceLocation RParenLoc, MultiExprArg Args,
4201 AtomicArgumentOrder ArgOrder) {
4202 // All the non-OpenCL operations take one of the following forms.
4203 // The OpenCL operations take the __c11 forms with one extra argument for
4204 // synchronization scope.
4205 enum {
4206 // C __c11_atomic_init(A *, C)
4207 Init,
4208
4209 // C __c11_atomic_load(A *, int)
4210 Load,
4211
4212 // void __atomic_load(A *, CP, int)
4213 LoadCopy,
4214
4215 // void __atomic_store(A *, CP, int)
4216 Copy,
4217
4218 // C __c11_atomic_add(A *, M, int)
4219 Arithmetic,
4220
4221 // C __atomic_exchange_n(A *, CP, int)
4222 Xchg,
4223
4224 // void __atomic_exchange(A *, C *, CP, int)
4225 GNUXchg,
4226
4227 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4228 C11CmpXchg,
4229
4230 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4231 GNUCmpXchg,
4232
4233 // bool __atomic_test_and_set(A *, int)
4234 TestAndSetByte,
4235
4236 // void __atomic_clear(A *, int)
4237 ClearByte,
4238 } Form = Init;
4239
4240 const unsigned NumForm = ClearByte + 1;
4241 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
4242 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
4243 // where:
4244 // C is an appropriate type,
4245 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4246 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4247 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4248 // the int parameters are for orderings.
4249
4250 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4251 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4252 "need to update code for modified forms");
4253 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
4254 AtomicExpr::AO__atomic_xor_fetch + 1 ==
4255 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
4256 "need to update code for modified C11 atomics");
4257 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
4258 Op <= AtomicExpr::AO__opencl_atomic_store;
4259 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
4260 Op <= AtomicExpr::AO__hip_atomic_store;
4261 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
4262 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
4263 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
4264 Op <= AtomicExpr::AO__c11_atomic_store) ||
4265 IsOpenCL;
4266 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4267 Op == AtomicExpr::AO__atomic_store_n ||
4268 Op == AtomicExpr::AO__atomic_exchange_n ||
4269 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
4270 Op == AtomicExpr::AO__scoped_atomic_load_n ||
4271 Op == AtomicExpr::AO__scoped_atomic_store_n ||
4272 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
4273 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
4274 // Bit mask for extra allowed value types other than integers for atomic
4275 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
4276 // allow floating point.
4277 enum ArithOpExtraValueType {
4278 AOEVT_None = 0,
4279 AOEVT_Pointer = 1,
4280 AOEVT_FP = 2,
4281 };
4282 unsigned ArithAllows = AOEVT_None;
4283
4284 switch (Op) {
4285 case AtomicExpr::AO__c11_atomic_init:
4286 case AtomicExpr::AO__opencl_atomic_init:
4287 Form = Init;
4288 break;
4289
4290 case AtomicExpr::AO__c11_atomic_load:
4291 case AtomicExpr::AO__opencl_atomic_load:
4292 case AtomicExpr::AO__hip_atomic_load:
4293 case AtomicExpr::AO__atomic_load_n:
4294 case AtomicExpr::AO__scoped_atomic_load_n:
4295 Form = Load;
4296 break;
4297
4298 case AtomicExpr::AO__atomic_load:
4299 case AtomicExpr::AO__scoped_atomic_load:
4300 Form = LoadCopy;
4301 break;
4302
4303 case AtomicExpr::AO__c11_atomic_store:
4304 case AtomicExpr::AO__opencl_atomic_store:
4305 case AtomicExpr::AO__hip_atomic_store:
4306 case AtomicExpr::AO__atomic_store:
4307 case AtomicExpr::AO__atomic_store_n:
4308 case AtomicExpr::AO__scoped_atomic_store:
4309 case AtomicExpr::AO__scoped_atomic_store_n:
4310 Form = Copy;
4311 break;
4312 case AtomicExpr::AO__atomic_fetch_add:
4313 case AtomicExpr::AO__atomic_fetch_sub:
4314 case AtomicExpr::AO__atomic_add_fetch:
4315 case AtomicExpr::AO__atomic_sub_fetch:
4316 case AtomicExpr::AO__scoped_atomic_fetch_add:
4317 case AtomicExpr::AO__scoped_atomic_fetch_sub:
4318 case AtomicExpr::AO__scoped_atomic_add_fetch:
4319 case AtomicExpr::AO__scoped_atomic_sub_fetch:
4320 case AtomicExpr::AO__c11_atomic_fetch_add:
4321 case AtomicExpr::AO__c11_atomic_fetch_sub:
4322 case AtomicExpr::AO__opencl_atomic_fetch_add:
4323 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4324 case AtomicExpr::AO__hip_atomic_fetch_add:
4325 case AtomicExpr::AO__hip_atomic_fetch_sub:
4326 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4327 Form = Arithmetic;
4328 break;
4329 case AtomicExpr::AO__atomic_fetch_max:
4330 case AtomicExpr::AO__atomic_fetch_min:
4331 case AtomicExpr::AO__atomic_max_fetch:
4332 case AtomicExpr::AO__atomic_min_fetch:
4333 case AtomicExpr::AO__scoped_atomic_fetch_max:
4334 case AtomicExpr::AO__scoped_atomic_fetch_min:
4335 case AtomicExpr::AO__scoped_atomic_max_fetch:
4336 case AtomicExpr::AO__scoped_atomic_min_fetch:
4337 case AtomicExpr::AO__c11_atomic_fetch_max:
4338 case AtomicExpr::AO__c11_atomic_fetch_min:
4339 case AtomicExpr::AO__opencl_atomic_fetch_max:
4340 case AtomicExpr::AO__opencl_atomic_fetch_min:
4341 case AtomicExpr::AO__hip_atomic_fetch_max:
4342 case AtomicExpr::AO__hip_atomic_fetch_min:
4343 ArithAllows = AOEVT_FP;
4344 Form = Arithmetic;
4345 break;
4346 case AtomicExpr::AO__c11_atomic_fetch_and:
4347 case AtomicExpr::AO__c11_atomic_fetch_or:
4348 case AtomicExpr::AO__c11_atomic_fetch_xor:
4349 case AtomicExpr::AO__hip_atomic_fetch_and:
4350 case AtomicExpr::AO__hip_atomic_fetch_or:
4351 case AtomicExpr::AO__hip_atomic_fetch_xor:
4352 case AtomicExpr::AO__c11_atomic_fetch_nand:
4353 case AtomicExpr::AO__opencl_atomic_fetch_and:
4354 case AtomicExpr::AO__opencl_atomic_fetch_or:
4355 case AtomicExpr::AO__opencl_atomic_fetch_xor:
4356 case AtomicExpr::AO__atomic_fetch_and:
4357 case AtomicExpr::AO__atomic_fetch_or:
4358 case AtomicExpr::AO__atomic_fetch_xor:
4359 case AtomicExpr::AO__atomic_fetch_nand:
4360 case AtomicExpr::AO__atomic_and_fetch:
4361 case AtomicExpr::AO__atomic_or_fetch:
4362 case AtomicExpr::AO__atomic_xor_fetch:
4363 case AtomicExpr::AO__atomic_nand_fetch:
4364 case AtomicExpr::AO__scoped_atomic_fetch_and:
4365 case AtomicExpr::AO__scoped_atomic_fetch_or:
4366 case AtomicExpr::AO__scoped_atomic_fetch_xor:
4367 case AtomicExpr::AO__scoped_atomic_fetch_nand:
4368 case AtomicExpr::AO__scoped_atomic_and_fetch:
4369 case AtomicExpr::AO__scoped_atomic_or_fetch:
4370 case AtomicExpr::AO__scoped_atomic_xor_fetch:
4371 case AtomicExpr::AO__scoped_atomic_nand_fetch:
4372 Form = Arithmetic;
4373 break;
4374
4375 case AtomicExpr::AO__c11_atomic_exchange:
4376 case AtomicExpr::AO__hip_atomic_exchange:
4377 case AtomicExpr::AO__opencl_atomic_exchange:
4378 case AtomicExpr::AO__atomic_exchange_n:
4379 case AtomicExpr::AO__scoped_atomic_exchange_n:
4380 Form = Xchg;
4381 break;
4382
4383 case AtomicExpr::AO__atomic_exchange:
4384 case AtomicExpr::AO__scoped_atomic_exchange:
4385 Form = GNUXchg;
4386 break;
4387
4388 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4389 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4390 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4391 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4392 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4393 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4394 Form = C11CmpXchg;
4395 break;
4396
4397 case AtomicExpr::AO__atomic_compare_exchange:
4398 case AtomicExpr::AO__atomic_compare_exchange_n:
4399 case AtomicExpr::AO__scoped_atomic_compare_exchange:
4400 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
4401 Form = GNUCmpXchg;
4402 break;
4403
4404 case AtomicExpr::AO__atomic_test_and_set:
4405 Form = TestAndSetByte;
4406 break;
4407
4408 case AtomicExpr::AO__atomic_clear:
4409 Form = ClearByte;
4410 break;
4411 }
4412
4413 unsigned AdjustedNumArgs = NumArgs[Form];
4414 if ((IsOpenCL || IsHIP || IsScoped) &&
4415 Op != AtomicExpr::AO__opencl_atomic_init)
4416 ++AdjustedNumArgs;
4417 // Check we have the right number of arguments.
4418 if (Args.size() < AdjustedNumArgs) {
4419 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4420 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4421 << /*is non object*/ 0 << ExprRange;
4422 return ExprError();
4423 } else if (Args.size() > AdjustedNumArgs) {
4424 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4425 diag::err_typecheck_call_too_many_args)
4426 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4427 << /*is non object*/ 0 << ExprRange;
4428 return ExprError();
4429 }
4430
4431 // Inspect the first argument of the atomic operation.
4432 Expr *Ptr = Args[0];
4434 if (ConvertedPtr.isInvalid())
4435 return ExprError();
4436
4437 Ptr = ConvertedPtr.get();
4438 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4439 if (!pointerType) {
4440 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4441 << Ptr->getType() << 0 << Ptr->getSourceRange();
4442 return ExprError();
4443 }
4444
4445 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4446 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4447 QualType ValType = AtomTy; // 'C'
4448 if (IsC11) {
4449 if (!AtomTy->isAtomicType()) {
4450 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4451 << Ptr->getType() << Ptr->getSourceRange();
4452 return ExprError();
4453 }
4454 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4456 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4457 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4458 << Ptr->getSourceRange();
4459 return ExprError();
4460 }
4461 ValType = AtomTy->castAs<AtomicType>()->getValueType();
4462 } else if (Form != Load && Form != LoadCopy) {
4463 if (ValType.isConstQualified()) {
4464 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4465 << Ptr->getType() << Ptr->getSourceRange();
4466 return ExprError();
4467 }
4468 }
4469
4470 if (Form != TestAndSetByte && Form != ClearByte) {
4471 // Pointer to object of size zero is not allowed.
4472 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
4473 diag::err_incomplete_type))
4474 return ExprError();
4475
4476 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
4477 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4478 << Ptr->getType() << 1 << Ptr->getSourceRange();
4479 return ExprError();
4480 }
4481 } else {
4482 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
4483 // non-const pointer type, including void* and pointers to incomplete
4484 // structs, but only access the first byte.
4485 AtomTy = Context.CharTy;
4486 AtomTy = AtomTy.withCVRQualifiers(
4487 pointerType->getPointeeType().getCVRQualifiers());
4488 QualType PointerQT = Context.getPointerType(AtomTy);
4489 pointerType = PointerQT->getAs<PointerType>();
4490 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
4491 ValType = AtomTy;
4492 }
4493
4494 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
4495 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4496 Diag(ExprRange.getBegin(),
4497 diag::err_atomic_op_needs_non_address_discriminated_pointer)
4498 << 0 << Ptr->getType() << Ptr->getSourceRange();
4499 return ExprError();
4500 }
4501
4502 // For an arithmetic operation, the implied arithmetic must be well-formed.
4503 if (Form == Arithmetic) {
4504 // GCC does not enforce these rules for GNU atomics, but we do to help catch
4505 // trivial type errors.
4506 auto IsAllowedValueType = [&](QualType ValType,
4507 unsigned AllowedType) -> bool {
4508 if (ValType->isIntegerType())
4509 return true;
4510 if (ValType->isPointerType())
4511 return AllowedType & AOEVT_Pointer;
4512 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
4513 return false;
4514 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
4515 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
4516 &Context.getTargetInfo().getLongDoubleFormat() ==
4517 &llvm::APFloat::x87DoubleExtended())
4518 return false;
4519 return true;
4520 };
4521 if (!IsAllowedValueType(ValType, ArithAllows)) {
4522 auto DID = ArithAllows & AOEVT_FP
4523 ? (ArithAllows & AOEVT_Pointer
4524 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
4525 : diag::err_atomic_op_needs_atomic_int_or_fp)
4526 : diag::err_atomic_op_needs_atomic_int;
4527 Diag(ExprRange.getBegin(), DID)
4528 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4529 return ExprError();
4530 }
4531 if (IsC11 && ValType->isPointerType() &&
4533 diag::err_incomplete_type)) {
4534 return ExprError();
4535 }
4536 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4537 // For __atomic_*_n operations, the value type must be a scalar integral or
4538 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4539 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4540 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4541 return ExprError();
4542 }
4543
4544 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4545 !AtomTy->isScalarType()) {
4546 // For GNU atomics, require a trivially-copyable type. This is not part of
4547 // the GNU atomics specification but we enforce it for consistency with
4548 // other atomics which generally all require a trivially-copyable type. This
4549 // is because atomics just copy bits.
4550 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4551 << Ptr->getType() << Ptr->getSourceRange();
4552 return ExprError();
4553 }
4554
4555 switch (ValType.getObjCLifetime()) {
4558 // okay
4559 break;
4560
4564 // FIXME: Can this happen? By this point, ValType should be known
4565 // to be trivially copyable.
4566 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4567 << ValType << Ptr->getSourceRange();
4568 return ExprError();
4569 }
4570
4571 // All atomic operations have an overload which takes a pointer to a volatile
4572 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4573 // into the result or the other operands. Similarly atomic_load takes a
4574 // pointer to a const 'A'.
4575 ValType.removeLocalVolatile();
4576 ValType.removeLocalConst();
4577 QualType ResultType = ValType;
4578 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
4579 Form == ClearByte)
4580 ResultType = Context.VoidTy;
4581 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
4582 ResultType = Context.BoolTy;
4583
4584 // The type of a parameter passed 'by value'. In the GNU atomics, such
4585 // arguments are actually passed as pointers.
4586 QualType ByValType = ValType; // 'CP'
4587 bool IsPassedByAddress = false;
4588 if (!IsC11 && !IsHIP && !IsN) {
4589 ByValType = Ptr->getType();
4590 IsPassedByAddress = true;
4591 }
4592
4593 SmallVector<Expr *, 5> APIOrderedArgs;
4594 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4595 APIOrderedArgs.push_back(Args[0]);
4596 switch (Form) {
4597 case Init:
4598 case Load:
4599 APIOrderedArgs.push_back(Args[1]); // Val1/Order
4600 break;
4601 case LoadCopy:
4602 case Copy:
4603 case Arithmetic:
4604 case Xchg:
4605 APIOrderedArgs.push_back(Args[2]); // Val1
4606 APIOrderedArgs.push_back(Args[1]); // Order
4607 break;
4608 case GNUXchg:
4609 APIOrderedArgs.push_back(Args[2]); // Val1
4610 APIOrderedArgs.push_back(Args[3]); // Val2
4611 APIOrderedArgs.push_back(Args[1]); // Order
4612 break;
4613 case C11CmpXchg:
4614 APIOrderedArgs.push_back(Args[2]); // Val1
4615 APIOrderedArgs.push_back(Args[4]); // Val2
4616 APIOrderedArgs.push_back(Args[1]); // Order
4617 APIOrderedArgs.push_back(Args[3]); // OrderFail
4618 break;
4619 case GNUCmpXchg:
4620 APIOrderedArgs.push_back(Args[2]); // Val1
4621 APIOrderedArgs.push_back(Args[4]); // Val2
4622 APIOrderedArgs.push_back(Args[5]); // Weak
4623 APIOrderedArgs.push_back(Args[1]); // Order
4624 APIOrderedArgs.push_back(Args[3]); // OrderFail
4625 break;
4626 case TestAndSetByte:
4627 case ClearByte:
4628 APIOrderedArgs.push_back(Args[1]); // Order
4629 break;
4630 }
4631 } else
4632 APIOrderedArgs.append(Args.begin(), Args.end());
4633
4634 // The first argument's non-CV pointer type is used to deduce the type of
4635 // subsequent arguments, except for:
4636 // - weak flag (always converted to bool)
4637 // - memory order (always converted to int)
4638 // - scope (always converted to int)
4639 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4640 QualType Ty;
4641 if (i < NumVals[Form] + 1) {
4642 switch (i) {
4643 case 0:
4644 // The first argument is always a pointer. It has a fixed type.
4645 // It is always dereferenced, a nullptr is undefined.
4646 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4647 // Nothing else to do: we already know all we want about this pointer.
4648 continue;
4649 case 1:
4650 // The second argument is the non-atomic operand. For arithmetic, this
4651 // is always passed by value, and for a compare_exchange it is always
4652 // passed by address. For the rest, GNU uses by-address and C11 uses
4653 // by-value.
4654 assert(Form != Load);
4655 if (Form == Arithmetic && ValType->isPointerType())
4656 Ty = Context.getPointerDiffType();
4657 else if (Form == Init || Form == Arithmetic)
4658 Ty = ValType;
4659 else if (Form == Copy || Form == Xchg) {
4660 if (IsPassedByAddress) {
4661 // The value pointer is always dereferenced, a nullptr is undefined.
4662 CheckNonNullArgument(*this, APIOrderedArgs[i],
4663 ExprRange.getBegin());
4664 }
4665 Ty = ByValType;
4666 } else {
4667 Expr *ValArg = APIOrderedArgs[i];
4668 // The value pointer is always dereferenced, a nullptr is undefined.
4669 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4671 // Keep address space of non-atomic pointer type.
4672 if (const PointerType *PtrTy =
4673 ValArg->getType()->getAs<PointerType>()) {
4674 AS = PtrTy->getPointeeType().getAddressSpace();
4675 }
4676 Ty = Context.getPointerType(
4677 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4678 }
4679 break;
4680 case 2:
4681 // The third argument to compare_exchange / GNU exchange is the desired
4682 // value, either by-value (for the C11 and *_n variant) or as a pointer.
4683 if (IsPassedByAddress)
4684 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4685 Ty = ByValType;
4686 break;
4687 case 3:
4688 // The fourth argument to GNU compare_exchange is a 'weak' flag.
4689 Ty = Context.BoolTy;
4690 break;
4691 }
4692 } else {
4693 // The order(s) and scope are always converted to int.
4694 Ty = Context.IntTy;
4695 }
4696
4697 InitializedEntity Entity =
4699 ExprResult Arg = APIOrderedArgs[i];
4700 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4701 if (Arg.isInvalid())
4702 return true;
4703 APIOrderedArgs[i] = Arg.get();
4704 }
4705
4706 // Permute the arguments into a 'consistent' order.
4707 SmallVector<Expr*, 5> SubExprs;
4708 SubExprs.push_back(Ptr);
4709 switch (Form) {
4710 case Init:
4711 // Note, AtomicExpr::getVal1() has a special case for this atomic.
4712 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4713 break;
4714 case Load:
4715 case TestAndSetByte:
4716 case ClearByte:
4717 SubExprs.push_back(APIOrderedArgs[1]); // Order
4718 break;
4719 case LoadCopy:
4720 case Copy:
4721 case Arithmetic:
4722 case Xchg:
4723 SubExprs.push_back(APIOrderedArgs[2]); // Order
4724 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4725 break;
4726 case GNUXchg:
4727 // Note, AtomicExpr::getVal2() has a special case for this atomic.
4728 SubExprs.push_back(APIOrderedArgs[3]); // Order
4729 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4730 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4731 break;
4732 case C11CmpXchg:
4733 SubExprs.push_back(APIOrderedArgs[3]); // Order
4734 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4735 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4736 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4737 break;
4738 case GNUCmpXchg:
4739 SubExprs.push_back(APIOrderedArgs[4]); // Order
4740 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4741 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4742 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4743 SubExprs.push_back(APIOrderedArgs[3]); // Weak
4744 break;
4745 }
4746
4747 // If the memory orders are constants, check they are valid.
4748 if (SubExprs.size() >= 2 && Form != Init) {
4749 std::optional<llvm::APSInt> Success =
4750 SubExprs[1]->getIntegerConstantExpr(Context);
4751 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
4752 Diag(SubExprs[1]->getBeginLoc(),
4753 diag::warn_atomic_op_has_invalid_memory_order)
4754 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
4755 << SubExprs[1]->getSourceRange();
4756 }
4757 if (SubExprs.size() >= 5) {
4758 if (std::optional<llvm::APSInt> Failure =
4759 SubExprs[3]->getIntegerConstantExpr(Context)) {
4760 if (!llvm::is_contained(
4761 {llvm::AtomicOrderingCABI::relaxed,
4762 llvm::AtomicOrderingCABI::consume,
4763 llvm::AtomicOrderingCABI::acquire,
4764 llvm::AtomicOrderingCABI::seq_cst},
4765 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
4766 Diag(SubExprs[3]->getBeginLoc(),
4767 diag::warn_atomic_op_has_invalid_memory_order)
4768 << /*failure=*/2 << SubExprs[3]->getSourceRange();
4769 }
4770 }
4771 }
4772 }
4773
4774 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4775 auto *Scope = Args[Args.size() - 1];
4776 if (std::optional<llvm::APSInt> Result =
4777 Scope->getIntegerConstantExpr(Context)) {
4778 if (!ScopeModel->isValid(Result->getZExtValue()))
4779 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
4780 << Scope->getSourceRange();
4781 }
4782 SubExprs.push_back(Scope);
4783 }
4784
4785 AtomicExpr *AE = new (Context)
4786 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4787
4788 if ((Op == AtomicExpr::AO__c11_atomic_load ||
4789 Op == AtomicExpr::AO__c11_atomic_store ||
4790 Op == AtomicExpr::AO__opencl_atomic_load ||
4791 Op == AtomicExpr::AO__hip_atomic_load ||
4792 Op == AtomicExpr::AO__opencl_atomic_store ||
4793 Op == AtomicExpr::AO__hip_atomic_store) &&
4794 Context.AtomicUsesUnsupportedLibcall(AE))
4795 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4796 << ((Op == AtomicExpr::AO__c11_atomic_load ||
4797 Op == AtomicExpr::AO__opencl_atomic_load ||
4798 Op == AtomicExpr::AO__hip_atomic_load)
4799 ? 0
4800 : 1);
4801
4802 if (ValType->isBitIntType()) {
4803 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
4804 return ExprError();
4805 }
4806
4807 return AE;
4808}
4809
4810/// checkBuiltinArgument - Given a call to a builtin function, perform
4811/// normal type-checking on the given argument, updating the call in
4812/// place. This is useful when a builtin function requires custom
4813/// type-checking for some of its arguments but not necessarily all of
4814/// them.
4815///
4816/// Returns true on error.
4817static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4818 FunctionDecl *Fn = E->getDirectCallee();
4819 assert(Fn && "builtin call without direct callee!");
4820
4821 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4822 InitializedEntity Entity =
4824
4825 ExprResult Arg = E->getArg(ArgIndex);
4826 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4827 if (Arg.isInvalid())
4828 return true;
4829
4830 E->setArg(ArgIndex, Arg.get());
4831 return false;
4832}
4833
4834ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
4835 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4836 Expr *Callee = TheCall->getCallee();
4837 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4838 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4839
4840 // Ensure that we have at least one argument to do type inference from.
4841 if (TheCall->getNumArgs() < 1) {
4842 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4843 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
4844 << Callee->getSourceRange();
4845 return ExprError();
4846 }
4847
4848 // Inspect the first argument of the atomic builtin. This should always be
4849 // a pointer type, whose element is an integral scalar or pointer type.
4850 // Because it is a pointer type, we don't have to worry about any implicit
4851 // casts here.
4852 // FIXME: We don't allow floating point scalars as input.
4853 Expr *FirstArg = TheCall->getArg(0);
4854 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4855 if (FirstArgResult.isInvalid())
4856 return ExprError();
4857 FirstArg = FirstArgResult.get();
4858 TheCall->setArg(0, FirstArg);
4859
4860 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4861 if (!pointerType) {
4862 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4863 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4864 return ExprError();
4865 }
4866
4867 QualType ValType = pointerType->getPointeeType();
4868 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4869 !ValType->isBlockPointerType()) {
4870 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4871 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4872 return ExprError();
4873 }
4874 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
4875 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4876 Diag(FirstArg->getBeginLoc(),
4877 diag::err_atomic_op_needs_non_address_discriminated_pointer)
4878 << 1 << ValType << FirstArg->getSourceRange();
4879 return ExprError();
4880 }
4881
4882 if (ValType.isConstQualified()) {
4883 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4884 << FirstArg->getType() << FirstArg->getSourceRange();
4885 return ExprError();
4886 }
4887
4888 switch (ValType.getObjCLifetime()) {
4891 // okay
4892 break;
4893
4897 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4898 << ValType << FirstArg->getSourceRange();
4899 return ExprError();
4900 }
4901
4902 // Strip any qualifiers off ValType.
4903 ValType = ValType.getUnqualifiedType();
4904
4905 // The majority of builtins return a value, but a few have special return
4906 // types, so allow them to override appropriately below.
4907 QualType ResultType = ValType;
4908
4909 // We need to figure out which concrete builtin this maps onto. For example,
4910 // __sync_fetch_and_add with a 2 byte object turns into
4911 // __sync_fetch_and_add_2.
4912#define BUILTIN_ROW(x) \
4913 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4914 Builtin::BI##x##_8, Builtin::BI##x##_16 }
4915
4916 static const unsigned BuiltinIndices[][5] = {
4917 BUILTIN_ROW(__sync_fetch_and_add),
4918 BUILTIN_ROW(__sync_fetch_and_sub),
4919 BUILTIN_ROW(__sync_fetch_and_or),
4920 BUILTIN_ROW(__sync_fetch_and_and),
4921 BUILTIN_ROW(__sync_fetch_and_xor),
4922 BUILTIN_ROW(__sync_fetch_and_nand),
4923
4924 BUILTIN_ROW(__sync_add_and_fetch),
4925 BUILTIN_ROW(__sync_sub_and_fetch),
4926 BUILTIN_ROW(__sync_and_and_fetch),
4927 BUILTIN_ROW(__sync_or_and_fetch),
4928 BUILTIN_ROW(__sync_xor_and_fetch),
4929 BUILTIN_ROW(__sync_nand_and_fetch),
4930
4931 BUILTIN_ROW(__sync_val_compare_and_swap),
4932 BUILTIN_ROW(__sync_bool_compare_and_swap),
4933 BUILTIN_ROW(__sync_lock_test_and_set),
4934 BUILTIN_ROW(__sync_lock_release),
4935 BUILTIN_ROW(__sync_swap)
4936 };
4937#undef BUILTIN_ROW
4938
4939 // Determine the index of the size.
4940 unsigned SizeIndex;
4941 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4942 case 1: SizeIndex = 0; break;
4943 case 2: SizeIndex = 1; break;
4944 case 4: SizeIndex = 2; break;
4945 case 8: SizeIndex = 3; break;
4946 case 16: SizeIndex = 4; break;
4947 default:
4948 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4949 << FirstArg->getType() << FirstArg->getSourceRange();
4950 return ExprError();
4951 }
4952
4953 // Each of these builtins has one pointer argument, followed by some number of
4954 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4955 // that we ignore. Find out which row of BuiltinIndices to read from as well
4956 // as the number of fixed args.
4957 unsigned BuiltinID = FDecl->getBuiltinID();
4958 unsigned BuiltinIndex, NumFixed = 1;
4959 bool WarnAboutSemanticsChange = false;
4960 switch (BuiltinID) {
4961 default: llvm_unreachable("Unknown overloaded atomic builtin!");
4962 case Builtin::BI__sync_fetch_and_add:
4963 case Builtin::BI__sync_fetch_and_add_1:
4964 case Builtin::BI__sync_fetch_and_add_2:
4965 case Builtin::BI__sync_fetch_and_add_4:
4966 case Builtin::BI__sync_fetch_and_add_8:
4967 case Builtin::BI__sync_fetch_and_add_16:
4968 BuiltinIndex = 0;
4969 break;
4970
4971 case Builtin::BI__sync_fetch_and_sub:
4972 case Builtin::BI__sync_fetch_and_sub_1:
4973 case Builtin::BI__sync_fetch_and_sub_2:
4974 case Builtin::BI__sync_fetch_and_sub_4:
4975 case Builtin::BI__sync_fetch_and_sub_8:
4976 case Builtin::BI__sync_fetch_and_sub_16:
4977 BuiltinIndex = 1;
4978 break;
4979
4980 case Builtin::BI__sync_fetch_and_or:
4981 case Builtin::BI__sync_fetch_and_or_1:
4982 case Builtin::BI__sync_fetch_and_or_2:
4983 case Builtin::BI__sync_fetch_and_or_4:
4984 case Builtin::BI__sync_fetch_and_or_8:
4985 case Builtin::BI__sync_fetch_and_or_16:
4986 BuiltinIndex = 2;
4987 break;
4988
4989 case Builtin::BI__sync_fetch_and_and:
4990 case Builtin::BI__sync_fetch_and_and_1:
4991 case Builtin::BI__sync_fetch_and_and_2:
4992 case Builtin::BI__sync_fetch_and_and_4:
4993 case Builtin::BI__sync_fetch_and_and_8:
4994 case Builtin::BI__sync_fetch_and_and_16:
4995 BuiltinIndex = 3;
4996 break;
4997
4998 case Builtin::BI__sync_fetch_and_xor:
4999 case Builtin::BI__sync_fetch_and_xor_1:
5000 case Builtin::BI__sync_fetch_and_xor_2:
5001 case Builtin::BI__sync_fetch_and_xor_4:
5002 case Builtin::BI__sync_fetch_and_xor_8:
5003 case Builtin::BI__sync_fetch_and_xor_16:
5004 BuiltinIndex = 4;
5005 break;
5006
5007 case Builtin::BI__sync_fetch_and_nand:
5008 case Builtin::BI__sync_fetch_and_nand_1:
5009 case Builtin::BI__sync_fetch_and_nand_2:
5010 case Builtin::BI__sync_fetch_and_nand_4:
5011 case Builtin::BI__sync_fetch_and_nand_8:
5012 case Builtin::BI__sync_fetch_and_nand_16:
5013 BuiltinIndex = 5;
5014 WarnAboutSemanticsChange = true;
5015 break;
5016
5017 case Builtin::BI__sync_add_and_fetch:
5018 case Builtin::BI__sync_add_and_fetch_1:
5019 case Builtin::BI__sync_add_and_fetch_2:
5020 case Builtin::BI__sync_add_and_fetch_4:
5021 case Builtin::BI__sync_add_and_fetch_8:
5022 case Builtin::BI__sync_add_and_fetch_16:
5023 BuiltinIndex = 6;
5024 break;
5025
5026 case Builtin::BI__sync_sub_and_fetch:
5027 case Builtin::BI__sync_sub_and_fetch_1:
5028 case Builtin::BI__sync_sub_and_fetch_2:
5029 case Builtin::BI__sync_sub_and_fetch_4:
5030 case Builtin::BI__sync_sub_and_fetch_8:
5031 case Builtin::BI__sync_sub_and_fetch_16:
5032 BuiltinIndex = 7;
5033 break;
5034
5035 case Builtin::BI__sync_and_and_fetch:
5036 case Builtin::BI__sync_and_and_fetch_1:
5037 case Builtin::BI__sync_and_and_fetch_2:
5038 case Builtin::BI__sync_and_and_fetch_4:
5039 case Builtin::BI__sync_and_and_fetch_8:
5040 case Builtin::BI__sync_and_and_fetch_16:
5041 BuiltinIndex = 8;
5042 break;
5043
5044 case Builtin::BI__sync_or_and_fetch:
5045 case Builtin::BI__sync_or_and_fetch_1:
5046 case Builtin::BI__sync_or_and_fetch_2:
5047 case Builtin::BI__sync_or_and_fetch_4:
5048 case Builtin::BI__sync_or_and_fetch_8:
5049 case Builtin::BI__sync_or_and_fetch_16:
5050 BuiltinIndex = 9;
5051 break;
5052
5053 case Builtin::BI__sync_xor_and_fetch:
5054 case Builtin::BI__sync_xor_and_fetch_1:
5055 case Builtin::BI__sync_xor_and_fetch_2:
5056 case Builtin::BI__sync_xor_and_fetch_4:
5057 case Builtin::BI__sync_xor_and_fetch_8:
5058 case Builtin::BI__sync_xor_and_fetch_16:
5059 BuiltinIndex = 10;
5060 break;
5061
5062 case Builtin::BI__sync_nand_and_fetch:
5063 case Builtin::BI__sync_nand_and_fetch_1:
5064 case Builtin::BI__sync_nand_and_fetch_2:
5065 case Builtin::BI__sync_nand_and_fetch_4:
5066 case Builtin::BI__sync_nand_and_fetch_8:
5067 case Builtin::BI__sync_nand_and_fetch_16:
5068 BuiltinIndex = 11;
5069 WarnAboutSemanticsChange = true;
5070 break;
5071
5072 case Builtin::BI__sync_val_compare_and_swap:
5073 case Builtin::BI__sync_val_compare_and_swap_1:
5074 case Builtin::BI__sync_val_compare_and_swap_2:
5075 case Builtin::BI__sync_val_compare_and_swap_4:
5076 case Builtin::BI__sync_val_compare_and_swap_8:
5077 case Builtin::BI__sync_val_compare_and_swap_16:
5078 BuiltinIndex = 12;
5079 NumFixed = 2;
5080 break;
5081
5082 case Builtin::BI__sync_bool_compare_and_swap:
5083 case Builtin::BI__sync_bool_compare_and_swap_1:
5084 case Builtin::BI__sync_bool_compare_and_swap_2:
5085 case Builtin::BI__sync_bool_compare_and_swap_4:
5086 case Builtin::BI__sync_bool_compare_and_swap_8:
5087 case Builtin::BI__sync_bool_compare_and_swap_16:
5088 BuiltinIndex = 13;
5089 NumFixed = 2;
5090 ResultType = Context.BoolTy;
5091 break;
5092
5093 case Builtin::BI__sync_lock_test_and_set:
5094 case Builtin::BI__sync_lock_test_and_set_1:
5095 case Builtin::BI__sync_lock_test_and_set_2:
5096 case Builtin::BI__sync_lock_test_and_set_4:
5097 case Builtin::BI__sync_lock_test_and_set_8:
5098 case Builtin::BI__sync_lock_test_and_set_16:
5099 BuiltinIndex = 14;
5100 break;
5101
5102 case Builtin::BI__sync_lock_release:
5103 case Builtin::BI__sync_lock_release_1:
5104 case Builtin::BI__sync_lock_release_2:
5105 case Builtin::BI__sync_lock_release_4:
5106 case Builtin::BI__sync_lock_release_8:
5107 case Builtin::BI__sync_lock_release_16:
5108 BuiltinIndex = 15;
5109 NumFixed = 0;
5110 ResultType = Context.VoidTy;
5111 break;
5112
5113 case Builtin::BI__sync_swap:
5114 case Builtin::BI__sync_swap_1:
5115 case Builtin::BI__sync_swap_2:
5116 case Builtin::BI__sync_swap_4:
5117 case Builtin::BI__sync_swap_8:
5118 case Builtin::BI__sync_swap_16:
5119 BuiltinIndex = 16;
5120 break;
5121 }
5122
5123 // Now that we know how many fixed arguments we expect, first check that we
5124 // have at least that many.
5125 if (TheCall->getNumArgs() < 1+NumFixed) {
5126 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5127 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5128 << Callee->getSourceRange();
5129 return ExprError();
5130 }
5131
5132 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5133 << Callee->getSourceRange();
5134
5135 if (WarnAboutSemanticsChange) {
5136 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5137 << Callee->getSourceRange();
5138 }
5139
5140 // Get the decl for the concrete builtin from this, we can tell what the
5141 // concrete integer type we should convert to is.
5142 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5143 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5144 FunctionDecl *NewBuiltinDecl;
5145 if (NewBuiltinID == BuiltinID)
5146 NewBuiltinDecl = FDecl;
5147 else {
5148 // Perform builtin lookup to avoid redeclaring it.
5149 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5150 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5151 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5152 assert(Res.getFoundDecl());
5153 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5154 if (!NewBuiltinDecl)
5155 return ExprError();
5156 }
5157
5158 // The first argument --- the pointer --- has a fixed type; we
5159 // deduce the types of the rest of the arguments accordingly. Walk
5160 // the remaining arguments, converting them to the deduced value type.
5161 for (unsigned i = 0; i != NumFixed; ++i) {
5162 ExprResult Arg = TheCall->getArg(i+1);
5163
5164 // GCC does an implicit conversion to the pointer or integer ValType. This
5165 // can fail in some cases (1i -> int**), check for this error case now.
5166 // Initialize the argument.
5167 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5168 ValType, /*consume*/ false);
5169 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5170 if (Arg.isInvalid())
5171 return ExprError();
5172
5173 // Okay, we have something that *can* be converted to the right type. Check
5174 // to see if there is a potentially weird extension going on here. This can
5175 // happen when you do an atomic operation on something like an char* and
5176 // pass in 42. The 42 gets converted to char. This is even more strange
5177 // for things like 45.123 -> char, etc.
5178 // FIXME: Do this check.
5179 TheCall->setArg(i+1, Arg.get());
5180 }
5181
5182 // Create a new DeclRefExpr to refer to the new decl.
5183 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5184 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5185 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5186 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5187
5188 // Set the callee in the CallExpr.
5189 // FIXME: This loses syntactic information.
5190 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5191 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5192 CK_BuiltinFnToFnPtr);
5193 TheCall->setCallee(PromotedCall.get());
5194
5195 // Change the result type of the call to match the original value type. This
5196 // is arbitrary, but the codegen for these builtins ins design to handle it
5197 // gracefully.
5198 TheCall->setType(ResultType);
5199
5200 // Prohibit problematic uses of bit-precise integer types with atomic
5201 // builtins. The arguments would have already been converted to the first
5202 // argument's type, so only need to check the first argument.
5203 const auto *BitIntValType = ValType->getAs<BitIntType>();
5204 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
5205 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5206 return ExprError();
5207 }
5208
5209 return TheCallResult;
5210}
5211
5212ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5213 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5214 DeclRefExpr *DRE =
5216 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5217 unsigned BuiltinID = FDecl->getBuiltinID();
5218 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5219 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5220 "Unexpected nontemporal load/store builtin!");
5221 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5222 unsigned numArgs = isStore ? 2 : 1;
5223
5224 // Ensure that we have the proper number of arguments.
5225 if (checkArgCount(TheCall, numArgs))
5226 return ExprError();
5227
5228 // Inspect the last argument of the nontemporal builtin. This should always
5229 // be a pointer type, from which we imply the type of the memory access.
5230 // Because it is a pointer type, we don't have to worry about any implicit
5231 // casts here.
5232 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5233 ExprResult PointerArgResult =
5235
5236 if (PointerArgResult.isInvalid())
5237 return ExprError();
5238 PointerArg = PointerArgResult.get();
5239 TheCall->setArg(numArgs - 1, PointerArg);
5240
5241 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5242 if (!pointerType) {
5243 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5244 << PointerArg->getType() << PointerArg->getSourceRange();
5245 return ExprError();
5246 }
5247
5248 QualType ValType = pointerType->getPointeeType();
5249
5250 // Strip any qualifiers off ValType.
5251 ValType = ValType.getUnqualifiedType();
5252 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5253 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5254 !ValType->isVectorType()) {
5255 Diag(DRE->getBeginLoc(),
5256 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5257 << PointerArg->getType() << PointerArg->getSourceRange();
5258 return ExprError();
5259 }
5260
5261 if (!isStore) {
5262 TheCall->setType(ValType);
5263 return TheCallResult;
5264 }
5265
5266 ExprResult ValArg = TheCall->getArg(0);
5267 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5268 Context, ValType, /*consume*/ false);
5269 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5270 if (ValArg.isInvalid())
5271 return ExprError();
5272
5273 TheCall->setArg(0, ValArg.get());
5274 TheCall->setType(Context.VoidTy);
5275 return TheCallResult;
5276}
5277
5278/// CheckObjCString - Checks that the format string argument to the os_log()
5279/// and os_trace() functions is correct, and converts it to const char *.
5280ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5281 Arg = Arg->IgnoreParenCasts();
5282 auto *Literal = dyn_cast<StringLiteral>(Arg);
5283 if (!Literal) {
5284 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5285 Literal = ObjcLiteral->getString();
5286 }
5287 }
5288
5289 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
5290 return ExprError(
5291 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5292 << Arg->getSourceRange());
5293 }
5294
5295 ExprResult Result(Literal);
5296 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5297 InitializedEntity Entity =
5299 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5300 return Result;
5301}
5302
5303/// Check that the user is calling the appropriate va_start builtin for the
5304/// target and calling convention.
5305static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5306 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5307 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5308 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5309 TT.getArch() == llvm::Triple::aarch64_32);
5310 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
5311 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5312 if (IsX64 || IsAArch64) {
5313 CallingConv CC = CC_C;
5314 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5315 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5316 if (IsMSVAStart) {
5317 // Don't allow this in System V ABI functions.
5318 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
5319 return S.Diag(Fn->getBeginLoc(),
5320 diag::err_ms_va_start_used_in_sysv_function);
5321 } else {
5322 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5323 // On x64 Windows, don't allow this in System V ABI functions.
5324 // (Yes, that means there's no corresponding way to support variadic
5325 // System V ABI functions on Windows.)
5326 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
5327 (!IsWindowsOrUEFI && CC == CC_Win64))
5328 return S.Diag(Fn->getBeginLoc(),
5329 diag::err_va_start_used_in_wrong_abi_function)
5330 << !IsWindowsOrUEFI;
5331 }
5332 return false;
5333 }
5334
5335 if (IsMSVAStart)
5336 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5337 return false;
5338}
5339
5341 ParmVarDecl **LastParam = nullptr) {
5342 // Determine whether the current function, block, or obj-c method is variadic
5343 // and get its parameter list.
5344 bool IsVariadic = false;
5346 DeclContext *Caller = S.CurContext;
5347 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5348 IsVariadic = Block->isVariadic();
5349 Params = Block->parameters();
5350 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5351 IsVariadic = FD->isVariadic();
5352 Params = FD->parameters();
5353 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5354 IsVariadic = MD->isVariadic();
5355 // FIXME: This isn't correct for methods (results in bogus warning).
5356 Params = MD->parameters();
5357 } else if (isa<CapturedDecl>(Caller)) {
5358 // We don't support va_start in a CapturedDecl.
5359 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5360 return true;
5361 } else {
5362 // This must be some other declcontext that parses exprs.
5363 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5364 return true;
5365 }
5366
5367 if (!IsVariadic) {
5368 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5369 return true;
5370 }
5371
5372 if (LastParam)
5373 *LastParam = Params.empty() ? nullptr : Params.back();
5374
5375 return false;
5376}
5377
5378bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5379 Expr *Fn = TheCall->getCallee();
5380 if (checkVAStartABI(*this, BuiltinID, Fn))
5381 return true;
5382
5383 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
5384 // This builtin requires one argument (the va_list), allows two arguments,
5385 // but diagnoses more than two arguments. e.g.,
5386 // __builtin_c23_va_start(); // error
5387 // __builtin_c23_va_start(list); // ok
5388 // __builtin_c23_va_start(list, param); // ok
5389 // __builtin_c23_va_start(list, anything, anything); // error
5390 // This differs from the GCC behavior in that they accept the last case
5391 // with a warning, but it doesn't seem like a useful behavior to allow.
5392 if (checkArgCountRange(TheCall, 1, 2))
5393 return true;
5394 } else {
5395 // In C23 mode, va_start only needs one argument. However, the builtin still
5396 // requires two arguments (which matches the behavior of the GCC builtin),
5397 // <stdarg.h> passes `0` as the second argument in C23 mode.
5398 if (checkArgCount(TheCall, 2))
5399 return true;
5400 }
5401
5402 // Type-check the first argument normally.
5403 if (checkBuiltinArgument(*this, TheCall, 0))
5404 return true;
5405
5406 // Check that the current function is variadic, and get its last parameter.
5407 ParmVarDecl *LastParam;
5408 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5409 return true;
5410
5411 // Verify that the second argument to the builtin is the last non-variadic
5412 // argument of the current function or method. In C23 mode, if the call is
5413 // not to __builtin_c23_va_start, and the second argument is an integer
5414 // constant expression with value 0, then we don't bother with this check.
5415 // For __builtin_c23_va_start, we only perform the check for the second
5416 // argument being the last argument to the current function if there is a
5417 // second argument present.
5418 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
5419 TheCall->getNumArgs() < 2) {
5420 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5421 return false;
5422 }
5423
5424 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5425 if (std::optional<llvm::APSInt> Val =
5427 Val && LangOpts.C23 && *Val == 0 &&
5428 BuiltinID != Builtin::BI__builtin_c23_va_start) {
5429 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5430 return false;
5431 }
5432
5433 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
5434 // next block.
5435 QualType Type;
5436 SourceLocation ParamLoc;
5437 bool IsCRegister = false;
5438 bool SecondArgIsLastNonVariadicArgument = false;
5439 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5440 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5441 SecondArgIsLastNonVariadicArgument = PV == LastParam;
5442
5443 Type = PV->getType();
5444 ParamLoc = PV->getLocation();
5445 IsCRegister =
5446 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5447 }
5448 }
5449
5450 if (!SecondArgIsLastNonVariadicArgument)
5451 Diag(TheCall->getArg(1)->getBeginLoc(),
5452 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
5453 else if (IsCRegister || Type->isReferenceType() ||
5454 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5455 // Promotable integers are UB, but enumerations need a bit of
5456 // extra checking to see what their promotable type actually is.
5457 if (!Context.isPromotableIntegerType(Type))
5458 return false;
5459 const auto *ED = Type->getAsEnumDecl();
5460 if (!ED)
5461 return true;
5462 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
5463 }()) {
5464 unsigned Reason = 0;
5465 if (Type->isReferenceType()) Reason = 1;
5466 else if (IsCRegister) Reason = 2;
5467 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5468 Diag(ParamLoc, diag::note_parameter_type) << Type;
5469 }
5470
5471 return false;
5472}
5473
5474bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
5475 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
5476 const LangOptions &LO = getLangOpts();
5477
5478 if (LO.CPlusPlus)
5479 return Arg->getType()
5481 .getTypePtr()
5482 ->getPointeeType()
5484
5485 // In C, allow aliasing through `char *`, this is required for AArch64 at
5486 // least.
5487 return true;
5488 };
5489
5490 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5491 // const char *named_addr);
5492
5493 Expr *Func = Call->getCallee();
5494
5495 if (Call->getNumArgs() < 3)
5496 return Diag(Call->getEndLoc(),
5497 diag::err_typecheck_call_too_few_args_at_least)
5498 << 0 /*function call*/ << 3 << Call->getNumArgs()
5499 << /*is non object*/ 0;
5500
5501 // Type-check the first argument normally.
5502 if (checkBuiltinArgument(*this, Call, 0))
5503 return true;
5504
5505 // Check that the current function is variadic.
5507 return true;
5508
5509 // __va_start on Windows does not validate the parameter qualifiers
5510
5511 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5512 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5513
5514 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5515 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5516
5517 const QualType &ConstCharPtrTy =
5518 Context.getPointerType(Context.CharTy.withConst());
5519 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
5520 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5521 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5522 << 0 /* qualifier difference */
5523 << 3 /* parameter mismatch */
5524 << 2 << Arg1->getType() << ConstCharPtrTy;
5525
5526 const QualType SizeTy = Context.getSizeType();
5527 if (!Context.hasSameType(
5529 SizeTy))
5530 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5531 << Arg2->getType() << SizeTy << 1 /* different class */
5532 << 0 /* qualifier difference */
5533 << 3 /* parameter mismatch */
5534 << 3 << Arg2->getType() << SizeTy;
5535
5536 return false;
5537}
5538
5539bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
5540 if (checkArgCount(TheCall, 2))
5541 return true;
5542
5543 if (BuiltinID == Builtin::BI__builtin_isunordered &&
5544 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
5545 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5546 << 1 << 0 << TheCall->getSourceRange();
5547
5548 ExprResult OrigArg0 = TheCall->getArg(0);
5549 ExprResult OrigArg1 = TheCall->getArg(1);
5550
5551 // Do standard promotions between the two arguments, returning their common
5552 // type.
5553 QualType Res = UsualArithmeticConversions(
5554 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
5555 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5556 return true;
5557
5558 // Make sure any conversions are pushed back into the call; this is
5559 // type safe since unordered compare builtins are declared as "_Bool
5560 // foo(...)".
5561 TheCall->setArg(0, OrigArg0.get());
5562 TheCall->setArg(1, OrigArg1.get());
5563
5564 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5565 return false;
5566
5567 // If the common type isn't a real floating type, then the arguments were
5568 // invalid for this operation.
5569 if (Res.isNull() || !Res->isRealFloatingType())
5570 return Diag(OrigArg0.get()->getBeginLoc(),
5571 diag::err_typecheck_call_invalid_ordered_compare)
5572 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5573 << SourceRange(OrigArg0.get()->getBeginLoc(),
5574 OrigArg1.get()->getEndLoc());
5575
5576 return false;
5577}
5578
5579bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
5580 unsigned BuiltinID) {
5581 if (checkArgCount(TheCall, NumArgs))
5582 return true;
5583
5584 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
5585 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
5586 BuiltinID == Builtin::BI__builtin_isinf ||
5587 BuiltinID == Builtin::BI__builtin_isinf_sign))
5588 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5589 << 0 << 0 << TheCall->getSourceRange();
5590
5591 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
5592 BuiltinID == Builtin::BI__builtin_isunordered))
5593 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5594 << 1 << 0 << TheCall->getSourceRange();
5595
5596 bool IsFPClass = NumArgs == 2;
5597
5598 // Find out position of floating-point argument.
5599 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
5600
5601 // We can count on all parameters preceding the floating-point just being int.
5602 // Try all of those.
5603 for (unsigned i = 0; i < FPArgNo; ++i) {
5604 Expr *Arg = TheCall->getArg(i);
5605
5606 if (Arg->isTypeDependent())
5607 return false;
5608
5611
5612 if (Res.isInvalid())
5613 return true;
5614 TheCall->setArg(i, Res.get());
5615 }
5616
5617 Expr *OrigArg = TheCall->getArg(FPArgNo);
5618
5619 if (OrigArg->isTypeDependent())
5620 return false;
5621
5622 // Usual Unary Conversions will convert half to float, which we want for
5623 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5624 // type how it is, but do normal L->Rvalue conversions.
5625 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) {
5626 ExprResult Res = UsualUnaryConversions(OrigArg);
5627
5628 if (!Res.isUsable())
5629 return true;
5630 OrigArg = Res.get();
5631 } else {
5633
5634 if (!Res.isUsable())
5635 return true;
5636 OrigArg = Res.get();
5637 }
5638 TheCall->setArg(FPArgNo, OrigArg);
5639
5640 QualType VectorResultTy;
5641 QualType ElementTy = OrigArg->getType();
5642 // TODO: When all classification function are implemented with is_fpclass,
5643 // vector argument can be supported in all of them.
5644 if (ElementTy->isVectorType() && IsFPClass) {
5645 VectorResultTy = GetSignedVectorType(ElementTy);
5646 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
5647 }
5648
5649 // This operation requires a non-_Complex floating-point number.
5650 if (!ElementTy->isRealFloatingType())
5651 return Diag(OrigArg->getBeginLoc(),
5652 diag::err_typecheck_call_invalid_unary_fp)
5653 << OrigArg->getType() << OrigArg->getSourceRange();
5654
5655 // __builtin_isfpclass has integer parameter that specify test mask. It is
5656 // passed in (...), so it should be analyzed completely here.
5657 if (IsFPClass)
5658 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
5659 return true;
5660
5661 // TODO: enable this code to all classification functions.
5662 if (IsFPClass) {
5663 QualType ResultTy;
5664 if (!VectorResultTy.isNull())
5665 ResultTy = VectorResultTy;
5666 else
5667 ResultTy = Context.IntTy;
5668 TheCall->setType(ResultTy);
5669 }
5670
5671 return false;
5672}
5673
5674bool Sema::BuiltinComplex(CallExpr *TheCall) {
5675 if (checkArgCount(TheCall, 2))
5676 return true;
5677
5678 bool Dependent = false;
5679 for (unsigned I = 0; I != 2; ++I) {
5680 Expr *Arg = TheCall->getArg(I);
5681 QualType T = Arg->getType();
5682 if (T->isDependentType()) {
5683 Dependent = true;
5684 continue;
5685 }
5686
5687 // Despite supporting _Complex int, GCC requires a real floating point type
5688 // for the operands of __builtin_complex.
5689 if (!T->isRealFloatingType()) {
5690 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
5691 << Arg->getType() << Arg->getSourceRange();
5692 }
5693
5694 ExprResult Converted = DefaultLvalueConversion(Arg);
5695 if (Converted.isInvalid())
5696 return true;
5697 TheCall->setArg(I, Converted.get());
5698 }
5699
5700 if (Dependent) {
5701 TheCall->setType(Context.DependentTy);
5702 return false;
5703 }
5704
5705 Expr *Real = TheCall->getArg(0);
5706 Expr *Imag = TheCall->getArg(1);
5707 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
5708 return Diag(Real->getBeginLoc(),
5709 diag::err_typecheck_call_different_arg_types)
5710 << Real->getType() << Imag->getType()
5711 << Real->getSourceRange() << Imag->getSourceRange();
5712 }
5713
5714 TheCall->setType(Context.getComplexType(Real->getType()));
5715 return false;
5716}
5717
5718/// BuiltinShuffleVector - Handle __builtin_shufflevector.
5719// This is declared to take (...), so we have to check everything.
5721 unsigned NumArgs = TheCall->getNumArgs();
5722 if (NumArgs < 2)
5723 return ExprError(Diag(TheCall->getEndLoc(),
5724 diag::err_typecheck_call_too_few_args_at_least)
5725 << 0 /*function call*/ << 2 << NumArgs
5726 << /*is non object*/ 0 << TheCall->getSourceRange());
5727
5728 // Determine which of the following types of shufflevector we're checking:
5729 // 1) unary, vector mask: (lhs, mask)
5730 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5731 QualType ResType = TheCall->getArg(0)->getType();
5732 unsigned NumElements = 0;
5733
5734 if (!TheCall->getArg(0)->isTypeDependent() &&
5735 !TheCall->getArg(1)->isTypeDependent()) {
5736 QualType LHSType = TheCall->getArg(0)->getType();
5737 QualType RHSType = TheCall->getArg(1)->getType();
5738
5739 if (!LHSType->isVectorType() || !RHSType->isVectorType())
5740 return ExprError(
5741 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5742 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
5743 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5744 TheCall->getArg(1)->getEndLoc()));
5745
5746 NumElements = LHSType->castAs<VectorType>()->getNumElements();
5747 unsigned NumResElements = NumArgs - 2;
5748
5749 // Check to see if we have a call with 2 vector arguments, the unary shuffle
5750 // with mask. If so, verify that RHS is an integer vector type with the
5751 // same number of elts as lhs.
5752 if (NumArgs == 2) {
5753 if (!RHSType->hasIntegerRepresentation() ||
5754 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
5755 return ExprError(Diag(TheCall->getBeginLoc(),
5756 diag::err_vec_builtin_incompatible_vector)
5757 << TheCall->getDirectCallee()
5758 << /*isMoreThanTwoArgs*/ false
5759 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5760 TheCall->getArg(1)->getEndLoc()));
5761 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5762 return ExprError(Diag(TheCall->getBeginLoc(),
5763 diag::err_vec_builtin_incompatible_vector)
5764 << TheCall->getDirectCallee()
5765 << /*isMoreThanTwoArgs*/ false
5766 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5767 TheCall->getArg(1)->getEndLoc()));
5768 } else if (NumElements != NumResElements) {
5769 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
5770 ResType = ResType->isExtVectorType()
5771 ? Context.getExtVectorType(EltType, NumResElements)
5772 : Context.getVectorType(EltType, NumResElements,
5774 }
5775 }
5776
5777 for (unsigned I = 2; I != NumArgs; ++I) {
5778 Expr *Arg = TheCall->getArg(I);
5779 if (Arg->isTypeDependent() || Arg->isValueDependent())
5780 continue;
5781
5782 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
5783 if (!Result)
5784 return ExprError(Diag(TheCall->getBeginLoc(),
5785 diag::err_shufflevector_nonconstant_argument)
5786 << Arg->getSourceRange());
5787
5788 // Allow -1 which will be translated to undef in the IR.
5789 if (Result->isSigned() && Result->isAllOnes())
5790 ;
5791 else if (Result->getActiveBits() > 64 ||
5792 Result->getZExtValue() >= NumElements * 2)
5793 return ExprError(Diag(TheCall->getBeginLoc(),
5794 diag::err_shufflevector_argument_too_large)
5795 << Arg->getSourceRange());
5796
5797 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
5798 }
5799
5800 auto *Result = new (Context) ShuffleVectorExpr(
5801 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
5802 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
5803
5804 // All moved to Result.
5805 TheCall->shrinkNumArgs(0);
5806 return Result;
5807}
5808
5810 SourceLocation BuiltinLoc,
5811 SourceLocation RParenLoc) {
5814 QualType DstTy = TInfo->getType();
5815 QualType SrcTy = E->getType();
5816
5817 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5818 return ExprError(Diag(BuiltinLoc,
5819 diag::err_convertvector_non_vector)
5820 << E->getSourceRange());
5821 if (!DstTy->isVectorType() && !DstTy->isDependentType())
5822 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
5823 << "second"
5824 << "__builtin_convertvector");
5825
5826 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5827 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5828 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5829 if (SrcElts != DstElts)
5830 return ExprError(Diag(BuiltinLoc,
5831 diag::err_convertvector_incompatible_vector)
5832 << E->getSourceRange());
5833 }
5834
5835 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
5836 RParenLoc, CurFPFeatureOverrides());
5837}
5838
5839bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
5840 unsigned NumArgs = TheCall->getNumArgs();
5841
5842 if (NumArgs > 3)
5843 return Diag(TheCall->getEndLoc(),
5844 diag::err_typecheck_call_too_many_args_at_most)
5845 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
5846 << TheCall->getSourceRange();
5847
5848 // Argument 0 is checked for us and the remaining arguments must be
5849 // constant integers.
5850 for (unsigned i = 1; i != NumArgs; ++i)
5851 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5852 return true;
5853
5854 return false;
5855}
5856
5857bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
5858 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
5859 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
5860 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5861 if (checkArgCount(TheCall, 1))
5862 return true;
5863 Expr *Arg = TheCall->getArg(0);
5864 if (Arg->isInstantiationDependent())
5865 return false;
5866
5867 QualType ArgTy = Arg->getType();
5868 if (!ArgTy->hasFloatingRepresentation())
5869 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
5870 << ArgTy;
5871 if (Arg->isLValue()) {
5872 ExprResult FirstArg = DefaultLvalueConversion(Arg);
5873 TheCall->setArg(0, FirstArg.get());
5874 }
5875 TheCall->setType(TheCall->getArg(0)->getType());
5876 return false;
5877}
5878
5879bool Sema::BuiltinAssume(CallExpr *TheCall) {
5880 Expr *Arg = TheCall->getArg(0);
5881 if (Arg->isInstantiationDependent()) return false;
5882
5883 if (Arg->HasSideEffects(Context))
5884 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5885 << Arg->getSourceRange()
5886 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5887
5888 return false;
5889}
5890
5891bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
5892 // The alignment must be a constant integer.
5893 Expr *Arg = TheCall->getArg(1);
5894
5895 // We can't check the value of a dependent argument.
5896 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5897 if (const auto *UE =
5898 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5899 if (UE->getKind() == UETT_AlignOf ||
5900 UE->getKind() == UETT_PreferredAlignOf)
5901 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5902 << Arg->getSourceRange();
5903
5904 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5905
5906 if (!Result.isPowerOf2())
5907 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5908 << Arg->getSourceRange();
5909
5910 if (Result < Context.getCharWidth())
5911 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5912 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5913
5914 if (Result > std::numeric_limits<int32_t>::max())
5915 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5916 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5917 }
5918
5919 return false;
5920}
5921
5922bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
5923 if (checkArgCountRange(TheCall, 2, 3))
5924 return true;
5925
5926 unsigned NumArgs = TheCall->getNumArgs();
5927 Expr *FirstArg = TheCall->getArg(0);
5928
5929 {
5930 ExprResult FirstArgResult =
5932 if (!FirstArgResult.get()->getType()->isPointerType()) {
5933 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
5934 << TheCall->getSourceRange();
5935 return true;
5936 }
5937 TheCall->setArg(0, FirstArgResult.get());
5938 }
5939
5940 // The alignment must be a constant integer.
5941 Expr *SecondArg = TheCall->getArg(1);
5942
5943 // We can't check the value of a dependent argument.
5944 if (!SecondArg->isValueDependent()) {
5945 llvm::APSInt Result;
5946 if (BuiltinConstantArg(TheCall, 1, Result))
5947 return true;
5948
5949 if (!Result.isPowerOf2())
5950 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5951 << SecondArg->getSourceRange();
5952
5954 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
5955 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
5956
5957 TheCall->setArg(1,
5959 }
5960
5961 if (NumArgs > 2) {
5962 Expr *ThirdArg = TheCall->getArg(2);
5963 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
5964 return true;
5965 TheCall->setArg(2, ThirdArg);
5966 }
5967
5968 return false;
5969}
5970
5971bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
5972 unsigned BuiltinID =
5973 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5974 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5975
5976 unsigned NumArgs = TheCall->getNumArgs();
5977 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5978 if (NumArgs < NumRequiredArgs) {
5979 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5980 << 0 /* function call */ << NumRequiredArgs << NumArgs
5981 << /*is non object*/ 0 << TheCall->getSourceRange();
5982 }
5983 if (NumArgs >= NumRequiredArgs + 0x100) {
5984 return Diag(TheCall->getEndLoc(),
5985 diag::err_typecheck_call_too_many_args_at_most)
5986 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5987 << /*is non object*/ 0 << TheCall->getSourceRange();
5988 }
5989 unsigned i = 0;
5990
5991 // For formatting call, check buffer arg.
5992 if (!IsSizeCall) {
5993 ExprResult Arg(TheCall->getArg(i));
5994 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5995 Context, Context.VoidPtrTy, false);
5996 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5997 if (Arg.isInvalid())
5998 return true;
5999 TheCall->setArg(i, Arg.get());
6000 i++;
6001 }
6002
6003 // Check string literal arg.
6004 unsigned FormatIdx = i;
6005 {
6006 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6007 if (Arg.isInvalid())
6008 return true;
6009 TheCall->setArg(i, Arg.get());
6010 i++;
6011 }
6012
6013 // Make sure variadic args are scalar.
6014 unsigned FirstDataArg = i;
6015 while (i < NumArgs) {
6017 TheCall->getArg(i), VariadicCallType::Function, nullptr);
6018 if (Arg.isInvalid())
6019 return true;
6020 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6021 if (ArgSize.getQuantity() >= 0x100) {
6022 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6023 << i << (int)ArgSize.getQuantity() << 0xff
6024 << TheCall->getSourceRange();
6025 }
6026 TheCall->setArg(i, Arg.get());
6027 i++;
6028 }
6029
6030 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6031 // call to avoid duplicate diagnostics.
6032 if (!IsSizeCall) {
6033 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6034 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6035 bool Success = CheckFormatArguments(
6036 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
6038 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
6039 if (!Success)
6040 return true;
6041 }
6042
6043 if (IsSizeCall) {
6044 TheCall->setType(Context.getSizeType());
6045 } else {
6046 TheCall->setType(Context.VoidPtrTy);
6047 }
6048 return false;
6049}
6050
6051bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6052 llvm::APSInt &Result) {
6053 Expr *Arg = TheCall->getArg(ArgNum);
6054
6055 if (Arg->isTypeDependent() || Arg->isValueDependent())
6056 return false;
6057
6058 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
6059 if (!R) {
6060 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6061 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
6062 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6063 << FDecl->getDeclName() << Arg->getSourceRange();
6064 }
6065 Result = *R;
6066
6067 return false;
6068}
6069
6070bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6071 int High, bool RangeIsError) {
6073 return false;
6074 llvm::APSInt Result;
6075
6076 // We can't check the value of a dependent argument.
6077 Expr *Arg = TheCall->getArg(ArgNum);
6078 if (Arg->isTypeDependent() || Arg->isValueDependent())
6079 return false;
6080
6081 // Check constant-ness first.
6082 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6083 return true;
6084
6085 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6086 if (RangeIsError)
6087 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6088 << toString(Result, 10) << Low << High << Arg->getSourceRange();
6089 else
6090 // Defer the warning until we know if the code will be emitted so that
6091 // dead code can ignore this.
6092 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6093 PDiag(diag::warn_argument_invalid_range)
6094 << toString(Result, 10) << Low << High
6095 << Arg->getSourceRange());
6096 }
6097
6098 return false;
6099}
6100
6101bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6102 unsigned Num) {
6103 llvm::APSInt Result;
6104
6105 // We can't check the value of a dependent argument.
6106 Expr *Arg = TheCall->getArg(ArgNum);
6107 if (Arg->isTypeDependent() || Arg->isValueDependent())
6108 return false;
6109
6110 // Check constant-ness first.
6111 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6112 return true;
6113
6114 if (Result.getSExtValue() % Num != 0)
6115 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6116 << Num << Arg->getSourceRange();
6117
6118 return false;
6119}
6120
6121bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6122 llvm::APSInt Result;
6123
6124 // We can't check the value of a dependent argument.
6125 Expr *Arg = TheCall->getArg(ArgNum);
6126 if (Arg->isTypeDependent() || Arg->isValueDependent())
6127 return false;
6128
6129 // Check constant-ness first.
6130 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6131 return true;
6132
6133 if (Result.isPowerOf2())
6134 return false;
6135
6136 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6137 << Arg->getSourceRange();
6138}
6139
6140static bool IsShiftedByte(llvm::APSInt Value) {
6141 if (Value.isNegative())
6142 return false;
6143
6144 // Check if it's a shifted byte, by shifting it down
6145 while (true) {
6146 // If the value fits in the bottom byte, the check passes.
6147 if (Value < 0x100)
6148 return true;
6149
6150 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6151 // fails.
6152 if ((Value & 0xFF) != 0)
6153 return false;
6154
6155 // If the bottom 8 bits are all 0, but something above that is nonzero,
6156 // then shifting the value right by 8 bits won't affect whether it's a
6157 // shifted byte or not. So do that, and go round again.
6158 Value >>= 8;
6159 }
6160}
6161
6162bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6163 unsigned ArgBits) {
6164 llvm::APSInt Result;
6165
6166 // We can't check the value of a dependent argument.
6167 Expr *Arg = TheCall->getArg(ArgNum);
6168 if (Arg->isTypeDependent() || Arg->isValueDependent())
6169 return false;
6170
6171 // Check constant-ness first.
6172 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6173 return true;
6174
6175 // Truncate to the given size.
6176 Result = Result.getLoBits(ArgBits);
6177 Result.setIsUnsigned(true);
6178
6179 if (IsShiftedByte(Result))
6180 return false;
6181
6182 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6183 << Arg->getSourceRange();
6184}
6185
6187 unsigned ArgNum,
6188 unsigned ArgBits) {
6189 llvm::APSInt Result;
6190
6191 // We can't check the value of a dependent argument.
6192 Expr *Arg = TheCall->getArg(ArgNum);
6193 if (Arg->isTypeDependent() || Arg->isValueDependent())
6194 return false;
6195
6196 // Check constant-ness first.
6197 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6198 return true;
6199
6200 // Truncate to the given size.
6201 Result = Result.getLoBits(ArgBits);
6202 Result.setIsUnsigned(true);
6203
6204 // Check to see if it's in either of the required forms.
6205 if (IsShiftedByte(Result) ||
6206 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6207 return false;
6208
6209 return Diag(TheCall->getBeginLoc(),
6210 diag::err_argument_not_shifted_byte_or_xxff)
6211 << Arg->getSourceRange();
6212}
6213
6214bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6215 if (!Context.getTargetInfo().hasSjLjLowering())
6216 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6217 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6218
6219 Expr *Arg = TheCall->getArg(1);
6220 llvm::APSInt Result;
6221
6222 // TODO: This is less than ideal. Overload this to take a value.
6223 if (BuiltinConstantArg(TheCall, 1, Result))
6224 return true;
6225
6226 if (Result != 1)
6227 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6228 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6229
6230 return false;
6231}
6232
6233bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6234 if (!Context.getTargetInfo().hasSjLjLowering())
6235 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6236 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6237 return false;
6238}
6239
6240bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
6241 if (checkArgCount(TheCall, 1))
6242 return true;
6243
6244 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
6245 if (ArgRes.isInvalid())
6246 return true;
6247
6248 // For simplicity, we support only limited expressions for the argument.
6249 // Specifically a pointer to a flexible array member:'ptr->array'. This
6250 // allows us to reject arguments with complex casting, which really shouldn't
6251 // be a huge problem.
6252 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
6253 if (!isa<PointerType>(Arg->getType()) && !Arg->getType()->isArrayType())
6254 return Diag(Arg->getBeginLoc(),
6255 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
6256 << Arg->getSourceRange();
6257
6258 if (Arg->HasSideEffects(Context))
6259 return Diag(Arg->getBeginLoc(),
6260 diag::err_builtin_counted_by_ref_has_side_effects)
6261 << Arg->getSourceRange();
6262
6263 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
6264 if (!ME->isFlexibleArrayMemberLike(
6265 Context, getLangOpts().getStrictFlexArraysLevel()))
6266 return Diag(Arg->getBeginLoc(),
6267 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
6268 << Arg->getSourceRange();
6269
6270 if (auto *CATy =
6271 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
6272 CATy && CATy->getKind() == CountAttributedType::CountedBy) {
6273 const auto *FAMDecl = cast<FieldDecl>(ME->getMemberDecl());
6274 if (const FieldDecl *CountFD = FAMDecl->findCountedByField()) {
6275 TheCall->setType(Context.getPointerType(CountFD->getType()));
6276 return false;
6277 }
6278 }
6279 } else {
6280 return Diag(Arg->getBeginLoc(),
6281 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
6282 << Arg->getSourceRange();
6283 }
6284
6285 TheCall->setType(Context.getPointerType(Context.VoidTy));
6286 return false;
6287}
6288
6289/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
6290/// It allows leaking and modification of bounds safety information.
6291bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
6293 const CallExpr *CE =
6294 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
6295 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
6296 return false;
6297
6298 switch (K) {
6301 Diag(E->getExprLoc(),
6302 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6303 << 0 << E->getSourceRange();
6304 break;
6306 Diag(E->getExprLoc(),
6307 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6308 << 1 << E->getSourceRange();
6309 break;
6311 Diag(E->getExprLoc(),
6312 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6313 << 2 << E->getSourceRange();
6314 break;
6316 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6317 << 0 << E->getSourceRange();
6318 break;
6320 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6321 << 1 << E->getSourceRange();
6322 break;
6323 }
6324
6325 return true;
6326}
6327
6328namespace {
6329
6330class UncoveredArgHandler {
6331 enum { Unknown = -1, AllCovered = -2 };
6332
6333 signed FirstUncoveredArg = Unknown;
6334 SmallVector<const Expr *, 4> DiagnosticExprs;
6335
6336public:
6337 UncoveredArgHandler() = default;
6338
6339 bool hasUncoveredArg() const {
6340 return (FirstUncoveredArg >= 0);
6341 }
6342
6343 unsigned getUncoveredArg() const {
6344 assert(hasUncoveredArg() && "no uncovered argument");
6345 return FirstUncoveredArg;
6346 }
6347
6348 void setAllCovered() {
6349 // A string has been found with all arguments covered, so clear out
6350 // the diagnostics.
6351 DiagnosticExprs.clear();
6352 FirstUncoveredArg = AllCovered;
6353 }
6354
6355 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6356 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6357
6358 // Don't update if a previous string covers all arguments.
6359 if (FirstUncoveredArg == AllCovered)
6360 return;
6361
6362 // UncoveredArgHandler tracks the highest uncovered argument index
6363 // and with it all the strings that match this index.
6364 if (NewFirstUncoveredArg == FirstUncoveredArg)
6365 DiagnosticExprs.push_back(StrExpr);
6366 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6367 DiagnosticExprs.clear();
6368 DiagnosticExprs.push_back(StrExpr);
6369 FirstUncoveredArg = NewFirstUncoveredArg;
6370 }
6371 }
6372
6373 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6374};
6375
6376enum StringLiteralCheckType {
6377 SLCT_NotALiteral,
6378 SLCT_UncheckedLiteral,
6379 SLCT_CheckedLiteral
6380};
6381
6382} // namespace
6383
6384static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6385 BinaryOperatorKind BinOpKind,
6386 bool AddendIsRight) {
6387 unsigned BitWidth = Offset.getBitWidth();
6388 unsigned AddendBitWidth = Addend.getBitWidth();
6389 // There might be negative interim results.
6390 if (Addend.isUnsigned()) {
6391 Addend = Addend.zext(++AddendBitWidth);
6392 Addend.setIsSigned(true);
6393 }
6394 // Adjust the bit width of the APSInts.
6395 if (AddendBitWidth > BitWidth) {
6396 Offset = Offset.sext(AddendBitWidth);
6397 BitWidth = AddendBitWidth;
6398 } else if (BitWidth > AddendBitWidth) {
6399 Addend = Addend.sext(BitWidth);
6400 }
6401
6402 bool Ov = false;
6403 llvm::APSInt ResOffset = Offset;
6404 if (BinOpKind == BO_Add)
6405 ResOffset = Offset.sadd_ov(Addend, Ov);
6406 else {
6407 assert(AddendIsRight && BinOpKind == BO_Sub &&
6408 "operator must be add or sub with addend on the right");
6409 ResOffset = Offset.ssub_ov(Addend, Ov);
6410 }
6411
6412 // We add an offset to a pointer here so we should support an offset as big as
6413 // possible.
6414 if (Ov) {
6415 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6416 "index (intermediate) result too big");
6417 Offset = Offset.sext(2 * BitWidth);
6418 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6419 return;
6420 }
6421
6422 Offset = ResOffset;
6423}
6424
6425namespace {
6426
6427// This is a wrapper class around StringLiteral to support offsetted string
6428// literals as format strings. It takes the offset into account when returning
6429// the string and its length or the source locations to display notes correctly.
6430class FormatStringLiteral {
6431 const StringLiteral *FExpr;
6432 int64_t Offset;
6433
6434public:
6435 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6436 : FExpr(fexpr), Offset(Offset) {}
6437
6438 const StringLiteral *getFormatString() const { return FExpr; }
6439
6440 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
6441
6442 unsigned getByteLength() const {
6443 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6444 }
6445
6446 unsigned getLength() const { return FExpr->getLength() - Offset; }
6447 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6448
6449 StringLiteralKind getKind() const { return FExpr->getKind(); }
6450
6451 QualType getType() const { return FExpr->getType(); }
6452
6453 bool isAscii() const { return FExpr->isOrdinary(); }
6454 bool isWide() const { return FExpr->isWide(); }
6455 bool isUTF8() const { return FExpr->isUTF8(); }
6456 bool isUTF16() const { return FExpr->isUTF16(); }
6457 bool isUTF32() const { return FExpr->isUTF32(); }
6458 bool isPascal() const { return FExpr->isPascal(); }
6459
6460 SourceLocation getLocationOfByte(
6461 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6462 const TargetInfo &Target, unsigned *StartToken = nullptr,
6463 unsigned *StartTokenByteOffset = nullptr) const {
6464 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6465 StartToken, StartTokenByteOffset);
6466 }
6467
6468 SourceLocation getBeginLoc() const LLVM_READONLY {
6469 return FExpr->getBeginLoc().getLocWithOffset(Offset);
6470 }
6471
6472 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6473};
6474
6475} // namespace
6476
6477static void CheckFormatString(
6478 Sema &S, const FormatStringLiteral *FExpr,
6479 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
6481 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6482 bool inFunctionCall, VariadicCallType CallType,
6483 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6484 bool IgnoreStringsWithoutSpecifiers);
6485
6486static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
6487 const Expr *E);
6488
6489// Determine if an expression is a string literal or constant string.
6490// If this function returns false on the arguments to a function expecting a
6491// format string, we will usually need to emit a warning.
6492// True string literals are then checked by CheckFormatString.
6493static StringLiteralCheckType checkFormatStringExpr(
6494 Sema &S, const StringLiteral *ReferenceFormatString, const Expr *E,
6496 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6497 VariadicCallType CallType, bool InFunctionCall,
6498 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6499 llvm::APSInt Offset, bool IgnoreStringsWithoutSpecifiers = false) {
6501 return SLCT_NotALiteral;
6502tryAgain:
6503 assert(Offset.isSigned() && "invalid offset");
6504
6505 if (E->isTypeDependent() || E->isValueDependent())
6506 return SLCT_NotALiteral;
6507
6508 E = E->IgnoreParenCasts();
6509
6511 // Technically -Wformat-nonliteral does not warn about this case.
6512 // The behavior of printf and friends in this case is implementation
6513 // dependent. Ideally if the format string cannot be null then
6514 // it should have a 'nonnull' attribute in the function prototype.
6515 return SLCT_UncheckedLiteral;
6516
6517 switch (E->getStmtClass()) {
6518 case Stmt::InitListExprClass:
6519 // Handle expressions like {"foobar"}.
6520 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
6521 return checkFormatStringExpr(
6522 S, ReferenceFormatString, SLE, Args, APK, format_idx, firstDataArg,
6523 Type, CallType, /*InFunctionCall*/ false, CheckedVarArgs,
6524 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6525 }
6526 return SLCT_NotALiteral;
6527 case Stmt::BinaryConditionalOperatorClass:
6528 case Stmt::ConditionalOperatorClass: {
6529 // The expression is a literal if both sub-expressions were, and it was
6530 // completely checked only if both sub-expressions were checked.
6533
6534 // Determine whether it is necessary to check both sub-expressions, for
6535 // example, because the condition expression is a constant that can be
6536 // evaluated at compile time.
6537 bool CheckLeft = true, CheckRight = true;
6538
6539 bool Cond;
6540 if (C->getCond()->EvaluateAsBooleanCondition(
6542 if (Cond)
6543 CheckRight = false;
6544 else
6545 CheckLeft = false;
6546 }
6547
6548 // We need to maintain the offsets for the right and the left hand side
6549 // separately to check if every possible indexed expression is a valid
6550 // string literal. They might have different offsets for different string
6551 // literals in the end.
6552 StringLiteralCheckType Left;
6553 if (!CheckLeft)
6554 Left = SLCT_UncheckedLiteral;
6555 else {
6556 Left = checkFormatStringExpr(
6557 S, ReferenceFormatString, C->getTrueExpr(), Args, APK, format_idx,
6558 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6559 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6560 if (Left == SLCT_NotALiteral || !CheckRight) {
6561 return Left;
6562 }
6563 }
6564
6565 StringLiteralCheckType Right = checkFormatStringExpr(
6566 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
6567 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6568 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6569
6570 return (CheckLeft && Left < Right) ? Left : Right;
6571 }
6572
6573 case Stmt::ImplicitCastExprClass:
6574 E = cast<ImplicitCastExpr>(E)->getSubExpr();
6575 goto tryAgain;
6576
6577 case Stmt::OpaqueValueExprClass:
6578 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6579 E = src;
6580 goto tryAgain;
6581 }
6582 return SLCT_NotALiteral;
6583
6584 case Stmt::PredefinedExprClass:
6585 // While __func__, etc., are technically not string literals, they
6586 // cannot contain format specifiers and thus are not a security
6587 // liability.
6588 return SLCT_UncheckedLiteral;
6589
6590 case Stmt::DeclRefExprClass: {
6591 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6592
6593 // As an exception, do not flag errors for variables binding to
6594 // const string literals.
6595 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6596 bool isConstant = false;
6597 QualType T = DR->getType();
6598
6599 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6600 isConstant = AT->getElementType().isConstant(S.Context);
6601 } else if (const PointerType *PT = T->getAs<PointerType>()) {
6602 isConstant = T.isConstant(S.Context) &&
6603 PT->getPointeeType().isConstant(S.Context);
6604 } else if (T->isObjCObjectPointerType()) {
6605 // In ObjC, there is usually no "const ObjectPointer" type,
6606 // so don't check if the pointee type is constant.
6607 isConstant = T.isConstant(S.Context);
6608 }
6609
6610 if (isConstant) {
6611 if (const Expr *Init = VD->getAnyInitializer()) {
6612 // Look through initializers like const char c[] = { "foo" }
6613 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6614 if (InitList->isStringLiteralInit())
6615 Init = InitList->getInit(0)->IgnoreParenImpCasts();
6616 }
6617 return checkFormatStringExpr(
6618 S, ReferenceFormatString, Init, Args, APK, format_idx,
6619 firstDataArg, Type, CallType,
6620 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg, Offset);
6621 }
6622 }
6623
6624 // When the format argument is an argument of this function, and this
6625 // function also has the format attribute, there are several interactions
6626 // for which there shouldn't be a warning. For instance, when calling
6627 // v*printf from a function that has the printf format attribute, we
6628 // should not emit a warning about using `fmt`, even though it's not
6629 // constant, because the arguments have already been checked for the
6630 // caller of `logmessage`:
6631 //
6632 // __attribute__((format(printf, 1, 2)))
6633 // void logmessage(char const *fmt, ...) {
6634 // va_list ap;
6635 // va_start(ap, fmt);
6636 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
6637 // ...
6638 // }
6639 //
6640 // Another interaction that we need to support is using a format string
6641 // specified by the format_matches attribute:
6642 //
6643 // __attribute__((format_matches(printf, 1, "%s %d")))
6644 // void logmessage(char const *fmt, const char *a, int b) {
6645 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
6646 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
6647 // ...
6648 // }
6649 //
6650 // Yet another interaction that we need to support is calling a variadic
6651 // format function from a format function that has fixed arguments. For
6652 // instance:
6653 //
6654 // __attribute__((format(printf, 1, 2)))
6655 // void logstring(char const *fmt, char const *str) {
6656 // printf(fmt, str); /* do not emit a warning about "fmt" */
6657 // }
6658 //
6659 // Same (and perhaps more relatably) for the variadic template case:
6660 //
6661 // template<typename... Args>
6662 // __attribute__((format(printf, 1, 2)))
6663 // void log(const char *fmt, Args&&... args) {
6664 // printf(fmt, forward<Args>(args)...);
6665 // /* do not emit a warning about "fmt" */
6666 // }
6667 //
6668 // Due to implementation difficulty, we only check the format, not the
6669 // format arguments, in all cases.
6670 //
6671 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
6672 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
6673 for (const auto *PVFormatMatches :
6674 D->specific_attrs<FormatMatchesAttr>()) {
6675 Sema::FormatStringInfo CalleeFSI;
6676 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
6677 0, &CalleeFSI))
6678 continue;
6679 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
6680 // If using the wrong type of format string, emit a diagnostic
6681 // here and stop checking to avoid irrelevant diagnostics.
6682 if (Type != S.GetFormatStringType(PVFormatMatches)) {
6683 S.Diag(Args[format_idx]->getBeginLoc(),
6684 diag::warn_format_string_type_incompatible)
6685 << PVFormatMatches->getType()->getName()
6687 if (!InFunctionCall) {
6688 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
6689 diag::note_format_string_defined);
6690 }
6691 return SLCT_UncheckedLiteral;
6692 }
6693 return checkFormatStringExpr(
6694 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
6695 Args, APK, format_idx, firstDataArg, Type, CallType,
6696 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
6697 Offset, IgnoreStringsWithoutSpecifiers);
6698 }
6699 }
6700
6701 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
6702 Sema::FormatStringInfo CallerFSI;
6703 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
6704 PVFormat->getFirstArg(), &CallerFSI))
6705 continue;
6706 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
6707 // We also check if the formats are compatible.
6708 // We can't pass a 'scanf' string to a 'printf' function.
6709 if (Type != S.GetFormatStringType(PVFormat)) {
6710 S.Diag(Args[format_idx]->getBeginLoc(),
6711 diag::warn_format_string_type_incompatible)
6712 << PVFormat->getType()->getName()
6714 if (!InFunctionCall) {
6715 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
6716 }
6717 return SLCT_UncheckedLiteral;
6718 }
6719 // Lastly, check that argument passing kinds transition in a
6720 // way that makes sense:
6721 // from a caller with FAPK_VAList, allow FAPK_VAList
6722 // from a caller with FAPK_Fixed, allow FAPK_Fixed
6723 // from a caller with FAPK_Fixed, allow FAPK_Variadic
6724 // from a caller with FAPK_Variadic, allow FAPK_VAList
6725 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
6730 return SLCT_UncheckedLiteral;
6731 }
6732 }
6733 }
6734 }
6735 }
6736 }
6737
6738 return SLCT_NotALiteral;
6739 }
6740
6741 case Stmt::CallExprClass:
6742 case Stmt::CXXMemberCallExprClass: {
6743 const CallExpr *CE = cast<CallExpr>(E);
6744 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6745 bool IsFirst = true;
6746 StringLiteralCheckType CommonResult;
6747 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6748 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6749 StringLiteralCheckType Result = checkFormatStringExpr(
6750 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
6751 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
6752 Offset, IgnoreStringsWithoutSpecifiers);
6753 if (IsFirst) {
6754 CommonResult = Result;
6755 IsFirst = false;
6756 }
6757 }
6758 if (!IsFirst)
6759 return CommonResult;
6760
6761 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6762 unsigned BuiltinID = FD->getBuiltinID();
6763 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6764 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6765 const Expr *Arg = CE->getArg(0);
6766 return checkFormatStringExpr(
6767 S, ReferenceFormatString, Arg, Args, APK, format_idx,
6768 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6769 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6770 }
6771 }
6772 }
6773 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
6774 return checkFormatStringExpr(
6775 S, ReferenceFormatString, SLE, Args, APK, format_idx, firstDataArg,
6776 Type, CallType, /*InFunctionCall*/ false, CheckedVarArgs,
6777 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6778 return SLCT_NotALiteral;
6779 }
6780 case Stmt::ObjCMessageExprClass: {
6781 const auto *ME = cast<ObjCMessageExpr>(E);
6782 if (const auto *MD = ME->getMethodDecl()) {
6783 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6784 // As a special case heuristic, if we're using the method -[NSBundle
6785 // localizedStringForKey:value:table:], ignore any key strings that lack
6786 // format specifiers. The idea is that if the key doesn't have any
6787 // format specifiers then its probably just a key to map to the
6788 // localized strings. If it does have format specifiers though, then its
6789 // likely that the text of the key is the format string in the
6790 // programmer's language, and should be checked.
6791 const ObjCInterfaceDecl *IFace;
6792 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6793 IFace->getIdentifier()->isStr("NSBundle") &&
6794 MD->getSelector().isKeywordSelector(
6795 {"localizedStringForKey", "value", "table"})) {
6796 IgnoreStringsWithoutSpecifiers = true;
6797 }
6798
6799 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6800 return checkFormatStringExpr(
6801 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
6802 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
6803 Offset, IgnoreStringsWithoutSpecifiers);
6804 }
6805 }
6806
6807 return SLCT_NotALiteral;
6808 }
6809 case Stmt::ObjCStringLiteralClass:
6810 case Stmt::StringLiteralClass: {
6811 const StringLiteral *StrE = nullptr;
6812
6813 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6814 StrE = ObjCFExpr->getString();
6815 else
6816 StrE = cast<StringLiteral>(E);
6817
6818 if (StrE) {
6819 if (Offset.isNegative() || Offset > StrE->getLength()) {
6820 // TODO: It would be better to have an explicit warning for out of
6821 // bounds literals.
6822 return SLCT_NotALiteral;
6823 }
6824 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6825 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
6826 format_idx, firstDataArg, Type, InFunctionCall,
6827 CallType, CheckedVarArgs, UncoveredArg,
6828 IgnoreStringsWithoutSpecifiers);
6829 return SLCT_CheckedLiteral;
6830 }
6831
6832 return SLCT_NotALiteral;
6833 }
6834 case Stmt::BinaryOperatorClass: {
6835 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6836
6837 // A string literal + an int offset is still a string literal.
6838 if (BinOp->isAdditiveOp()) {
6839 Expr::EvalResult LResult, RResult;
6840
6841 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6842 LResult, S.Context, Expr::SE_NoSideEffects,
6844 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6845 RResult, S.Context, Expr::SE_NoSideEffects,
6847
6848 if (LIsInt != RIsInt) {
6849 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6850
6851 if (LIsInt) {
6852 if (BinOpKind == BO_Add) {
6853 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6854 E = BinOp->getRHS();
6855 goto tryAgain;
6856 }
6857 } else {
6858 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6859 E = BinOp->getLHS();
6860 goto tryAgain;
6861 }
6862 }
6863 }
6864
6865 return SLCT_NotALiteral;
6866 }
6867 case Stmt::UnaryOperatorClass: {
6868 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6869 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6870 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6871 Expr::EvalResult IndexResult;
6872 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6875 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6876 /*RHS is int*/ true);
6877 E = ASE->getBase();
6878 goto tryAgain;
6879 }
6880 }
6881
6882 return SLCT_NotALiteral;
6883 }
6884
6885 default:
6886 return SLCT_NotALiteral;
6887 }
6888}
6889
6890// If this expression can be evaluated at compile-time,
6891// check if the result is a StringLiteral and return it
6892// otherwise return nullptr
6894 const Expr *E) {
6895 Expr::EvalResult Result;
6896 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
6897 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
6898 if (isa_and_nonnull<StringLiteral>(LVE))
6899 return LVE;
6900 }
6901 return nullptr;
6902}
6903
6905 switch (FST) {
6907 return "scanf";
6909 return "printf";
6911 return "NSString";
6913 return "strftime";
6915 return "strfmon";
6917 return "kprintf";
6919 return "freebsd_kprintf";
6921 return "os_log";
6922 default:
6923 return "<unknown>";
6924 }
6925}
6926
6928 return llvm::StringSwitch<FormatStringType>(Flavor)
6929 .Cases("gnu_scanf", "scanf", FormatStringType::Scanf)
6930 .Cases("gnu_printf", "printf", "printf0", "syslog",
6932 .Cases("NSString", "CFString", FormatStringType::NSString)
6933 .Cases("gnu_strftime", "strftime", FormatStringType::Strftime)
6934 .Cases("gnu_strfmon", "strfmon", FormatStringType::Strfmon)
6935 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err",
6937 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
6938 .Case("os_trace", FormatStringType::OSLog)
6939 .Case("os_log", FormatStringType::OSLog)
6940 .Default(FormatStringType::Unknown);
6941}
6942
6944 return GetFormatStringType(Format->getType()->getName());
6945}
6946
6947FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
6948 return GetFormatStringType(Format->getType()->getName());
6949}
6950
6951bool Sema::CheckFormatArguments(const FormatAttr *Format,
6952 ArrayRef<const Expr *> Args, bool IsCXXMember,
6953 VariadicCallType CallType, SourceLocation Loc,
6954 SourceRange Range,
6955 llvm::SmallBitVector &CheckedVarArgs) {
6956 FormatStringInfo FSI;
6957 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
6958 IsCXXMember,
6959 CallType != VariadicCallType::DoesNotApply, &FSI))
6960 return CheckFormatArguments(
6961 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
6962 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
6963 return false;
6964}
6965
6966bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
6967 ArrayRef<const Expr *> Args, bool IsCXXMember,
6968 VariadicCallType CallType, SourceLocation Loc,
6969 SourceRange Range,
6970 llvm::SmallBitVector &CheckedVarArgs) {
6971 FormatStringInfo FSI;
6972 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
6973 &FSI)) {
6974 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
6975 return CheckFormatArguments(Args, FSI.ArgPassingKind,
6976 Format->getFormatString(), FSI.FormatIdx,
6977 FSI.FirstDataArg, GetFormatStringType(Format),
6978 CallType, Loc, Range, CheckedVarArgs);
6979 }
6980 return false;
6981}
6982
6983bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6985 const StringLiteral *ReferenceFormatString,
6986 unsigned format_idx, unsigned firstDataArg,
6988 VariadicCallType CallType, SourceLocation Loc,
6989 SourceRange Range,
6990 llvm::SmallBitVector &CheckedVarArgs) {
6991 // CHECK: printf/scanf-like function is called with no format string.
6992 if (format_idx >= Args.size()) {
6993 Diag(Loc, diag::warn_missing_format_string) << Range;
6994 return false;
6995 }
6996
6997 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6998
6999 // CHECK: format string is not a string literal.
7000 //
7001 // Dynamically generated format strings are difficult to
7002 // automatically vet at compile time. Requiring that format strings
7003 // are string literals: (1) permits the checking of format strings by
7004 // the compiler and thereby (2) can practically remove the source of
7005 // many format string exploits.
7006
7007 // Format string can be either ObjC string (e.g. @"%d") or
7008 // C string (e.g. "%d")
7009 // ObjC string uses the same format specifiers as C string, so we can use
7010 // the same format string checking logic for both ObjC and C strings.
7011 UncoveredArgHandler UncoveredArg;
7012 StringLiteralCheckType CT = checkFormatStringExpr(
7013 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
7014 firstDataArg, Type, CallType,
7015 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
7016 /*no string offset*/ llvm::APSInt(64, false) = 0);
7017
7018 // Generate a diagnostic where an uncovered argument is detected.
7019 if (UncoveredArg.hasUncoveredArg()) {
7020 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7021 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7022 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7023 }
7024
7025 if (CT != SLCT_NotALiteral)
7026 // Literal format string found, check done!
7027 return CT == SLCT_CheckedLiteral;
7028
7029 // Strftime is particular as it always uses a single 'time' argument,
7030 // so it is safe to pass a non-literal string.
7032 return false;
7033
7034 // Do not emit diag when the string param is a macro expansion and the
7035 // format is either NSString or CFString. This is a hack to prevent
7036 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7037 // which are usually used in place of NS and CF string literals.
7038 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7040 SourceMgr.isInSystemMacro(FormatLoc))
7041 return false;
7042
7043 // If there are no arguments specified, warn with -Wformat-security, otherwise
7044 // warn only with -Wformat-nonliteral.
7045 if (Args.size() == firstDataArg) {
7046 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7047 << OrigFormatExpr->getSourceRange();
7048 switch (Type) {
7049 default:
7050 break;
7054 Diag(FormatLoc, diag::note_format_security_fixit)
7055 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7056 break;
7058 Diag(FormatLoc, diag::note_format_security_fixit)
7059 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7060 break;
7061 }
7062 } else {
7063 Diag(FormatLoc, diag::warn_format_nonliteral)
7064 << OrigFormatExpr->getSourceRange();
7065 }
7066 return false;
7067}
7068
7069namespace {
7070
7071class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7072protected:
7073 Sema &S;
7074 const FormatStringLiteral *FExpr;
7075 const Expr *OrigFormatExpr;
7076 const FormatStringType FSType;
7077 const unsigned FirstDataArg;
7078 const unsigned NumDataArgs;
7079 const char *Beg; // Start of format string.
7080 const Sema::FormatArgumentPassingKind ArgPassingKind;
7081 ArrayRef<const Expr *> Args;
7082 unsigned FormatIdx;
7083 llvm::SmallBitVector CoveredArgs;
7084 bool usesPositionalArgs = false;
7085 bool atFirstArg = true;
7086 bool inFunctionCall;
7087 VariadicCallType CallType;
7088 llvm::SmallBitVector &CheckedVarArgs;
7089 UncoveredArgHandler &UncoveredArg;
7090
7091public:
7092 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7093 const Expr *origFormatExpr, const FormatStringType type,
7094 unsigned firstDataArg, unsigned numDataArgs,
7095 const char *beg, Sema::FormatArgumentPassingKind APK,
7096 ArrayRef<const Expr *> Args, unsigned formatIdx,
7097 bool inFunctionCall, VariadicCallType callType,
7098 llvm::SmallBitVector &CheckedVarArgs,
7099 UncoveredArgHandler &UncoveredArg)
7100 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7101 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7102 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
7103 inFunctionCall(inFunctionCall), CallType(callType),
7104 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7105 CoveredArgs.resize(numDataArgs);
7106 CoveredArgs.reset();
7107 }
7108
7109 bool HasFormatArguments() const {
7110 return ArgPassingKind == Sema::FAPK_Fixed ||
7111 ArgPassingKind == Sema::FAPK_Variadic;
7112 }
7113
7114 void DoneProcessing();
7115
7116 void HandleIncompleteSpecifier(const char *startSpecifier,
7117 unsigned specifierLen) override;
7118
7119 void HandleInvalidLengthModifier(
7120 const analyze_format_string::FormatSpecifier &FS,
7121 const analyze_format_string::ConversionSpecifier &CS,
7122 const char *startSpecifier, unsigned specifierLen,
7123 unsigned DiagID);
7124
7125 void HandleNonStandardLengthModifier(
7126 const analyze_format_string::FormatSpecifier &FS,
7127 const char *startSpecifier, unsigned specifierLen);
7128
7129 void HandleNonStandardConversionSpecifier(
7130 const analyze_format_string::ConversionSpecifier &CS,
7131 const char *startSpecifier, unsigned specifierLen);
7132
7133 void HandlePosition(const char *startPos, unsigned posLen) override;
7134
7135 void HandleInvalidPosition(const char *startSpecifier,
7136 unsigned specifierLen,
7138
7139 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7140
7141 void HandleNullChar(const char *nullCharacter) override;
7142
7143 template <typename Range>
7144 static void
7145 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7146 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7147 bool IsStringLocation, Range StringRange,
7148 ArrayRef<FixItHint> Fixit = {});
7149
7150protected:
7151 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7152 const char *startSpec,
7153 unsigned specifierLen,
7154 const char *csStart, unsigned csLen);
7155
7156 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7157 const char *startSpec,
7158 unsigned specifierLen);
7159
7160 SourceRange getFormatStringRange();
7161 CharSourceRange getSpecifierRange(const char *startSpecifier,
7162 unsigned specifierLen);
7163 SourceLocation getLocationOfByte(const char *x);
7164
7165 const Expr *getDataArg(unsigned i) const;
7166
7167 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7168 const analyze_format_string::ConversionSpecifier &CS,
7169 const char *startSpecifier, unsigned specifierLen,
7170 unsigned argIndex);
7171
7172 template <typename Range>
7173 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7174 bool IsStringLocation, Range StringRange,
7175 ArrayRef<FixItHint> Fixit = {});
7176};
7177
7178} // namespace
7179
7180SourceRange CheckFormatHandler::getFormatStringRange() {
7181 return OrigFormatExpr->getSourceRange();
7182}
7183
7184CharSourceRange CheckFormatHandler::
7185getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7186 SourceLocation Start = getLocationOfByte(startSpecifier);
7187 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
7188
7189 // Advance the end SourceLocation by one due to half-open ranges.
7190 End = End.getLocWithOffset(1);
7191
7192 return CharSourceRange::getCharRange(Start, End);
7193}
7194
7195SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7196 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7198}
7199
7200void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7201 unsigned specifierLen){
7202 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7203 getLocationOfByte(startSpecifier),
7204 /*IsStringLocation*/true,
7205 getSpecifierRange(startSpecifier, specifierLen));
7206}
7207
7208void CheckFormatHandler::HandleInvalidLengthModifier(
7211 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7212 using namespace analyze_format_string;
7213
7214 const LengthModifier &LM = FS.getLengthModifier();
7215 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7216
7217 // See if we know how to fix this length modifier.
7218 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7219 if (FixedLM) {
7220 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7221 getLocationOfByte(LM.getStart()),
7222 /*IsStringLocation*/true,
7223 getSpecifierRange(startSpecifier, specifierLen));
7224
7225 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7226 << FixedLM->toString()
7227 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7228
7229 } else {
7230 FixItHint Hint;
7231 if (DiagID == diag::warn_format_nonsensical_length)
7232 Hint = FixItHint::CreateRemoval(LMRange);
7233
7234 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7235 getLocationOfByte(LM.getStart()),
7236 /*IsStringLocation*/true,
7237 getSpecifierRange(startSpecifier, specifierLen),
7238 Hint);
7239 }
7240}
7241
7242void CheckFormatHandler::HandleNonStandardLengthModifier(
7244 const char *startSpecifier, unsigned specifierLen) {
7245 using namespace analyze_format_string;
7246
7247 const LengthModifier &LM = FS.getLengthModifier();
7248 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7249
7250 // See if we know how to fix this length modifier.
7251 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7252 if (FixedLM) {
7253 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7254 << LM.toString() << 0,
7255 getLocationOfByte(LM.getStart()),
7256 /*IsStringLocation*/true,
7257 getSpecifierRange(startSpecifier, specifierLen));
7258
7259 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7260 << FixedLM->toString()
7261 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7262
7263 } else {
7264 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7265 << LM.toString() << 0,
7266 getLocationOfByte(LM.getStart()),
7267 /*IsStringLocation*/true,
7268 getSpecifierRange(startSpecifier, specifierLen));
7269 }
7270}
7271
7272void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7274 const char *startSpecifier, unsigned specifierLen) {
7275 using namespace analyze_format_string;
7276
7277 // See if we know how to fix this conversion specifier.
7278 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7279 if (FixedCS) {
7280 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7281 << CS.toString() << /*conversion specifier*/1,
7282 getLocationOfByte(CS.getStart()),
7283 /*IsStringLocation*/true,
7284 getSpecifierRange(startSpecifier, specifierLen));
7285
7286 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7287 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7288 << FixedCS->toString()
7289 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7290 } else {
7291 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7292 << CS.toString() << /*conversion specifier*/1,
7293 getLocationOfByte(CS.getStart()),
7294 /*IsStringLocation*/true,
7295 getSpecifierRange(startSpecifier, specifierLen));
7296 }
7297}
7298
7299void CheckFormatHandler::HandlePosition(const char *startPos,
7300 unsigned posLen) {
7301 if (!S.getDiagnostics().isIgnored(
7302 diag::warn_format_non_standard_positional_arg, SourceLocation()))
7303 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7304 getLocationOfByte(startPos),
7305 /*IsStringLocation*/ true,
7306 getSpecifierRange(startPos, posLen));
7307}
7308
7309void CheckFormatHandler::HandleInvalidPosition(
7310 const char *startSpecifier, unsigned specifierLen,
7312 if (!S.getDiagnostics().isIgnored(
7313 diag::warn_format_invalid_positional_specifier, SourceLocation()))
7314 EmitFormatDiagnostic(
7315 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
7316 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
7317 getSpecifierRange(startSpecifier, specifierLen));
7318}
7319
7320void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7321 unsigned posLen) {
7322 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
7323 SourceLocation()))
7324 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7325 getLocationOfByte(startPos),
7326 /*IsStringLocation*/ true,
7327 getSpecifierRange(startPos, posLen));
7328}
7329
7330void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7331 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7332 // The presence of a null character is likely an error.
7333 EmitFormatDiagnostic(
7334 S.PDiag(diag::warn_printf_format_string_contains_null_char),
7335 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7336 getFormatStringRange());
7337 }
7338}
7339
7340// Note that this may return NULL if there was an error parsing or building
7341// one of the argument expressions.
7342const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7343 return Args[FirstDataArg + i];
7344}
7345
7346void CheckFormatHandler::DoneProcessing() {
7347 // Does the number of data arguments exceed the number of
7348 // format conversions in the format string?
7349 if (HasFormatArguments()) {
7350 // Find any arguments that weren't covered.
7351 CoveredArgs.flip();
7352 signed notCoveredArg = CoveredArgs.find_first();
7353 if (notCoveredArg >= 0) {
7354 assert((unsigned)notCoveredArg < NumDataArgs);
7355 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7356 } else {
7357 UncoveredArg.setAllCovered();
7358 }
7359 }
7360}
7361
7362void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7363 const Expr *ArgExpr) {
7364 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
7365 "Invalid state");
7366
7367 if (!ArgExpr)
7368 return;
7369
7370 SourceLocation Loc = ArgExpr->getBeginLoc();
7371
7372 if (S.getSourceManager().isInSystemMacro(Loc))
7373 return;
7374
7375 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7376 for (auto E : DiagnosticExprs)
7377 PDiag << E->getSourceRange();
7378
7379 CheckFormatHandler::EmitFormatDiagnostic(
7380 S, IsFunctionCall, DiagnosticExprs[0],
7381 PDiag, Loc, /*IsStringLocation*/false,
7382 DiagnosticExprs[0]->getSourceRange());
7383}
7384
7385bool
7386CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7387 SourceLocation Loc,
7388 const char *startSpec,
7389 unsigned specifierLen,
7390 const char *csStart,
7391 unsigned csLen) {
7392 bool keepGoing = true;
7393 if (argIndex < NumDataArgs) {
7394 // Consider the argument coverered, even though the specifier doesn't
7395 // make sense.
7396 CoveredArgs.set(argIndex);
7397 }
7398 else {
7399 // If argIndex exceeds the number of data arguments we
7400 // don't issue a warning because that is just a cascade of warnings (and
7401 // they may have intended '%%' anyway). We don't want to continue processing
7402 // the format string after this point, however, as we will like just get
7403 // gibberish when trying to match arguments.
7404 keepGoing = false;
7405 }
7406
7407 StringRef Specifier(csStart, csLen);
7408
7409 // If the specifier in non-printable, it could be the first byte of a UTF-8
7410 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7411 // hex value.
7412 std::string CodePointStr;
7413 if (!llvm::sys::locale::isPrint(*csStart)) {
7414 llvm::UTF32 CodePoint;
7415 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7416 const llvm::UTF8 *E =
7417 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7418 llvm::ConversionResult Result =
7419 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7420
7421 if (Result != llvm::conversionOK) {
7422 unsigned char FirstChar = *csStart;
7423 CodePoint = (llvm::UTF32)FirstChar;
7424 }
7425
7426 llvm::raw_string_ostream OS(CodePointStr);
7427 if (CodePoint < 256)
7428 OS << "\\x" << llvm::format("%02x", CodePoint);
7429 else if (CodePoint <= 0xFFFF)
7430 OS << "\\u" << llvm::format("%04x", CodePoint);
7431 else
7432 OS << "\\U" << llvm::format("%08x", CodePoint);
7433 Specifier = CodePointStr;
7434 }
7435
7436 EmitFormatDiagnostic(
7437 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7438 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7439
7440 return keepGoing;
7441}
7442
7443void
7444CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7445 const char *startSpec,
7446 unsigned specifierLen) {
7447 EmitFormatDiagnostic(
7448 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7449 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7450}
7451
7452bool
7453CheckFormatHandler::CheckNumArgs(
7456 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7457
7458 if (HasFormatArguments() && argIndex >= NumDataArgs) {
7460 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7461 << (argIndex+1) << NumDataArgs)
7462 : S.PDiag(diag::warn_printf_insufficient_data_args);
7463 EmitFormatDiagnostic(
7464 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7465 getSpecifierRange(startSpecifier, specifierLen));
7466
7467 // Since more arguments than conversion tokens are given, by extension
7468 // all arguments are covered, so mark this as so.
7469 UncoveredArg.setAllCovered();
7470 return false;
7471 }
7472 return true;
7473}
7474
7475template<typename Range>
7476void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7477 SourceLocation Loc,
7478 bool IsStringLocation,
7479 Range StringRange,
7480 ArrayRef<FixItHint> FixIt) {
7481 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7482 Loc, IsStringLocation, StringRange, FixIt);
7483}
7484
7485/// If the format string is not within the function call, emit a note
7486/// so that the function call and string are in diagnostic messages.
7487///
7488/// \param InFunctionCall if true, the format string is within the function
7489/// call and only one diagnostic message will be produced. Otherwise, an
7490/// extra note will be emitted pointing to location of the format string.
7491///
7492/// \param ArgumentExpr the expression that is passed as the format string
7493/// argument in the function call. Used for getting locations when two
7494/// diagnostics are emitted.
7495///
7496/// \param PDiag the callee should already have provided any strings for the
7497/// diagnostic message. This function only adds locations and fixits
7498/// to diagnostics.
7499///
7500/// \param Loc primary location for diagnostic. If two diagnostics are
7501/// required, one will be at Loc and a new SourceLocation will be created for
7502/// the other one.
7503///
7504/// \param IsStringLocation if true, Loc points to the format string should be
7505/// used for the note. Otherwise, Loc points to the argument list and will
7506/// be used with PDiag.
7507///
7508/// \param StringRange some or all of the string to highlight. This is
7509/// templated so it can accept either a CharSourceRange or a SourceRange.
7510///
7511/// \param FixIt optional fix it hint for the format string.
7512template <typename Range>
7513void CheckFormatHandler::EmitFormatDiagnostic(
7514 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7515 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7516 Range StringRange, ArrayRef<FixItHint> FixIt) {
7517 if (InFunctionCall) {
7518 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7519 D << StringRange;
7520 D << FixIt;
7521 } else {
7522 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7523 << ArgumentExpr->getSourceRange();
7524
7526 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7527 diag::note_format_string_defined);
7528
7529 Note << StringRange;
7530 Note << FixIt;
7531 }
7532}
7533
7534//===--- CHECK: Printf format string checking -----------------------------===//
7535
7536namespace {
7537
7538class CheckPrintfHandler : public CheckFormatHandler {
7539public:
7540 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7541 const Expr *origFormatExpr, const FormatStringType type,
7542 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
7543 const char *beg, Sema::FormatArgumentPassingKind APK,
7544 ArrayRef<const Expr *> Args, unsigned formatIdx,
7545 bool inFunctionCall, VariadicCallType CallType,
7546 llvm::SmallBitVector &CheckedVarArgs,
7547 UncoveredArgHandler &UncoveredArg)
7548 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7549 numDataArgs, beg, APK, Args, formatIdx,
7550 inFunctionCall, CallType, CheckedVarArgs,
7551 UncoveredArg) {}
7552
7553 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
7554
7555 /// Returns true if '%@' specifiers are allowed in the format string.
7556 bool allowsObjCArg() const {
7557 return FSType == FormatStringType::NSString ||
7558 FSType == FormatStringType::OSLog ||
7559 FSType == FormatStringType::OSTrace;
7560 }
7561
7562 bool HandleInvalidPrintfConversionSpecifier(
7563 const analyze_printf::PrintfSpecifier &FS,
7564 const char *startSpecifier,
7565 unsigned specifierLen) override;
7566
7567 void handleInvalidMaskType(StringRef MaskType) override;
7568
7569 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7570 const char *startSpecifier, unsigned specifierLen,
7571 const TargetInfo &Target) override;
7572 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7573 const char *StartSpecifier,
7574 unsigned SpecifierLen,
7575 const Expr *E);
7576
7577 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7578 const char *startSpecifier, unsigned specifierLen);
7579 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7580 const analyze_printf::OptionalAmount &Amt,
7581 unsigned type,
7582 const char *startSpecifier, unsigned specifierLen);
7583 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7584 const analyze_printf::OptionalFlag &flag,
7585 const char *startSpecifier, unsigned specifierLen);
7586 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7587 const analyze_printf::OptionalFlag &ignoredFlag,
7588 const analyze_printf::OptionalFlag &flag,
7589 const char *startSpecifier, unsigned specifierLen);
7590 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7591 const Expr *E);
7592
7593 void HandleEmptyObjCModifierFlag(const char *startFlag,
7594 unsigned flagLen) override;
7595
7596 void HandleInvalidObjCModifierFlag(const char *startFlag,
7597 unsigned flagLen) override;
7598
7599 void
7600 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7601 const char *flagsEnd,
7602 const char *conversionPosition) override;
7603};
7604
7605/// Keeps around the information needed to verify that two specifiers are
7606/// compatible.
7607class EquatableFormatArgument {
7608public:
7609 enum SpecifierSensitivity : unsigned {
7610 SS_None,
7611 SS_Private,
7612 SS_Public,
7613 SS_Sensitive
7614 };
7615
7616 enum FormatArgumentRole : unsigned {
7617 FAR_Data,
7618 FAR_FieldWidth,
7619 FAR_Precision,
7620 FAR_Auxiliary, // FreeBSD kernel %b and %D
7621 };
7622
7623private:
7624 analyze_format_string::ArgType ArgType;
7626 StringRef SpecifierLetter;
7627 CharSourceRange Range;
7628 SourceLocation ElementLoc;
7629 FormatArgumentRole Role : 2;
7630 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
7631 unsigned Position : 14;
7632 unsigned ModifierFor : 14; // not set for FAR_Data
7633
7634 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
7635 bool InFunctionCall) const;
7636
7637public:
7638 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
7640 StringRef SpecifierLetter,
7641 analyze_format_string::ArgType ArgType,
7642 FormatArgumentRole Role,
7643 SpecifierSensitivity Sensitivity, unsigned Position,
7644 unsigned ModifierFor)
7645 : ArgType(ArgType), LengthMod(LengthMod),
7646 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
7647 Role(Role), Sensitivity(Sensitivity), Position(Position),
7648 ModifierFor(ModifierFor) {}
7649
7650 unsigned getPosition() const { return Position; }
7651 SourceLocation getSourceLocation() const { return ElementLoc; }
7652 CharSourceRange getSourceRange() const { return Range; }
7653 analyze_format_string::LengthModifier getLengthModifier() const {
7654 return analyze_format_string::LengthModifier(nullptr, LengthMod);
7655 }
7656 void setModifierFor(unsigned V) { ModifierFor = V; }
7657
7658 std::string buildFormatSpecifier() const {
7659 std::string result;
7660 llvm::raw_string_ostream(result)
7661 << getLengthModifier().toString() << SpecifierLetter;
7662 return result;
7663 }
7664
7665 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
7666 const Expr *FmtExpr, bool InFunctionCall) const;
7667};
7668
7669/// Turns format strings into lists of EquatableSpecifier objects.
7670class DecomposePrintfHandler : public CheckPrintfHandler {
7671 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
7672 bool HadError;
7673
7674 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7675 const Expr *origFormatExpr,
7676 const FormatStringType type, unsigned firstDataArg,
7677 unsigned numDataArgs, bool isObjC, const char *beg,
7679 ArrayRef<const Expr *> Args, unsigned formatIdx,
7680 bool inFunctionCall, VariadicCallType CallType,
7681 llvm::SmallBitVector &CheckedVarArgs,
7682 UncoveredArgHandler &UncoveredArg,
7683 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
7684 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7685 numDataArgs, isObjC, beg, APK, Args, formatIdx,
7686 inFunctionCall, CallType, CheckedVarArgs,
7687 UncoveredArg),
7688 Specs(Specs), HadError(false) {}
7689
7690public:
7691 static bool
7692 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
7693 FormatStringType type, bool IsObjC, bool InFunctionCall,
7694 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
7695
7696 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7697 const char *startSpecifier,
7698 unsigned specifierLen,
7699 const TargetInfo &Target) override;
7700};
7701
7702} // namespace
7703
7704bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7705 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
7706 unsigned specifierLen) {
7709
7710 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7711 getLocationOfByte(CS.getStart()),
7712 startSpecifier, specifierLen,
7713 CS.getStart(), CS.getLength());
7714}
7715
7716void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7717 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7718}
7719
7720// Error out if struct or complex type argments are passed to os_log.
7722 QualType T) {
7723 if (FSType != FormatStringType::OSLog)
7724 return false;
7725 return T->isRecordType() || T->isComplexType();
7726}
7727
7728bool CheckPrintfHandler::HandleAmount(
7729 const analyze_format_string::OptionalAmount &Amt, unsigned k,
7730 const char *startSpecifier, unsigned specifierLen) {
7731 if (Amt.hasDataArgument()) {
7732 if (HasFormatArguments()) {
7733 unsigned argIndex = Amt.getArgIndex();
7734 if (argIndex >= NumDataArgs) {
7735 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7736 << k,
7737 getLocationOfByte(Amt.getStart()),
7738 /*IsStringLocation*/ true,
7739 getSpecifierRange(startSpecifier, specifierLen));
7740 // Don't do any more checking. We will just emit
7741 // spurious errors.
7742 return false;
7743 }
7744
7745 // Type check the data argument. It should be an 'int'.
7746 // Although not in conformance with C99, we also allow the argument to be
7747 // an 'unsigned int' as that is a reasonably safe case. GCC also
7748 // doesn't emit a warning for that case.
7749 CoveredArgs.set(argIndex);
7750 const Expr *Arg = getDataArg(argIndex);
7751 if (!Arg)
7752 return false;
7753
7754 QualType T = Arg->getType();
7755
7756 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7757 assert(AT.isValid());
7758
7759 if (!AT.matchesType(S.Context, T)) {
7760 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
7761 ? diag::err_printf_asterisk_wrong_type
7762 : diag::warn_printf_asterisk_wrong_type;
7763 EmitFormatDiagnostic(S.PDiag(DiagID)
7765 << T << Arg->getSourceRange(),
7766 getLocationOfByte(Amt.getStart()),
7767 /*IsStringLocation*/ true,
7768 getSpecifierRange(startSpecifier, specifierLen));
7769 // Don't do any more checking. We will just emit
7770 // spurious errors.
7771 return false;
7772 }
7773 }
7774 }
7775 return true;
7776}
7777
7778void CheckPrintfHandler::HandleInvalidAmount(
7781 unsigned type,
7782 const char *startSpecifier,
7783 unsigned specifierLen) {
7786
7787 FixItHint fixit =
7789 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7790 Amt.getConstantLength()))
7791 : FixItHint();
7792
7793 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7794 << type << CS.toString(),
7795 getLocationOfByte(Amt.getStart()),
7796 /*IsStringLocation*/true,
7797 getSpecifierRange(startSpecifier, specifierLen),
7798 fixit);
7799}
7800
7801void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7802 const analyze_printf::OptionalFlag &flag,
7803 const char *startSpecifier,
7804 unsigned specifierLen) {
7805 // Warn about pointless flag with a fixit removal.
7808 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7809 << flag.toString() << CS.toString(),
7810 getLocationOfByte(flag.getPosition()),
7811 /*IsStringLocation*/true,
7812 getSpecifierRange(startSpecifier, specifierLen),
7814 getSpecifierRange(flag.getPosition(), 1)));
7815}
7816
7817void CheckPrintfHandler::HandleIgnoredFlag(
7819 const analyze_printf::OptionalFlag &ignoredFlag,
7820 const analyze_printf::OptionalFlag &flag,
7821 const char *startSpecifier,
7822 unsigned specifierLen) {
7823 // Warn about ignored flag with a fixit removal.
7824 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7825 << ignoredFlag.toString() << flag.toString(),
7826 getLocationOfByte(ignoredFlag.getPosition()),
7827 /*IsStringLocation*/true,
7828 getSpecifierRange(startSpecifier, specifierLen),
7830 getSpecifierRange(ignoredFlag.getPosition(), 1)));
7831}
7832
7833void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7834 unsigned flagLen) {
7835 // Warn about an empty flag.
7836 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7837 getLocationOfByte(startFlag),
7838 /*IsStringLocation*/true,
7839 getSpecifierRange(startFlag, flagLen));
7840}
7841
7842void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7843 unsigned flagLen) {
7844 // Warn about an invalid flag.
7845 auto Range = getSpecifierRange(startFlag, flagLen);
7846 StringRef flag(startFlag, flagLen);
7847 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7848 getLocationOfByte(startFlag),
7849 /*IsStringLocation*/true,
7850 Range, FixItHint::CreateRemoval(Range));
7851}
7852
7853void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7854 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7855 // Warn about using '[...]' without a '@' conversion.
7856 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7857 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7858 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7859 getLocationOfByte(conversionPosition),
7860 /*IsStringLocation*/ true, Range,
7862}
7863
7864void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
7865 const Expr *FmtExpr,
7866 bool InFunctionCall) const {
7867 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
7868 ElementLoc, true, Range);
7869}
7870
7871bool EquatableFormatArgument::VerifyCompatible(
7872 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
7873 bool InFunctionCall) const {
7875 if (Role != Other.Role) {
7876 // diagnose and stop
7877 EmitDiagnostic(
7878 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
7879 FmtExpr, InFunctionCall);
7880 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
7881 return false;
7882 }
7883
7884 if (Role != FAR_Data) {
7885 if (ModifierFor != Other.ModifierFor) {
7886 // diagnose and stop
7887 EmitDiagnostic(S,
7888 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
7889 << (ModifierFor + 1) << (Other.ModifierFor + 1),
7890 FmtExpr, InFunctionCall);
7891 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
7892 return false;
7893 }
7894 return true;
7895 }
7896
7897 bool HadError = false;
7898 if (Sensitivity != Other.Sensitivity) {
7899 // diagnose and continue
7900 EmitDiagnostic(S,
7901 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
7902 << Sensitivity << Other.Sensitivity,
7903 FmtExpr, InFunctionCall);
7904 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7905 << 0 << Other.Range;
7906 }
7907
7908 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
7909 case MK::Match:
7910 break;
7911
7912 case MK::MatchPromotion:
7913 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
7914 // MatchPromotion is treated as a failure by format_matches.
7915 case MK::NoMatch:
7916 case MK::NoMatchTypeConfusion:
7917 case MK::NoMatchPromotionTypeConfusion:
7918 EmitDiagnostic(S,
7919 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
7920 << buildFormatSpecifier()
7921 << Other.buildFormatSpecifier(),
7922 FmtExpr, InFunctionCall);
7923 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7924 << 0 << Other.Range;
7925 break;
7926
7927 case MK::NoMatchPedantic:
7928 EmitDiagnostic(S,
7929 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
7930 << buildFormatSpecifier()
7931 << Other.buildFormatSpecifier(),
7932 FmtExpr, InFunctionCall);
7933 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7934 << 0 << Other.Range;
7935 break;
7936
7937 case MK::NoMatchSignedness:
7938 EmitDiagnostic(S,
7939 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
7940 << buildFormatSpecifier()
7941 << Other.buildFormatSpecifier(),
7942 FmtExpr, InFunctionCall);
7943 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7944 << 0 << Other.Range;
7945 break;
7946 }
7947 return !HadError;
7948}
7949
7950bool DecomposePrintfHandler::GetSpecifiers(
7951 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
7952 FormatStringType Type, bool IsObjC, bool InFunctionCall,
7954 StringRef Data = FSL->getString();
7955 const char *Str = Data.data();
7956 llvm::SmallBitVector BV;
7957 UncoveredArgHandler UA;
7958 const Expr *PrintfArgs[] = {FSL->getFormatString()};
7959 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
7960 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
7961 InFunctionCall, VariadicCallType::DoesNotApply, BV,
7962 UA, Args);
7963
7965 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
7967 H.DoneProcessing();
7968 if (H.HadError)
7969 return false;
7970
7971 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
7972 const EquatableFormatArgument &B) {
7973 return A.getPosition() < B.getPosition();
7974 });
7975 return true;
7976}
7977
7978bool DecomposePrintfHandler::HandlePrintfSpecifier(
7979 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
7980 unsigned specifierLen, const TargetInfo &Target) {
7981 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
7982 specifierLen, Target)) {
7983 HadError = true;
7984 return false;
7985 }
7986
7987 // Do not add any specifiers to the list for %%. This is possibly incorrect
7988 // if using a precision/width with a data argument, but that combination is
7989 // meaningless and we wouldn't know which format to attach the
7990 // precision/width to.
7991 const auto &CS = FS.getConversionSpecifier();
7993 return true;
7994
7995 // have to patch these to have the right ModifierFor if they are used
7996 const unsigned Unset = ~0;
7997 unsigned FieldWidthIndex = Unset;
7998 unsigned PrecisionIndex = Unset;
7999
8000 // field width?
8001 const auto &FieldWidth = FS.getFieldWidth();
8002 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8003 FieldWidthIndex = Specs.size();
8004 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8005 getLocationOfByte(FieldWidth.getStart()),
8007 FieldWidth.getArgType(S.Context),
8008 EquatableFormatArgument::FAR_FieldWidth,
8009 EquatableFormatArgument::SS_None,
8010 FieldWidth.usesPositionalArg()
8011 ? FieldWidth.getPositionalArgIndex() - 1
8012 : FieldWidthIndex,
8013 0);
8014 }
8015 // precision?
8016 const auto &Precision = FS.getPrecision();
8017 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
8018 PrecisionIndex = Specs.size();
8019 Specs.emplace_back(
8020 getSpecifierRange(startSpecifier, specifierLen),
8021 getLocationOfByte(Precision.getStart()),
8023 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
8024 EquatableFormatArgument::SS_None,
8025 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
8026 : PrecisionIndex,
8027 0);
8028 }
8029
8030 // this specifier
8031 unsigned SpecIndex =
8032 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
8033 if (FieldWidthIndex != Unset)
8034 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
8035 if (PrecisionIndex != Unset)
8036 Specs[PrecisionIndex].setModifierFor(SpecIndex);
8037
8038 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
8039 if (FS.isPrivate())
8040 Sensitivity = EquatableFormatArgument::SS_Private;
8041 else if (FS.isPublic())
8042 Sensitivity = EquatableFormatArgument::SS_Public;
8043 else if (FS.isSensitive())
8044 Sensitivity = EquatableFormatArgument::SS_Sensitive;
8045 else
8046 Sensitivity = EquatableFormatArgument::SS_None;
8047
8048 Specs.emplace_back(
8049 getSpecifierRange(startSpecifier, specifierLen),
8050 getLocationOfByte(CS.getStart()), FS.getLengthModifier().getKind(),
8051 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
8052 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
8053
8054 // auxiliary argument?
8057 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8058 getLocationOfByte(CS.getStart()),
8060 CS.getCharacters(),
8062 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
8063 SpecIndex + 1, SpecIndex);
8064 }
8065 return true;
8066}
8067
8068// Determines if the specified is a C++ class or struct containing
8069// a member with the specified name and kind (e.g. a CXXMethodDecl named
8070// "c_str()").
8071template<typename MemberKind>
8073CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8074 auto *RD = Ty->getAsCXXRecordDecl();
8076
8077 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
8078 return Results;
8079
8080 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8083
8084 // We just need to include all members of the right kind turned up by the
8085 // filter, at this point.
8086 if (S.LookupQualifiedName(R, RD))
8087 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8088 NamedDecl *decl = (*I)->getUnderlyingDecl();
8089 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8090 Results.insert(FK);
8091 }
8092 return Results;
8093}
8094
8095/// Check if we could call '.c_str()' on an object.
8096///
8097/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8098/// allow the call, or if it would be ambiguous).
8100 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8101
8102 MethodSet Results =
8103 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8104 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8105 MI != ME; ++MI)
8106 if ((*MI)->getMinRequiredArguments() == 0)
8107 return true;
8108 return false;
8109}
8110
8111// Check if a (w)string was passed when a (w)char* was needed, and offer a
8112// better diagnostic if so. AT is assumed to be valid.
8113// Returns true when a c_str() conversion method is found.
8114bool CheckPrintfHandler::checkForCStrMembers(
8115 const analyze_printf::ArgType &AT, const Expr *E) {
8116 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8117
8118 MethodSet Results =
8120
8121 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8122 MI != ME; ++MI) {
8123 const CXXMethodDecl *Method = *MI;
8124 if (Method->getMinRequiredArguments() == 0 &&
8125 AT.matchesType(S.Context, Method->getReturnType())) {
8126 // FIXME: Suggest parens if the expression needs them.
8128 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8129 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8130 return true;
8131 }
8132 }
8133
8134 return false;
8135}
8136
8137bool CheckPrintfHandler::HandlePrintfSpecifier(
8138 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8139 unsigned specifierLen, const TargetInfo &Target) {
8140 using namespace analyze_format_string;
8141 using namespace analyze_printf;
8142
8143 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8144
8145 if (FS.consumesDataArgument()) {
8146 if (atFirstArg) {
8147 atFirstArg = false;
8148 usesPositionalArgs = FS.usesPositionalArg();
8149 }
8150 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8151 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8152 startSpecifier, specifierLen);
8153 return false;
8154 }
8155 }
8156
8157 // First check if the field width, precision, and conversion specifier
8158 // have matching data arguments.
8159 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8160 startSpecifier, specifierLen)) {
8161 return false;
8162 }
8163
8164 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8165 startSpecifier, specifierLen)) {
8166 return false;
8167 }
8168
8169 if (!CS.consumesDataArgument()) {
8170 // FIXME: Technically specifying a precision or field width here
8171 // makes no sense. Worth issuing a warning at some point.
8172 return true;
8173 }
8174
8175 // Consume the argument.
8176 unsigned argIndex = FS.getArgIndex();
8177 if (argIndex < NumDataArgs) {
8178 // The check to see if the argIndex is valid will come later.
8179 // We set the bit here because we may exit early from this
8180 // function if we encounter some other error.
8181 CoveredArgs.set(argIndex);
8182 }
8183
8184 // FreeBSD kernel extensions.
8185 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8186 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8187 // We need at least two arguments.
8188 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8189 return false;
8190
8191 if (HasFormatArguments()) {
8192 // Claim the second argument.
8193 CoveredArgs.set(argIndex + 1);
8194
8195 // Type check the first argument (int for %b, pointer for %D)
8196 const Expr *Ex = getDataArg(argIndex);
8197 const analyze_printf::ArgType &AT =
8198 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
8199 ? ArgType(S.Context.IntTy)
8200 : ArgType::CPointerTy;
8201 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8202 EmitFormatDiagnostic(
8203 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8204 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8205 << false << Ex->getSourceRange(),
8206 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8207 getSpecifierRange(startSpecifier, specifierLen));
8208
8209 // Type check the second argument (char * for both %b and %D)
8210 Ex = getDataArg(argIndex + 1);
8212 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8213 EmitFormatDiagnostic(
8214 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8215 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8216 << false << Ex->getSourceRange(),
8217 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8218 getSpecifierRange(startSpecifier, specifierLen));
8219 }
8220 return true;
8221 }
8222
8223 // Check for using an Objective-C specific conversion specifier
8224 // in a non-ObjC literal.
8225 if (!allowsObjCArg() && CS.isObjCArg()) {
8226 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8227 specifierLen);
8228 }
8229
8230 // %P can only be used with os_log.
8231 if (FSType != FormatStringType::OSLog &&
8232 CS.getKind() == ConversionSpecifier::PArg) {
8233 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8234 specifierLen);
8235 }
8236
8237 // %n is not allowed with os_log.
8238 if (FSType == FormatStringType::OSLog &&
8239 CS.getKind() == ConversionSpecifier::nArg) {
8240 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8241 getLocationOfByte(CS.getStart()),
8242 /*IsStringLocation*/ false,
8243 getSpecifierRange(startSpecifier, specifierLen));
8244
8245 return true;
8246 }
8247
8248 // Only scalars are allowed for os_trace.
8249 if (FSType == FormatStringType::OSTrace &&
8250 (CS.getKind() == ConversionSpecifier::PArg ||
8251 CS.getKind() == ConversionSpecifier::sArg ||
8252 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8253 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8254 specifierLen);
8255 }
8256
8257 // Check for use of public/private annotation outside of os_log().
8258 if (FSType != FormatStringType::OSLog) {
8259 if (FS.isPublic().isSet()) {
8260 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8261 << "public",
8262 getLocationOfByte(FS.isPublic().getPosition()),
8263 /*IsStringLocation*/ false,
8264 getSpecifierRange(startSpecifier, specifierLen));
8265 }
8266 if (FS.isPrivate().isSet()) {
8267 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8268 << "private",
8269 getLocationOfByte(FS.isPrivate().getPosition()),
8270 /*IsStringLocation*/ false,
8271 getSpecifierRange(startSpecifier, specifierLen));
8272 }
8273 }
8274
8275 const llvm::Triple &Triple = Target.getTriple();
8276 if (CS.getKind() == ConversionSpecifier::nArg &&
8277 (Triple.isAndroid() || Triple.isOSFuchsia())) {
8278 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
8279 getLocationOfByte(CS.getStart()),
8280 /*IsStringLocation*/ false,
8281 getSpecifierRange(startSpecifier, specifierLen));
8282 }
8283
8284 // Check for invalid use of field width
8285 if (!FS.hasValidFieldWidth()) {
8286 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8287 startSpecifier, specifierLen);
8288 }
8289
8290 // Check for invalid use of precision
8291 if (!FS.hasValidPrecision()) {
8292 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8293 startSpecifier, specifierLen);
8294 }
8295
8296 // Precision is mandatory for %P specifier.
8297 if (CS.getKind() == ConversionSpecifier::PArg &&
8299 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8300 getLocationOfByte(startSpecifier),
8301 /*IsStringLocation*/ false,
8302 getSpecifierRange(startSpecifier, specifierLen));
8303 }
8304
8305 // Check each flag does not conflict with any other component.
8307 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8308 if (!FS.hasValidLeadingZeros())
8309 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8310 if (!FS.hasValidPlusPrefix())
8311 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8312 if (!FS.hasValidSpacePrefix())
8313 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8314 if (!FS.hasValidAlternativeForm())
8315 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8316 if (!FS.hasValidLeftJustified())
8317 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8318
8319 // Check that flags are not ignored by another flag
8320 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8321 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8322 startSpecifier, specifierLen);
8323 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8324 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8325 startSpecifier, specifierLen);
8326
8327 // Check the length modifier is valid with the given conversion specifier.
8329 S.getLangOpts()))
8330 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8331 diag::warn_format_nonsensical_length);
8332 else if (!FS.hasStandardLengthModifier())
8333 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8335 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8336 diag::warn_format_non_standard_conversion_spec);
8337
8339 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8340
8341 // The remaining checks depend on the data arguments.
8342 if (!HasFormatArguments())
8343 return true;
8344
8345 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8346 return false;
8347
8348 const Expr *Arg = getDataArg(argIndex);
8349 if (!Arg)
8350 return true;
8351
8352 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8353}
8354
8355static bool requiresParensToAddCast(const Expr *E) {
8356 // FIXME: We should have a general way to reason about operator
8357 // precedence and whether parens are actually needed here.
8358 // Take care of a few common cases where they aren't.
8359 const Expr *Inside = E->IgnoreImpCasts();
8360 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8361 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8362
8363 switch (Inside->getStmtClass()) {
8364 case Stmt::ArraySubscriptExprClass:
8365 case Stmt::CallExprClass:
8366 case Stmt::CharacterLiteralClass:
8367 case Stmt::CXXBoolLiteralExprClass:
8368 case Stmt::DeclRefExprClass:
8369 case Stmt::FloatingLiteralClass:
8370 case Stmt::IntegerLiteralClass:
8371 case Stmt::MemberExprClass:
8372 case Stmt::ObjCArrayLiteralClass:
8373 case Stmt::ObjCBoolLiteralExprClass:
8374 case Stmt::ObjCBoxedExprClass:
8375 case Stmt::ObjCDictionaryLiteralClass:
8376 case Stmt::ObjCEncodeExprClass:
8377 case Stmt::ObjCIvarRefExprClass:
8378 case Stmt::ObjCMessageExprClass:
8379 case Stmt::ObjCPropertyRefExprClass:
8380 case Stmt::ObjCStringLiteralClass:
8381 case Stmt::ObjCSubscriptRefExprClass:
8382 case Stmt::ParenExprClass:
8383 case Stmt::StringLiteralClass:
8384 case Stmt::UnaryOperatorClass:
8385 return false;
8386 default:
8387 return true;
8388 }
8389}
8390
8391static std::pair<QualType, StringRef>
8393 QualType IntendedTy,
8394 const Expr *E) {
8395 // Use a 'while' to peel off layers of typedefs.
8396 QualType TyTy = IntendedTy;
8397 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8398 StringRef Name = UserTy->getDecl()->getName();
8399 QualType CastTy = llvm::StringSwitch<QualType>(Name)
8400 .Case("CFIndex", Context.getNSIntegerType())
8401 .Case("NSInteger", Context.getNSIntegerType())
8402 .Case("NSUInteger", Context.getNSUIntegerType())
8403 .Case("SInt32", Context.IntTy)
8404 .Case("UInt32", Context.UnsignedIntTy)
8405 .Default(QualType());
8406
8407 if (!CastTy.isNull())
8408 return std::make_pair(CastTy, Name);
8409
8410 TyTy = UserTy->desugar();
8411 }
8412
8413 // Strip parens if necessary.
8414 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8415 return shouldNotPrintDirectly(Context,
8416 PE->getSubExpr()->getType(),
8417 PE->getSubExpr());
8418
8419 // If this is a conditional expression, then its result type is constructed
8420 // via usual arithmetic conversions and thus there might be no necessary
8421 // typedef sugar there. Recurse to operands to check for NSInteger &
8422 // Co. usage condition.
8423 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8424 QualType TrueTy, FalseTy;
8425 StringRef TrueName, FalseName;
8426
8427 std::tie(TrueTy, TrueName) =
8428 shouldNotPrintDirectly(Context,
8429 CO->getTrueExpr()->getType(),
8430 CO->getTrueExpr());
8431 std::tie(FalseTy, FalseName) =
8432 shouldNotPrintDirectly(Context,
8433 CO->getFalseExpr()->getType(),
8434 CO->getFalseExpr());
8435
8436 if (TrueTy == FalseTy)
8437 return std::make_pair(TrueTy, TrueName);
8438 else if (TrueTy.isNull())
8439 return std::make_pair(FalseTy, FalseName);
8440 else if (FalseTy.isNull())
8441 return std::make_pair(TrueTy, TrueName);
8442 }
8443
8444 return std::make_pair(QualType(), StringRef());
8445}
8446
8447/// Return true if \p ICE is an implicit argument promotion of an arithmetic
8448/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8449/// type do not count.
8450static bool
8452 QualType From = ICE->getSubExpr()->getType();
8453 QualType To = ICE->getType();
8454 // It's an integer promotion if the destination type is the promoted
8455 // source type.
8456 if (ICE->getCastKind() == CK_IntegralCast &&
8458 S.Context.getPromotedIntegerType(From) == To)
8459 return true;
8460 // Look through vector types, since we do default argument promotion for
8461 // those in OpenCL.
8462 if (const auto *VecTy = From->getAs<ExtVectorType>())
8463 From = VecTy->getElementType();
8464 if (const auto *VecTy = To->getAs<ExtVectorType>())
8465 To = VecTy->getElementType();
8466 // It's a floating promotion if the source type is a lower rank.
8467 return ICE->getCastKind() == CK_FloatingCast &&
8468 S.Context.getFloatingTypeOrder(From, To) < 0;
8469}
8470
8473 DiagnosticsEngine &Diags, SourceLocation Loc) {
8475 if (Diags.isIgnored(
8476 diag::warn_format_conversion_argument_type_mismatch_signedness,
8477 Loc) ||
8478 Diags.isIgnored(
8479 // Arbitrary -Wformat diagnostic to detect -Wno-format:
8480 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
8482 }
8483 }
8484 return Match;
8485}
8486
8487bool
8488CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8489 const char *StartSpecifier,
8490 unsigned SpecifierLen,
8491 const Expr *E) {
8492 using namespace analyze_format_string;
8493 using namespace analyze_printf;
8494
8495 // Now type check the data expression that matches the
8496 // format specifier.
8497 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8498 if (!AT.isValid())
8499 return true;
8500
8501 QualType ExprTy = E->getType();
8502 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8503 ExprTy = TET->getUnderlyingExpr()->getType();
8504 }
8505
8506 // When using the format attribute in C++, you can receive a function or an
8507 // array that will necessarily decay to a pointer when passed to the final
8508 // format consumer. Apply decay before type comparison.
8509 if (ExprTy->canDecayToPointerType())
8510 ExprTy = S.Context.getDecayedType(ExprTy);
8511
8512 // Diagnose attempts to print a boolean value as a character. Unlike other
8513 // -Wformat diagnostics, this is fine from a type perspective, but it still
8514 // doesn't make sense.
8517 const CharSourceRange &CSR =
8518 getSpecifierRange(StartSpecifier, SpecifierLen);
8519 SmallString<4> FSString;
8520 llvm::raw_svector_ostream os(FSString);
8521 FS.toString(os);
8522 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8523 << FSString,
8524 E->getExprLoc(), false, CSR);
8525 return true;
8526 }
8527
8528 // Diagnose attempts to use '%P' with ObjC object types, which will result in
8529 // dumping raw class data (like is-a pointer), not actual data.
8531 ExprTy->isObjCObjectPointerType()) {
8532 const CharSourceRange &CSR =
8533 getSpecifierRange(StartSpecifier, SpecifierLen);
8534 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
8535 E->getExprLoc(), false, CSR);
8536 return true;
8537 }
8538
8539 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
8541 ArgType::MatchKind OrigMatch = Match;
8542
8544 if (Match == ArgType::Match)
8545 return true;
8546
8547 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
8548 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
8549
8550 // Look through argument promotions for our error message's reported type.
8551 // This includes the integral and floating promotions, but excludes array
8552 // and function pointer decay (seeing that an argument intended to be a
8553 // string has type 'char [6]' is probably more confusing than 'char *') and
8554 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8555 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8556 if (isArithmeticArgumentPromotion(S, ICE)) {
8557 E = ICE->getSubExpr();
8558 ExprTy = E->getType();
8559
8560 // Check if we didn't match because of an implicit cast from a 'char'
8561 // or 'short' to an 'int'. This is done because printf is a varargs
8562 // function.
8563 if (ICE->getType() == S.Context.IntTy ||
8564 ICE->getType() == S.Context.UnsignedIntTy) {
8565 // All further checking is done on the subexpression
8566 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
8567 if (OrigMatch == ArgType::NoMatchSignedness &&
8568 ImplicitMatch != ArgType::NoMatchSignedness)
8569 // If the original match was a signedness match this match on the
8570 // implicit cast type also need to be signedness match otherwise we
8571 // might introduce new unexpected warnings from -Wformat-signedness.
8572 return true;
8573 ImplicitMatch = handleFormatSignedness(
8574 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
8575 if (ImplicitMatch == ArgType::Match)
8576 return true;
8577 }
8578 }
8579 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8580 // Special case for 'a', which has type 'int' in C.
8581 // Note, however, that we do /not/ want to treat multibyte constants like
8582 // 'MooV' as characters! This form is deprecated but still exists. In
8583 // addition, don't treat expressions as of type 'char' if one byte length
8584 // modifier is provided.
8585 if (ExprTy == S.Context.IntTy &&
8587 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
8588 ExprTy = S.Context.CharTy;
8589 // To improve check results, we consider a character literal in C
8590 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
8591 // more likely a type confusion situation, so we will suggest to
8592 // use '%hhd' instead by discarding the MatchPromotion.
8593 if (Match == ArgType::MatchPromotion)
8595 }
8596 }
8597 if (Match == ArgType::MatchPromotion) {
8598 // WG14 N2562 only clarified promotions in *printf
8599 // For NSLog in ObjC, just preserve -Wformat behavior
8600 if (!S.getLangOpts().ObjC &&
8601 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
8602 ImplicitMatch != ArgType::NoMatchTypeConfusion)
8603 return true;
8605 }
8606 if (ImplicitMatch == ArgType::NoMatchPedantic ||
8607 ImplicitMatch == ArgType::NoMatchTypeConfusion)
8608 Match = ImplicitMatch;
8609 assert(Match != ArgType::MatchPromotion);
8610
8611 // Look through unscoped enums to their underlying type.
8612 bool IsEnum = false;
8613 bool IsScopedEnum = false;
8614 QualType IntendedTy = ExprTy;
8615 if (const auto *ED = ExprTy->getAsEnumDecl()) {
8616 IntendedTy = ED->getIntegerType();
8617 if (!ED->isScoped()) {
8618 ExprTy = IntendedTy;
8619 // This controls whether we're talking about the underlying type or not,
8620 // which we only want to do when it's an unscoped enum.
8621 IsEnum = true;
8622 } else {
8623 IsScopedEnum = true;
8624 }
8625 }
8626
8627 // %C in an Objective-C context prints a unichar, not a wchar_t.
8628 // If the argument is an integer of some kind, believe the %C and suggest
8629 // a cast instead of changing the conversion specifier.
8630 if (isObjCContext() &&
8633 !ExprTy->isCharType()) {
8634 // 'unichar' is defined as a typedef of unsigned short, but we should
8635 // prefer using the typedef if it is visible.
8636 IntendedTy = S.Context.UnsignedShortTy;
8637
8638 // While we are here, check if the value is an IntegerLiteral that happens
8639 // to be within the valid range.
8640 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8641 const llvm::APInt &V = IL->getValue();
8642 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8643 return true;
8644 }
8645
8646 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8648 if (S.LookupName(Result, S.getCurScope())) {
8649 NamedDecl *ND = Result.getFoundDecl();
8650 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8651 if (TD->getUnderlyingType() == IntendedTy)
8652 IntendedTy =
8654 /*Qualifier=*/std::nullopt, TD);
8655 }
8656 }
8657 }
8658
8659 // Special-case some of Darwin's platform-independence types by suggesting
8660 // casts to primitive types that are known to be large enough.
8661 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8662 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8663 QualType CastTy;
8664 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8665 if (!CastTy.isNull()) {
8666 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8667 // (long in ASTContext). Only complain to pedants or when they're the
8668 // underlying type of a scoped enum (which always needs a cast).
8669 if (!IsScopedEnum &&
8670 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8671 (AT.isSizeT() || AT.isPtrdiffT()) &&
8672 AT.matchesType(S.Context, CastTy))
8674 IntendedTy = CastTy;
8675 ShouldNotPrintDirectly = true;
8676 }
8677 }
8678
8679 // We may be able to offer a FixItHint if it is a supported type.
8680 PrintfSpecifier fixedFS = FS;
8681 bool Success =
8682 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8683
8684 if (Success) {
8685 // Get the fix string from the fixed format specifier
8686 SmallString<16> buf;
8687 llvm::raw_svector_ostream os(buf);
8688 fixedFS.toString(os);
8689
8690 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8691
8692 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
8693 unsigned Diag;
8694 switch (Match) {
8695 case ArgType::Match:
8698 llvm_unreachable("expected non-matching");
8700 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
8701 break;
8703 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8704 break;
8706 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8707 break;
8708 case ArgType::NoMatch:
8709 Diag = diag::warn_format_conversion_argument_type_mismatch;
8710 break;
8711 }
8712
8713 // In this case, the specifier is wrong and should be changed to match
8714 // the argument.
8715 EmitFormatDiagnostic(S.PDiag(Diag)
8717 << IntendedTy << IsEnum << E->getSourceRange(),
8718 E->getBeginLoc(),
8719 /*IsStringLocation*/ false, SpecRange,
8720 FixItHint::CreateReplacement(SpecRange, os.str()));
8721 } else {
8722 // The canonical type for formatting this value is different from the
8723 // actual type of the expression. (This occurs, for example, with Darwin's
8724 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8725 // should be printed as 'long' for 64-bit compatibility.)
8726 // Rather than emitting a normal format/argument mismatch, we want to
8727 // add a cast to the recommended type (and correct the format string
8728 // if necessary). We should also do so for scoped enumerations.
8729 SmallString<16> CastBuf;
8730 llvm::raw_svector_ostream CastFix(CastBuf);
8731 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
8732 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8733 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
8734
8736 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
8737 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
8738 E->getExprLoc());
8739 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
8740 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8741
8742 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8743 // If there's already a cast present, just replace it.
8744 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8745 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8746
8747 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
8748 // If the expression has high enough precedence,
8749 // just write the C-style cast.
8750 Hints.push_back(
8751 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8752 } else {
8753 // Otherwise, add parens around the expression as well as the cast.
8754 CastFix << "(";
8755 Hints.push_back(
8756 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8757
8758 // We don't use getLocForEndOfToken because it returns invalid source
8759 // locations for macro expansions (by design).
8763 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8764 }
8765
8766 if (ShouldNotPrintDirectly && !IsScopedEnum) {
8767 // The expression has a type that should not be printed directly.
8768 // We extract the name from the typedef because we don't want to show
8769 // the underlying type in the diagnostic.
8770 StringRef Name;
8771 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
8772 Name = TypedefTy->getDecl()->getName();
8773 else
8774 Name = CastTyName;
8775 unsigned Diag = Match == ArgType::NoMatchPedantic
8776 ? diag::warn_format_argument_needs_cast_pedantic
8777 : diag::warn_format_argument_needs_cast;
8778 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8779 << E->getSourceRange(),
8780 E->getBeginLoc(), /*IsStringLocation=*/false,
8781 SpecRange, Hints);
8782 } else {
8783 // In this case, the expression could be printed using a different
8784 // specifier, but we've decided that the specifier is probably correct
8785 // and we should cast instead. Just use the normal warning message.
8786
8787 unsigned Diag =
8788 IsScopedEnum
8789 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8790 : diag::warn_format_conversion_argument_type_mismatch;
8791
8792 EmitFormatDiagnostic(
8793 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8794 << IsEnum << E->getSourceRange(),
8795 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8796 }
8797 }
8798 } else {
8799 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8800 SpecifierLen);
8801 // Since the warning for passing non-POD types to variadic functions
8802 // was deferred until now, we emit a warning for non-POD
8803 // arguments here.
8804 bool EmitTypeMismatch = false;
8805 switch (S.isValidVarArgType(ExprTy)) {
8806 case VarArgKind::Valid:
8808 unsigned Diag;
8809 switch (Match) {
8810 case ArgType::Match:
8813 llvm_unreachable("expected non-matching");
8815 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
8816 break;
8818 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8819 break;
8821 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8822 break;
8823 case ArgType::NoMatch:
8824 Diag = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)
8825 ? diag::err_format_conversion_argument_type_mismatch
8826 : diag::warn_format_conversion_argument_type_mismatch;
8827 break;
8828 }
8829
8830 EmitFormatDiagnostic(
8831 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8832 << IsEnum << CSR << E->getSourceRange(),
8833 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8834 break;
8835 }
8838 if (CallType == VariadicCallType::DoesNotApply) {
8839 EmitTypeMismatch = true;
8840 } else {
8841 EmitFormatDiagnostic(
8842 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8843 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8844 << AT.getRepresentativeTypeName(S.Context) << CSR
8845 << E->getSourceRange(),
8846 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8847 checkForCStrMembers(AT, E);
8848 }
8849 break;
8850
8852 if (CallType == VariadicCallType::DoesNotApply)
8853 EmitTypeMismatch = true;
8854 else if (ExprTy->isObjCObjectType())
8855 EmitFormatDiagnostic(
8856 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8857 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8858 << AT.getRepresentativeTypeName(S.Context) << CSR
8859 << E->getSourceRange(),
8860 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8861 else
8862 // FIXME: If this is an initializer list, suggest removing the braces
8863 // or inserting a cast to the target type.
8864 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8865 << isa<InitListExpr>(E) << ExprTy << CallType
8867 break;
8868 }
8869
8870 if (EmitTypeMismatch) {
8871 // The function is not variadic, so we do not generate warnings about
8872 // being allowed to pass that object as a variadic argument. Instead,
8873 // since there are inherently no printf specifiers for types which cannot
8874 // be passed as variadic arguments, emit a plain old specifier mismatch
8875 // argument.
8876 EmitFormatDiagnostic(
8877 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8878 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
8879 << E->getSourceRange(),
8880 E->getBeginLoc(), false, CSR);
8881 }
8882
8883 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8884 "format string specifier index out of range");
8885 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8886 }
8887
8888 return true;
8889}
8890
8891//===--- CHECK: Scanf format string checking ------------------------------===//
8892
8893namespace {
8894
8895class CheckScanfHandler : public CheckFormatHandler {
8896public:
8897 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8898 const Expr *origFormatExpr, FormatStringType type,
8899 unsigned firstDataArg, unsigned numDataArgs,
8900 const char *beg, Sema::FormatArgumentPassingKind APK,
8901 ArrayRef<const Expr *> Args, unsigned formatIdx,
8902 bool inFunctionCall, VariadicCallType CallType,
8903 llvm::SmallBitVector &CheckedVarArgs,
8904 UncoveredArgHandler &UncoveredArg)
8905 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8906 numDataArgs, beg, APK, Args, formatIdx,
8907 inFunctionCall, CallType, CheckedVarArgs,
8908 UncoveredArg) {}
8909
8910 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8911 const char *startSpecifier,
8912 unsigned specifierLen) override;
8913
8914 bool HandleInvalidScanfConversionSpecifier(
8915 const analyze_scanf::ScanfSpecifier &FS,
8916 const char *startSpecifier,
8917 unsigned specifierLen) override;
8918
8919 void HandleIncompleteScanList(const char *start, const char *end) override;
8920};
8921
8922} // namespace
8923
8924void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8925 const char *end) {
8926 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8927 getLocationOfByte(end), /*IsStringLocation*/true,
8928 getSpecifierRange(start, end - start));
8929}
8930
8931bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8933 const char *startSpecifier,
8934 unsigned specifierLen) {
8937
8938 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8939 getLocationOfByte(CS.getStart()),
8940 startSpecifier, specifierLen,
8941 CS.getStart(), CS.getLength());
8942}
8943
8944bool CheckScanfHandler::HandleScanfSpecifier(
8946 const char *startSpecifier,
8947 unsigned specifierLen) {
8948 using namespace analyze_scanf;
8949 using namespace analyze_format_string;
8950
8951 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8952
8953 // Handle case where '%' and '*' don't consume an argument. These shouldn't
8954 // be used to decide if we are using positional arguments consistently.
8955 if (FS.consumesDataArgument()) {
8956 if (atFirstArg) {
8957 atFirstArg = false;
8958 usesPositionalArgs = FS.usesPositionalArg();
8959 }
8960 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8961 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8962 startSpecifier, specifierLen);
8963 return false;
8964 }
8965 }
8966
8967 // Check if the field with is non-zero.
8968 const OptionalAmount &Amt = FS.getFieldWidth();
8970 if (Amt.getConstantAmount() == 0) {
8971 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8972 Amt.getConstantLength());
8973 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8974 getLocationOfByte(Amt.getStart()),
8975 /*IsStringLocation*/true, R,
8977 }
8978 }
8979
8980 if (!FS.consumesDataArgument()) {
8981 // FIXME: Technically specifying a precision or field width here
8982 // makes no sense. Worth issuing a warning at some point.
8983 return true;
8984 }
8985
8986 // Consume the argument.
8987 unsigned argIndex = FS.getArgIndex();
8988 if (argIndex < NumDataArgs) {
8989 // The check to see if the argIndex is valid will come later.
8990 // We set the bit here because we may exit early from this
8991 // function if we encounter some other error.
8992 CoveredArgs.set(argIndex);
8993 }
8994
8995 // Check the length modifier is valid with the given conversion specifier.
8997 S.getLangOpts()))
8998 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8999 diag::warn_format_nonsensical_length);
9000 else if (!FS.hasStandardLengthModifier())
9001 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9003 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9004 diag::warn_format_non_standard_conversion_spec);
9005
9007 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9008
9009 // The remaining checks depend on the data arguments.
9010 if (!HasFormatArguments())
9011 return true;
9012
9013 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9014 return false;
9015
9016 // Check that the argument type matches the format specifier.
9017 const Expr *Ex = getDataArg(argIndex);
9018 if (!Ex)
9019 return true;
9020
9022
9023 if (!AT.isValid()) {
9024 return true;
9025 }
9026
9028 AT.matchesType(S.Context, Ex->getType());
9031 return true;
9034
9035 ScanfSpecifier fixedFS = FS;
9036 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9037 S.getLangOpts(), S.Context);
9038
9039 unsigned Diag =
9040 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9041 : Signedness
9042 ? diag::warn_format_conversion_argument_type_mismatch_signedness
9043 : diag::warn_format_conversion_argument_type_mismatch;
9044
9045 if (Success) {
9046 // Get the fix string from the fixed format specifier.
9047 SmallString<128> buf;
9048 llvm::raw_svector_ostream os(buf);
9049 fixedFS.toString(os);
9050
9051 EmitFormatDiagnostic(
9053 << Ex->getType() << false << Ex->getSourceRange(),
9054 Ex->getBeginLoc(),
9055 /*IsStringLocation*/ false,
9056 getSpecifierRange(startSpecifier, specifierLen),
9058 getSpecifierRange(startSpecifier, specifierLen), os.str()));
9059 } else {
9060 EmitFormatDiagnostic(S.PDiag(Diag)
9062 << Ex->getType() << false << Ex->getSourceRange(),
9063 Ex->getBeginLoc(),
9064 /*IsStringLocation*/ false,
9065 getSpecifierRange(startSpecifier, specifierLen));
9066 }
9067
9068 return true;
9069}
9070
9071static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
9073 const StringLiteral *Fmt,
9075 const Expr *FmtExpr, bool InFunctionCall) {
9076 bool HadError = false;
9077 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
9078 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
9079 while (FmtIter < FmtEnd && RefIter < RefEnd) {
9080 // In positional-style format strings, the same specifier can appear
9081 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
9082 // are sorted by getPosition(), and we process each range of equal
9083 // getPosition() values as one group.
9084 // RefArgs are taken from a string literal that was given to
9085 // attribute(format_matches), and if we got this far, we have already
9086 // verified that if it has positional specifiers that appear in multiple
9087 // locations, then they are all mutually compatible. What's left for us to
9088 // do is verify that all specifiers with the same position in FmtArgs are
9089 // compatible with the RefArgs specifiers. We check each specifier from
9090 // FmtArgs against the first member of the RefArgs group.
9091 for (; FmtIter < FmtEnd; ++FmtIter) {
9092 // Clang does not diagnose missing format specifiers in positional-style
9093 // strings (TODO: which it probably should do, as it is UB to skip over a
9094 // format argument). Skip specifiers if needed.
9095 if (FmtIter->getPosition() < RefIter->getPosition())
9096 continue;
9097
9098 // Delimits a new getPosition() value.
9099 if (FmtIter->getPosition() > RefIter->getPosition())
9100 break;
9101
9102 HadError |=
9103 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
9104 }
9105
9106 // Jump RefIter to the start of the next group.
9107 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
9108 return Arg.getPosition() != RefIter->getPosition();
9109 });
9110 }
9111
9112 if (FmtIter < FmtEnd) {
9113 CheckFormatHandler::EmitFormatDiagnostic(
9114 S, InFunctionCall, FmtExpr,
9115 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
9116 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
9117 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
9118 } else if (RefIter < RefEnd) {
9119 CheckFormatHandler::EmitFormatDiagnostic(
9120 S, InFunctionCall, FmtExpr,
9121 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
9122 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
9123 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
9124 << 1 << RefIter->getSourceRange();
9125 }
9126 return !HadError;
9127}
9128
9130 Sema &S, const FormatStringLiteral *FExpr,
9131 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
9133 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
9134 bool inFunctionCall, VariadicCallType CallType,
9135 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
9136 bool IgnoreStringsWithoutSpecifiers) {
9137 // CHECK: is the format string a wide literal?
9138 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9139 CheckFormatHandler::EmitFormatDiagnostic(
9140 S, inFunctionCall, Args[format_idx],
9141 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9142 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9143 return;
9144 }
9145
9146 // Str - The format string. NOTE: this is NOT null-terminated!
9147 StringRef StrRef = FExpr->getString();
9148 const char *Str = StrRef.data();
9149 // Account for cases where the string literal is truncated in a declaration.
9150 const ConstantArrayType *T =
9151 S.Context.getAsConstantArrayType(FExpr->getType());
9152 assert(T && "String literal not of constant array type!");
9153 size_t TypeSize = T->getZExtSize();
9154 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9155 const unsigned numDataArgs = Args.size() - firstDataArg;
9156
9157 if (IgnoreStringsWithoutSpecifiers &&
9159 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9160 return;
9161
9162 // Emit a warning if the string literal is truncated and does not contain an
9163 // embedded null character.
9164 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9165 CheckFormatHandler::EmitFormatDiagnostic(
9166 S, inFunctionCall, Args[format_idx],
9167 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9168 FExpr->getBeginLoc(),
9169 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9170 return;
9171 }
9172
9173 // CHECK: empty format string?
9174 if (StrLen == 0 && numDataArgs > 0) {
9175 CheckFormatHandler::EmitFormatDiagnostic(
9176 S, inFunctionCall, Args[format_idx],
9177 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9178 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9179 return;
9180 }
9181
9186 bool IsObjC =
9188 if (ReferenceFormatString == nullptr) {
9189 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9190 numDataArgs, IsObjC, Str, APK, Args, format_idx,
9191 inFunctionCall, CallType, CheckedVarArgs,
9192 UncoveredArg);
9193
9195 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
9198 H.DoneProcessing();
9199 } else {
9201 Type, ReferenceFormatString, FExpr->getFormatString(),
9202 inFunctionCall ? nullptr : Args[format_idx]);
9203 }
9204 } else if (Type == FormatStringType::Scanf) {
9205 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9206 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
9207 CallType, CheckedVarArgs, UncoveredArg);
9208
9210 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9211 H.DoneProcessing();
9212 } // TODO: handle other formats
9213}
9214
9216 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
9217 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
9222 return true;
9223
9224 bool IsObjC =
9227 FormatStringLiteral RefLit = AuthoritativeFormatString;
9228 FormatStringLiteral TestLit = TestedFormatString;
9229 const Expr *Arg;
9230 bool DiagAtStringLiteral;
9231 if (FunctionCallArg) {
9232 Arg = FunctionCallArg;
9233 DiagAtStringLiteral = false;
9234 } else {
9235 Arg = TestedFormatString;
9236 DiagAtStringLiteral = true;
9237 }
9238 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
9239 AuthoritativeFormatString, Type,
9240 IsObjC, true, RefArgs) &&
9241 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
9242 DiagAtStringLiteral, FmtArgs)) {
9243 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
9244 TestedFormatString, FmtArgs, Arg,
9245 DiagAtStringLiteral);
9246 }
9247 return false;
9248}
9249
9251 const StringLiteral *Str) {
9256 return true;
9257
9258 FormatStringLiteral RefLit = Str;
9260 bool IsObjC =
9262 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
9263 true, Args))
9264 return false;
9265
9266 // Group arguments by getPosition() value, and check that each member of the
9267 // group is compatible with the first member. This verifies that when
9268 // positional arguments are used multiple times (such as %2$i %2$d), all uses
9269 // are mutually compatible. As an optimization, don't test the first member
9270 // against itself.
9271 bool HadError = false;
9272 auto Iter = Args.begin();
9273 auto End = Args.end();
9274 while (Iter != End) {
9275 const auto &FirstInGroup = *Iter;
9276 for (++Iter;
9277 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
9278 ++Iter) {
9279 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
9280 }
9281 }
9282 return !HadError;
9283}
9284
9286 // Str - The format string. NOTE: this is NOT null-terminated!
9287 StringRef StrRef = FExpr->getString();
9288 const char *Str = StrRef.data();
9289 // Account for cases where the string literal is truncated in a declaration.
9290 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9291 assert(T && "String literal not of constant array type!");
9292 size_t TypeSize = T->getZExtSize();
9293 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9294 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9295 getLangOpts(),
9296 Context.getTargetInfo());
9297}
9298
9299//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9300
9301// Returns the related absolute value function that is larger, of 0 if one
9302// does not exist.
9303static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9304 switch (AbsFunction) {
9305 default:
9306 return 0;
9307
9308 case Builtin::BI__builtin_abs:
9309 return Builtin::BI__builtin_labs;
9310 case Builtin::BI__builtin_labs:
9311 return Builtin::BI__builtin_llabs;
9312 case Builtin::BI__builtin_llabs:
9313 return 0;
9314
9315 case Builtin::BI__builtin_fabsf:
9316 return Builtin::BI__builtin_fabs;
9317 case Builtin::BI__builtin_fabs:
9318 return Builtin::BI__builtin_fabsl;
9319 case Builtin::BI__builtin_fabsl:
9320 return 0;
9321
9322 case Builtin::BI__builtin_cabsf:
9323 return Builtin::BI__builtin_cabs;
9324 case Builtin::BI__builtin_cabs:
9325 return Builtin::BI__builtin_cabsl;
9326 case Builtin::BI__builtin_cabsl:
9327 return 0;
9328
9329 case Builtin::BIabs:
9330 return Builtin::BIlabs;
9331 case Builtin::BIlabs:
9332 return Builtin::BIllabs;
9333 case Builtin::BIllabs:
9334 return 0;
9335
9336 case Builtin::BIfabsf:
9337 return Builtin::BIfabs;
9338 case Builtin::BIfabs:
9339 return Builtin::BIfabsl;
9340 case Builtin::BIfabsl:
9341 return 0;
9342
9343 case Builtin::BIcabsf:
9344 return Builtin::BIcabs;
9345 case Builtin::BIcabs:
9346 return Builtin::BIcabsl;
9347 case Builtin::BIcabsl:
9348 return 0;
9349 }
9350}
9351
9352// Returns the argument type of the absolute value function.
9354 unsigned AbsType) {
9355 if (AbsType == 0)
9356 return QualType();
9357
9359 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9361 return QualType();
9362
9364 if (!FT)
9365 return QualType();
9366
9367 if (FT->getNumParams() != 1)
9368 return QualType();
9369
9370 return FT->getParamType(0);
9371}
9372
9373// Returns the best absolute value function, or zero, based on type and
9374// current absolute value function.
9375static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9376 unsigned AbsFunctionKind) {
9377 unsigned BestKind = 0;
9378 uint64_t ArgSize = Context.getTypeSize(ArgType);
9379 for (unsigned Kind = AbsFunctionKind; Kind != 0;
9380 Kind = getLargerAbsoluteValueFunction(Kind)) {
9381 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9382 if (Context.getTypeSize(ParamType) >= ArgSize) {
9383 if (BestKind == 0)
9384 BestKind = Kind;
9385 else if (Context.hasSameType(ParamType, ArgType)) {
9386 BestKind = Kind;
9387 break;
9388 }
9389 }
9390 }
9391 return BestKind;
9392}
9393
9399
9401 if (T->isIntegralOrEnumerationType())
9402 return AVK_Integer;
9403 if (T->isRealFloatingType())
9404 return AVK_Floating;
9405 if (T->isAnyComplexType())
9406 return AVK_Complex;
9407
9408 llvm_unreachable("Type not integer, floating, or complex");
9409}
9410
9411// Changes the absolute value function to a different type. Preserves whether
9412// the function is a builtin.
9413static unsigned changeAbsFunction(unsigned AbsKind,
9414 AbsoluteValueKind ValueKind) {
9415 switch (ValueKind) {
9416 case AVK_Integer:
9417 switch (AbsKind) {
9418 default:
9419 return 0;
9420 case Builtin::BI__builtin_fabsf:
9421 case Builtin::BI__builtin_fabs:
9422 case Builtin::BI__builtin_fabsl:
9423 case Builtin::BI__builtin_cabsf:
9424 case Builtin::BI__builtin_cabs:
9425 case Builtin::BI__builtin_cabsl:
9426 return Builtin::BI__builtin_abs;
9427 case Builtin::BIfabsf:
9428 case Builtin::BIfabs:
9429 case Builtin::BIfabsl:
9430 case Builtin::BIcabsf:
9431 case Builtin::BIcabs:
9432 case Builtin::BIcabsl:
9433 return Builtin::BIabs;
9434 }
9435 case AVK_Floating:
9436 switch (AbsKind) {
9437 default:
9438 return 0;
9439 case Builtin::BI__builtin_abs:
9440 case Builtin::BI__builtin_labs:
9441 case Builtin::BI__builtin_llabs:
9442 case Builtin::BI__builtin_cabsf:
9443 case Builtin::BI__builtin_cabs:
9444 case Builtin::BI__builtin_cabsl:
9445 return Builtin::BI__builtin_fabsf;
9446 case Builtin::BIabs:
9447 case Builtin::BIlabs:
9448 case Builtin::BIllabs:
9449 case Builtin::BIcabsf:
9450 case Builtin::BIcabs:
9451 case Builtin::BIcabsl:
9452 return Builtin::BIfabsf;
9453 }
9454 case AVK_Complex:
9455 switch (AbsKind) {
9456 default:
9457 return 0;
9458 case Builtin::BI__builtin_abs:
9459 case Builtin::BI__builtin_labs:
9460 case Builtin::BI__builtin_llabs:
9461 case Builtin::BI__builtin_fabsf:
9462 case Builtin::BI__builtin_fabs:
9463 case Builtin::BI__builtin_fabsl:
9464 return Builtin::BI__builtin_cabsf;
9465 case Builtin::BIabs:
9466 case Builtin::BIlabs:
9467 case Builtin::BIllabs:
9468 case Builtin::BIfabsf:
9469 case Builtin::BIfabs:
9470 case Builtin::BIfabsl:
9471 return Builtin::BIcabsf;
9472 }
9473 }
9474 llvm_unreachable("Unable to convert function");
9475}
9476
9477static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9478 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9479 if (!FnInfo)
9480 return 0;
9481
9482 switch (FDecl->getBuiltinID()) {
9483 default:
9484 return 0;
9485 case Builtin::BI__builtin_abs:
9486 case Builtin::BI__builtin_fabs:
9487 case Builtin::BI__builtin_fabsf:
9488 case Builtin::BI__builtin_fabsl:
9489 case Builtin::BI__builtin_labs:
9490 case Builtin::BI__builtin_llabs:
9491 case Builtin::BI__builtin_cabs:
9492 case Builtin::BI__builtin_cabsf:
9493 case Builtin::BI__builtin_cabsl:
9494 case Builtin::BIabs:
9495 case Builtin::BIlabs:
9496 case Builtin::BIllabs:
9497 case Builtin::BIfabs:
9498 case Builtin::BIfabsf:
9499 case Builtin::BIfabsl:
9500 case Builtin::BIcabs:
9501 case Builtin::BIcabsf:
9502 case Builtin::BIcabsl:
9503 return FDecl->getBuiltinID();
9504 }
9505 llvm_unreachable("Unknown Builtin type");
9506}
9507
9508// If the replacement is valid, emit a note with replacement function.
9509// Additionally, suggest including the proper header if not already included.
9511 unsigned AbsKind, QualType ArgType) {
9512 bool EmitHeaderHint = true;
9513 const char *HeaderName = nullptr;
9514 std::string FunctionName;
9515 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9516 FunctionName = "std::abs";
9517 if (ArgType->isIntegralOrEnumerationType()) {
9518 HeaderName = "cstdlib";
9519 } else if (ArgType->isRealFloatingType()) {
9520 HeaderName = "cmath";
9521 } else {
9522 llvm_unreachable("Invalid Type");
9523 }
9524
9525 // Lookup all std::abs
9526 if (NamespaceDecl *Std = S.getStdNamespace()) {
9527 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9529 S.LookupQualifiedName(R, Std);
9530
9531 for (const auto *I : R) {
9532 const FunctionDecl *FDecl = nullptr;
9533 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9534 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9535 } else {
9536 FDecl = dyn_cast<FunctionDecl>(I);
9537 }
9538 if (!FDecl)
9539 continue;
9540
9541 // Found std::abs(), check that they are the right ones.
9542 if (FDecl->getNumParams() != 1)
9543 continue;
9544
9545 // Check that the parameter type can handle the argument.
9546 QualType ParamType = FDecl->getParamDecl(0)->getType();
9547 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9548 S.Context.getTypeSize(ArgType) <=
9549 S.Context.getTypeSize(ParamType)) {
9550 // Found a function, don't need the header hint.
9551 EmitHeaderHint = false;
9552 break;
9553 }
9554 }
9555 }
9556 } else {
9557 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9558 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9559
9560 if (HeaderName) {
9561 DeclarationName DN(&S.Context.Idents.get(FunctionName));
9562 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9564 S.LookupName(R, S.getCurScope());
9565
9566 if (R.isSingleResult()) {
9567 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9568 if (FD && FD->getBuiltinID() == AbsKind) {
9569 EmitHeaderHint = false;
9570 } else {
9571 return;
9572 }
9573 } else if (!R.empty()) {
9574 return;
9575 }
9576 }
9577 }
9578
9579 S.Diag(Loc, diag::note_replace_abs_function)
9580 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9581
9582 if (!HeaderName)
9583 return;
9584
9585 if (!EmitHeaderHint)
9586 return;
9587
9588 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9589 << FunctionName;
9590}
9591
9592template <std::size_t StrLen>
9593static bool IsStdFunction(const FunctionDecl *FDecl,
9594 const char (&Str)[StrLen]) {
9595 if (!FDecl)
9596 return false;
9597 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9598 return false;
9599 if (!FDecl->isInStdNamespace())
9600 return false;
9601
9602 return true;
9603}
9604
9605enum class MathCheck { NaN, Inf };
9606static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
9607 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
9608 return llvm::is_contained(names, calleeName);
9609 };
9610
9611 switch (Check) {
9612 case MathCheck::NaN:
9613 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
9614 "__builtin_nanf16", "__builtin_nanf128"});
9615 case MathCheck::Inf:
9616 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
9617 "__builtin_inff16", "__builtin_inff128"});
9618 }
9619 llvm_unreachable("unknown MathCheck");
9620}
9621
9622static bool IsInfinityFunction(const FunctionDecl *FDecl) {
9623 if (FDecl->getName() != "infinity")
9624 return false;
9625
9626 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
9627 const CXXRecordDecl *RDecl = MDecl->getParent();
9628 if (RDecl->getName() != "numeric_limits")
9629 return false;
9630
9631 if (const NamespaceDecl *NSDecl =
9632 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
9633 return NSDecl->isStdNamespace();
9634 }
9635
9636 return false;
9637}
9638
9639void Sema::CheckInfNaNFunction(const CallExpr *Call,
9640 const FunctionDecl *FDecl) {
9641 if (!FDecl->getIdentifier())
9642 return;
9643
9644 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
9645 if (FPO.getNoHonorNaNs() &&
9646 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
9648 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9649 << 1 << 0 << Call->getSourceRange();
9650 return;
9651 }
9652
9653 if (FPO.getNoHonorInfs() &&
9654 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
9655 IsInfinityFunction(FDecl) ||
9657 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9658 << 0 << 0 << Call->getSourceRange();
9659 }
9660}
9661
9662void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9663 const FunctionDecl *FDecl) {
9664 if (Call->getNumArgs() != 1)
9665 return;
9666
9667 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9668 bool IsStdAbs = IsStdFunction(FDecl, "abs");
9669 if (AbsKind == 0 && !IsStdAbs)
9670 return;
9671
9672 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9673 QualType ParamType = Call->getArg(0)->getType();
9674
9675 // Unsigned types cannot be negative. Suggest removing the absolute value
9676 // function call.
9677 if (ArgType->isUnsignedIntegerType()) {
9678 std::string FunctionName =
9679 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9680 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9681 Diag(Call->getExprLoc(), diag::note_remove_abs)
9682 << FunctionName
9683 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9684 return;
9685 }
9686
9687 // Taking the absolute value of a pointer is very suspicious, they probably
9688 // wanted to index into an array, dereference a pointer, call a function, etc.
9689 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9690 unsigned DiagType = 0;
9691 if (ArgType->isFunctionType())
9692 DiagType = 1;
9693 else if (ArgType->isArrayType())
9694 DiagType = 2;
9695
9696 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9697 return;
9698 }
9699
9700 // std::abs has overloads which prevent most of the absolute value problems
9701 // from occurring.
9702 if (IsStdAbs)
9703 return;
9704
9705 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9706 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9707
9708 // The argument and parameter are the same kind. Check if they are the right
9709 // size.
9710 if (ArgValueKind == ParamValueKind) {
9711 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9712 return;
9713
9714 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9715 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9716 << FDecl << ArgType << ParamType;
9717
9718 if (NewAbsKind == 0)
9719 return;
9720
9721 emitReplacement(*this, Call->getExprLoc(),
9722 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9723 return;
9724 }
9725
9726 // ArgValueKind != ParamValueKind
9727 // The wrong type of absolute value function was used. Attempt to find the
9728 // proper one.
9729 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9730 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9731 if (NewAbsKind == 0)
9732 return;
9733
9734 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9735 << FDecl << ParamValueKind << ArgValueKind;
9736
9737 emitReplacement(*this, Call->getExprLoc(),
9738 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9739}
9740
9741//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9742void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9743 const FunctionDecl *FDecl) {
9744 if (!Call || !FDecl) return;
9745
9746 // Ignore template specializations and macros.
9747 if (inTemplateInstantiation()) return;
9748 if (Call->getExprLoc().isMacroID()) return;
9749
9750 // Only care about the one template argument, two function parameter std::max
9751 if (Call->getNumArgs() != 2) return;
9752 if (!IsStdFunction(FDecl, "max")) return;
9753 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9754 if (!ArgList) return;
9755 if (ArgList->size() != 1) return;
9756
9757 // Check that template type argument is unsigned integer.
9758 const auto& TA = ArgList->get(0);
9759 if (TA.getKind() != TemplateArgument::Type) return;
9760 QualType ArgType = TA.getAsType();
9761 if (!ArgType->isUnsignedIntegerType()) return;
9762
9763 // See if either argument is a literal zero.
9764 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9765 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9766 if (!MTE) return false;
9767 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9768 if (!Num) return false;
9769 if (Num->getValue() != 0) return false;
9770 return true;
9771 };
9772
9773 const Expr *FirstArg = Call->getArg(0);
9774 const Expr *SecondArg = Call->getArg(1);
9775 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9776 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9777
9778 // Only warn when exactly one argument is zero.
9779 if (IsFirstArgZero == IsSecondArgZero) return;
9780
9781 SourceRange FirstRange = FirstArg->getSourceRange();
9782 SourceRange SecondRange = SecondArg->getSourceRange();
9783
9784 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9785
9786 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9787 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9788
9789 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9790 SourceRange RemovalRange;
9791 if (IsFirstArgZero) {
9792 RemovalRange = SourceRange(FirstRange.getBegin(),
9793 SecondRange.getBegin().getLocWithOffset(-1));
9794 } else {
9795 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9796 SecondRange.getEnd());
9797 }
9798
9799 Diag(Call->getExprLoc(), diag::note_remove_max_call)
9800 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9801 << FixItHint::CreateRemoval(RemovalRange);
9802}
9803
9804//===--- CHECK: Standard memory functions ---------------------------------===//
9805
9806/// Takes the expression passed to the size_t parameter of functions
9807/// such as memcmp, strncat, etc and warns if it's a comparison.
9808///
9809/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9811 const IdentifierInfo *FnName,
9812 SourceLocation FnLoc,
9813 SourceLocation RParenLoc) {
9814 const auto *Size = dyn_cast<BinaryOperator>(E);
9815 if (!Size)
9816 return false;
9817
9818 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9819 if (!Size->isComparisonOp() && !Size->isLogicalOp())
9820 return false;
9821
9822 SourceRange SizeRange = Size->getSourceRange();
9823 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9824 << SizeRange << FnName;
9825 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9826 << FnName
9828 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9829 << FixItHint::CreateRemoval(RParenLoc);
9830 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9831 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9833 ")");
9834
9835 return true;
9836}
9837
9838/// Determine whether the given type is or contains a dynamic class type
9839/// (e.g., whether it has a vtable).
9841 bool &IsContained) {
9842 // Look through array types while ignoring qualifiers.
9843 const Type *Ty = T->getBaseElementTypeUnsafe();
9844 IsContained = false;
9845
9846 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9847 RD = RD ? RD->getDefinition() : nullptr;
9848 if (!RD || RD->isInvalidDecl())
9849 return nullptr;
9850
9851 if (RD->isDynamicClass())
9852 return RD;
9853
9854 // Check all the fields. If any bases were dynamic, the class is dynamic.
9855 // It's impossible for a class to transitively contain itself by value, so
9856 // infinite recursion is impossible.
9857 for (auto *FD : RD->fields()) {
9858 bool SubContained;
9859 if (const CXXRecordDecl *ContainedRD =
9860 getContainedDynamicClass(FD->getType(), SubContained)) {
9861 IsContained = true;
9862 return ContainedRD;
9863 }
9864 }
9865
9866 return nullptr;
9867}
9868
9870 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9871 if (Unary->getKind() == UETT_SizeOf)
9872 return Unary;
9873 return nullptr;
9874}
9875
9876/// If E is a sizeof expression, returns its argument expression,
9877/// otherwise returns NULL.
9878static const Expr *getSizeOfExprArg(const Expr *E) {
9880 if (!SizeOf->isArgumentType())
9881 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9882 return nullptr;
9883}
9884
9885/// If E is a sizeof expression, returns its argument type.
9888 return SizeOf->getTypeOfArgument();
9889 return QualType();
9890}
9891
9892namespace {
9893
9894struct SearchNonTrivialToInitializeField
9895 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9896 using Super =
9897 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9898
9899 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9900
9901 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9902 SourceLocation SL) {
9903 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9904 asDerived().visitArray(PDIK, AT, SL);
9905 return;
9906 }
9907
9908 Super::visitWithKind(PDIK, FT, SL);
9909 }
9910
9911 void visitARCStrong(QualType FT, SourceLocation SL) {
9912 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9913 }
9914 void visitARCWeak(QualType FT, SourceLocation SL) {
9915 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9916 }
9917 void visitStruct(QualType FT, SourceLocation SL) {
9918 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
9919 visit(FD->getType(), FD->getLocation());
9920 }
9921 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9922 const ArrayType *AT, SourceLocation SL) {
9923 visit(getContext().getBaseElementType(AT), SL);
9924 }
9925 void visitTrivial(QualType FT, SourceLocation SL) {}
9926
9927 static void diag(QualType RT, const Expr *E, Sema &S) {
9928 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9929 }
9930
9931 ASTContext &getContext() { return S.getASTContext(); }
9932
9933 const Expr *E;
9934 Sema &S;
9935};
9936
9937struct SearchNonTrivialToCopyField
9938 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9939 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9940
9941 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9942
9943 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9944 SourceLocation SL) {
9945 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9946 asDerived().visitArray(PCK, AT, SL);
9947 return;
9948 }
9949
9950 Super::visitWithKind(PCK, FT, SL);
9951 }
9952
9953 void visitARCStrong(QualType FT, SourceLocation SL) {
9954 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9955 }
9956 void visitARCWeak(QualType FT, SourceLocation SL) {
9957 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9958 }
9959 void visitPtrAuth(QualType FT, SourceLocation SL) {
9960 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9961 }
9962 void visitStruct(QualType FT, SourceLocation SL) {
9963 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
9964 visit(FD->getType(), FD->getLocation());
9965 }
9966 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9967 SourceLocation SL) {
9968 visit(getContext().getBaseElementType(AT), SL);
9969 }
9970 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9971 SourceLocation SL) {}
9972 void visitTrivial(QualType FT, SourceLocation SL) {}
9973 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9974
9975 static void diag(QualType RT, const Expr *E, Sema &S) {
9976 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9977 }
9978
9979 ASTContext &getContext() { return S.getASTContext(); }
9980
9981 const Expr *E;
9982 Sema &S;
9983};
9984
9985}
9986
9987/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9988static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9989 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9990
9991 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9992 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9993 return false;
9994
9995 return doesExprLikelyComputeSize(BO->getLHS()) ||
9996 doesExprLikelyComputeSize(BO->getRHS());
9997 }
9998
9999 return getAsSizeOfExpr(SizeofExpr) != nullptr;
10000}
10001
10002/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10003///
10004/// \code
10005/// #define MACRO 0
10006/// foo(MACRO);
10007/// foo(0);
10008/// \endcode
10009///
10010/// This should return true for the first call to foo, but not for the second
10011/// (regardless of whether foo is a macro or function).
10013 SourceLocation CallLoc,
10014 SourceLocation ArgLoc) {
10015 if (!CallLoc.isMacroID())
10016 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10017
10018 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10019 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10020}
10021
10022/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10023/// last two arguments transposed.
10024static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10025 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10026 return;
10027
10028 const Expr *SizeArg =
10029 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10030
10031 auto isLiteralZero = [](const Expr *E) {
10032 return (isa<IntegerLiteral>(E) &&
10033 cast<IntegerLiteral>(E)->getValue() == 0) ||
10035 cast<CharacterLiteral>(E)->getValue() == 0);
10036 };
10037
10038 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10039 SourceLocation CallLoc = Call->getRParenLoc();
10041 if (isLiteralZero(SizeArg) &&
10042 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10043
10044 SourceLocation DiagLoc = SizeArg->getExprLoc();
10045
10046 // Some platforms #define bzero to __builtin_memset. See if this is the
10047 // case, and if so, emit a better diagnostic.
10048 if (BId == Builtin::BIbzero ||
10050 CallLoc, SM, S.getLangOpts()) == "bzero")) {
10051 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10052 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10053 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10054 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10055 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10056 }
10057 return;
10058 }
10059
10060 // If the second argument to a memset is a sizeof expression and the third
10061 // isn't, this is also likely an error. This should catch
10062 // 'memset(buf, sizeof(buf), 0xff)'.
10063 if (BId == Builtin::BImemset &&
10064 doesExprLikelyComputeSize(Call->getArg(1)) &&
10065 !doesExprLikelyComputeSize(Call->getArg(2))) {
10066 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10067 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10068 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10069 return;
10070 }
10071}
10072
10073void Sema::CheckMemaccessArguments(const CallExpr *Call,
10074 unsigned BId,
10075 IdentifierInfo *FnName) {
10076 assert(BId != 0);
10077
10078 // It is possible to have a non-standard definition of memset. Validate
10079 // we have enough arguments, and if not, abort further checking.
10080 unsigned ExpectedNumArgs =
10081 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10082 if (Call->getNumArgs() < ExpectedNumArgs)
10083 return;
10084
10085 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10086 BId == Builtin::BIstrndup ? 1 : 2);
10087 unsigned LenArg =
10088 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10089 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10090
10091 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10092 Call->getBeginLoc(), Call->getRParenLoc()))
10093 return;
10094
10095 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10096 CheckMemaccessSize(*this, BId, Call);
10097
10098 // We have special checking when the length is a sizeof expression.
10099 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10100 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10101 llvm::FoldingSetNodeID SizeOfArgID;
10102
10103 // Although widely used, 'bzero' is not a standard function. Be more strict
10104 // with the argument types before allowing diagnostics and only allow the
10105 // form bzero(ptr, sizeof(...)).
10106 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10107 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10108 return;
10109
10110 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10111 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10112 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10113
10114 QualType DestTy = Dest->getType();
10115 QualType PointeeTy;
10116 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10117 PointeeTy = DestPtrTy->getPointeeType();
10118
10119 // Never warn about void type pointers. This can be used to suppress
10120 // false positives.
10121 if (PointeeTy->isVoidType())
10122 continue;
10123
10124 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10125 // actually comparing the expressions for equality. Because computing the
10126 // expression IDs can be expensive, we only do this if the diagnostic is
10127 // enabled.
10128 if (SizeOfArg &&
10129 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10130 SizeOfArg->getExprLoc())) {
10131 // We only compute IDs for expressions if the warning is enabled, and
10132 // cache the sizeof arg's ID.
10133 if (SizeOfArgID == llvm::FoldingSetNodeID())
10134 SizeOfArg->Profile(SizeOfArgID, Context, true);
10135 llvm::FoldingSetNodeID DestID;
10136 Dest->Profile(DestID, Context, true);
10137 if (DestID == SizeOfArgID) {
10138 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10139 // over sizeof(src) as well.
10140 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10141 StringRef ReadableName = FnName->getName();
10142
10143 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10144 if (UnaryOp->getOpcode() == UO_AddrOf)
10145 ActionIdx = 1; // If its an address-of operator, just remove it.
10146 if (!PointeeTy->isIncompleteType() &&
10147 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10148 ActionIdx = 2; // If the pointee's size is sizeof(char),
10149 // suggest an explicit length.
10150
10151 // If the function is defined as a builtin macro, do not show macro
10152 // expansion.
10153 SourceLocation SL = SizeOfArg->getExprLoc();
10154 SourceRange DSR = Dest->getSourceRange();
10155 SourceRange SSR = SizeOfArg->getSourceRange();
10156 SourceManager &SM = getSourceManager();
10157
10158 if (SM.isMacroArgExpansion(SL)) {
10159 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10160 SL = SM.getSpellingLoc(SL);
10161 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10162 SM.getSpellingLoc(DSR.getEnd()));
10163 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10164 SM.getSpellingLoc(SSR.getEnd()));
10165 }
10166
10167 DiagRuntimeBehavior(SL, SizeOfArg,
10168 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10169 << ReadableName
10170 << PointeeTy
10171 << DestTy
10172 << DSR
10173 << SSR);
10174 DiagRuntimeBehavior(SL, SizeOfArg,
10175 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10176 << ActionIdx
10177 << SSR);
10178
10179 break;
10180 }
10181 }
10182
10183 // Also check for cases where the sizeof argument is the exact same
10184 // type as the memory argument, and where it points to a user-defined
10185 // record type.
10186 if (SizeOfArgTy != QualType()) {
10187 if (PointeeTy->isRecordType() &&
10188 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10189 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10190 PDiag(diag::warn_sizeof_pointer_type_memaccess)
10191 << FnName << SizeOfArgTy << ArgIdx
10192 << PointeeTy << Dest->getSourceRange()
10193 << LenExpr->getSourceRange());
10194 break;
10195 }
10196 }
10197 } else if (DestTy->isArrayType()) {
10198 PointeeTy = DestTy;
10199 }
10200
10201 if (PointeeTy == QualType())
10202 continue;
10203
10204 // Always complain about dynamic classes.
10205 bool IsContained;
10206 if (const CXXRecordDecl *ContainedRD =
10207 getContainedDynamicClass(PointeeTy, IsContained)) {
10208
10209 unsigned OperationType = 0;
10210 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10211 // "overwritten" if we're warning about the destination for any call
10212 // but memcmp; otherwise a verb appropriate to the call.
10213 if (ArgIdx != 0 || IsCmp) {
10214 if (BId == Builtin::BImemcpy)
10215 OperationType = 1;
10216 else if(BId == Builtin::BImemmove)
10217 OperationType = 2;
10218 else if (IsCmp)
10219 OperationType = 3;
10220 }
10221
10222 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10223 PDiag(diag::warn_dyn_class_memaccess)
10224 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10225 << IsContained << ContainedRD << OperationType
10226 << Call->getCallee()->getSourceRange());
10227 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10228 BId != Builtin::BImemset)
10230 Dest->getExprLoc(), Dest,
10231 PDiag(diag::warn_arc_object_memaccess)
10232 << ArgIdx << FnName << PointeeTy
10233 << Call->getCallee()->getSourceRange());
10234 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
10235
10236 // FIXME: Do not consider incomplete types even though they may be
10237 // completed later. GCC does not diagnose such code, but we may want to
10238 // consider diagnosing it in the future, perhaps under a different, but
10239 // related, diagnostic group.
10240 bool NonTriviallyCopyableCXXRecord =
10241 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
10242 !PointeeTy.isTriviallyCopyableType(Context);
10243
10244 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10246 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10247 PDiag(diag::warn_cstruct_memaccess)
10248 << ArgIdx << FnName << PointeeTy << 0);
10249 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10250 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10251 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10252 // FIXME: Limiting this warning to dest argument until we decide
10253 // whether it's valid for source argument too.
10254 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10255 PDiag(diag::warn_cxxstruct_memaccess)
10256 << FnName << PointeeTy);
10257 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10259 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10260 PDiag(diag::warn_cstruct_memaccess)
10261 << ArgIdx << FnName << PointeeTy << 1);
10262 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10263 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10264 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10265 // FIXME: Limiting this warning to dest argument until we decide
10266 // whether it's valid for source argument too.
10267 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10268 PDiag(diag::warn_cxxstruct_memaccess)
10269 << FnName << PointeeTy);
10270 } else {
10271 continue;
10272 }
10273 } else
10274 continue;
10275
10277 Dest->getExprLoc(), Dest,
10278 PDiag(diag::note_bad_memaccess_silence)
10279 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10280 break;
10281 }
10282}
10283
10284// A little helper routine: ignore addition and subtraction of integer literals.
10285// This intentionally does not ignore all integer constant expressions because
10286// we don't want to remove sizeof().
10287static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10288 Ex = Ex->IgnoreParenCasts();
10289
10290 while (true) {
10291 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10292 if (!BO || !BO->isAdditiveOp())
10293 break;
10294
10295 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10296 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10297
10298 if (isa<IntegerLiteral>(RHS))
10299 Ex = LHS;
10300 else if (isa<IntegerLiteral>(LHS))
10301 Ex = RHS;
10302 else
10303 break;
10304 }
10305
10306 return Ex;
10307}
10308
10310 ASTContext &Context) {
10311 // Only handle constant-sized or VLAs, but not flexible members.
10312 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10313 // Only issue the FIXIT for arrays of size > 1.
10314 if (CAT->getZExtSize() <= 1)
10315 return false;
10316 } else if (!Ty->isVariableArrayType()) {
10317 return false;
10318 }
10319 return true;
10320}
10321
10322void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10323 IdentifierInfo *FnName) {
10324
10325 // Don't crash if the user has the wrong number of arguments
10326 unsigned NumArgs = Call->getNumArgs();
10327 if ((NumArgs != 3) && (NumArgs != 4))
10328 return;
10329
10330 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10331 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10332 const Expr *CompareWithSrc = nullptr;
10333
10334 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10335 Call->getBeginLoc(), Call->getRParenLoc()))
10336 return;
10337
10338 // Look for 'strlcpy(dst, x, sizeof(x))'
10339 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10340 CompareWithSrc = Ex;
10341 else {
10342 // Look for 'strlcpy(dst, x, strlen(x))'
10343 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10344 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10345 SizeCall->getNumArgs() == 1)
10346 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10347 }
10348 }
10349
10350 if (!CompareWithSrc)
10351 return;
10352
10353 // Determine if the argument to sizeof/strlen is equal to the source
10354 // argument. In principle there's all kinds of things you could do
10355 // here, for instance creating an == expression and evaluating it with
10356 // EvaluateAsBooleanCondition, but this uses a more direct technique:
10357 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10358 if (!SrcArgDRE)
10359 return;
10360
10361 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10362 if (!CompareWithSrcDRE ||
10363 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10364 return;
10365
10366 const Expr *OriginalSizeArg = Call->getArg(2);
10367 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10368 << OriginalSizeArg->getSourceRange() << FnName;
10369
10370 // Output a FIXIT hint if the destination is an array (rather than a
10371 // pointer to an array). This could be enhanced to handle some
10372 // pointers if we know the actual size, like if DstArg is 'array+2'
10373 // we could say 'sizeof(array)-2'.
10374 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10376 return;
10377
10378 SmallString<128> sizeString;
10379 llvm::raw_svector_ostream OS(sizeString);
10380 OS << "sizeof(";
10381 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10382 OS << ")";
10383
10384 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10385 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10386 OS.str());
10387}
10388
10389/// Check if two expressions refer to the same declaration.
10390static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10391 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10392 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10393 return D1->getDecl() == D2->getDecl();
10394 return false;
10395}
10396
10397static const Expr *getStrlenExprArg(const Expr *E) {
10398 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10399 const FunctionDecl *FD = CE->getDirectCallee();
10400 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10401 return nullptr;
10402 return CE->getArg(0)->IgnoreParenCasts();
10403 }
10404 return nullptr;
10405}
10406
10407void Sema::CheckStrncatArguments(const CallExpr *CE,
10408 const IdentifierInfo *FnName) {
10409 // Don't crash if the user has the wrong number of arguments.
10410 if (CE->getNumArgs() < 3)
10411 return;
10412 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10413 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10414 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10415
10416 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10417 CE->getRParenLoc()))
10418 return;
10419
10420 // Identify common expressions, which are wrongly used as the size argument
10421 // to strncat and may lead to buffer overflows.
10422 unsigned PatternType = 0;
10423 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10424 // - sizeof(dst)
10425 if (referToTheSameDecl(SizeOfArg, DstArg))
10426 PatternType = 1;
10427 // - sizeof(src)
10428 else if (referToTheSameDecl(SizeOfArg, SrcArg))
10429 PatternType = 2;
10430 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10431 if (BE->getOpcode() == BO_Sub) {
10432 const Expr *L = BE->getLHS()->IgnoreParenCasts();
10433 const Expr *R = BE->getRHS()->IgnoreParenCasts();
10434 // - sizeof(dst) - strlen(dst)
10435 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10437 PatternType = 1;
10438 // - sizeof(src) - (anything)
10439 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10440 PatternType = 2;
10441 }
10442 }
10443
10444 if (PatternType == 0)
10445 return;
10446
10447 // Generate the diagnostic.
10448 SourceLocation SL = LenArg->getBeginLoc();
10449 SourceRange SR = LenArg->getSourceRange();
10450 SourceManager &SM = getSourceManager();
10451
10452 // If the function is defined as a builtin macro, do not show macro expansion.
10453 if (SM.isMacroArgExpansion(SL)) {
10454 SL = SM.getSpellingLoc(SL);
10455 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10456 SM.getSpellingLoc(SR.getEnd()));
10457 }
10458
10459 // Check if the destination is an array (rather than a pointer to an array).
10460 QualType DstTy = DstArg->getType();
10461 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10462 Context);
10463 if (!isKnownSizeArray) {
10464 if (PatternType == 1)
10465 Diag(SL, diag::warn_strncat_wrong_size) << SR;
10466 else
10467 Diag(SL, diag::warn_strncat_src_size) << SR;
10468 return;
10469 }
10470
10471 if (PatternType == 1)
10472 Diag(SL, diag::warn_strncat_large_size) << SR;
10473 else
10474 Diag(SL, diag::warn_strncat_src_size) << SR;
10475
10476 SmallString<128> sizeString;
10477 llvm::raw_svector_ostream OS(sizeString);
10478 OS << "sizeof(";
10479 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10480 OS << ") - ";
10481 OS << "strlen(";
10482 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10483 OS << ") - 1";
10484
10485 Diag(SL, diag::note_strncat_wrong_size)
10486 << FixItHint::CreateReplacement(SR, OS.str());
10487}
10488
10489namespace {
10490void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10491 const UnaryOperator *UnaryExpr, const Decl *D) {
10493 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10494 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10495 return;
10496 }
10497}
10498
10499void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10500 const UnaryOperator *UnaryExpr) {
10501 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10502 const Decl *D = Lvalue->getDecl();
10503 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
10504 if (!DD->getType()->isReferenceType())
10505 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10506 }
10507 }
10508
10509 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10510 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10511 Lvalue->getMemberDecl());
10512}
10513
10514void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10515 const UnaryOperator *UnaryExpr) {
10516 const auto *Lambda = dyn_cast<LambdaExpr>(
10518 if (!Lambda)
10519 return;
10520
10521 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10522 << CalleeName << 2 /*object: lambda expression*/;
10523}
10524
10525void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10526 const DeclRefExpr *Lvalue) {
10527 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10528 if (Var == nullptr)
10529 return;
10530
10531 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10532 << CalleeName << 0 /*object: */ << Var;
10533}
10534
10535void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10536 const CastExpr *Cast) {
10537 SmallString<128> SizeString;
10538 llvm::raw_svector_ostream OS(SizeString);
10539
10540 clang::CastKind Kind = Cast->getCastKind();
10541 if (Kind == clang::CK_BitCast &&
10542 !Cast->getSubExpr()->getType()->isFunctionPointerType())
10543 return;
10544 if (Kind == clang::CK_IntegralToPointer &&
10546 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10547 return;
10548
10549 switch (Cast->getCastKind()) {
10550 case clang::CK_BitCast:
10551 case clang::CK_IntegralToPointer:
10552 case clang::CK_FunctionToPointerDecay:
10553 OS << '\'';
10554 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10555 OS << '\'';
10556 break;
10557 default:
10558 return;
10559 }
10560
10561 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10562 << CalleeName << 0 /*object: */ << OS.str();
10563}
10564} // namespace
10565
10566void Sema::CheckFreeArguments(const CallExpr *E) {
10567 const std::string CalleeName =
10568 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10569
10570 { // Prefer something that doesn't involve a cast to make things simpler.
10571 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10572 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10573 switch (UnaryExpr->getOpcode()) {
10574 case UnaryOperator::Opcode::UO_AddrOf:
10575 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10576 case UnaryOperator::Opcode::UO_Plus:
10577 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10578 default:
10579 break;
10580 }
10581
10582 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10583 if (Lvalue->getType()->isArrayType())
10584 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10585
10586 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10587 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10588 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10589 return;
10590 }
10591
10592 if (isa<BlockExpr>(Arg)) {
10593 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10594 << CalleeName << 1 /*object: block*/;
10595 return;
10596 }
10597 }
10598 // Maybe the cast was important, check after the other cases.
10599 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10600 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10601}
10602
10603void
10604Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10605 SourceLocation ReturnLoc,
10606 bool isObjCMethod,
10607 const AttrVec *Attrs,
10608 const FunctionDecl *FD) {
10609 // Check if the return value is null but should not be.
10610 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10611 (!isObjCMethod && isNonNullType(lhsType))) &&
10612 CheckNonNullExpr(*this, RetValExp))
10613 Diag(ReturnLoc, diag::warn_null_ret)
10614 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10615
10616 // C++11 [basic.stc.dynamic.allocation]p4:
10617 // If an allocation function declared with a non-throwing
10618 // exception-specification fails to allocate storage, it shall return
10619 // a null pointer. Any other allocation function that fails to allocate
10620 // storage shall indicate failure only by throwing an exception [...]
10621 if (FD) {
10623 if (Op == OO_New || Op == OO_Array_New) {
10624 const FunctionProtoType *Proto
10625 = FD->getType()->castAs<FunctionProtoType>();
10626 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10627 CheckNonNullExpr(*this, RetValExp))
10628 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10629 << FD << getLangOpts().CPlusPlus11;
10630 }
10631 }
10632
10633 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
10634 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
10635 }
10636
10637 // PPC MMA non-pointer types are not allowed as return type. Checking the type
10638 // here prevent the user from using a PPC MMA type as trailing return type.
10639 if (Context.getTargetInfo().getTriple().isPPC64())
10640 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10641}
10642
10644 const Expr *RHS, BinaryOperatorKind Opcode) {
10645 if (!BinaryOperator::isEqualityOp(Opcode))
10646 return;
10647
10648 // Match and capture subexpressions such as "(float) X == 0.1".
10649 const FloatingLiteral *FPLiteral;
10650 const CastExpr *FPCast;
10651 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
10652 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
10653 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
10654 return FPLiteral && FPCast;
10655 };
10656
10657 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
10658 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
10659 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
10660 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
10661 TargetTy->isFloatingPoint()) {
10662 bool Lossy;
10663 llvm::APFloat TargetC = FPLiteral->getValue();
10664 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
10665 llvm::APFloat::rmNearestTiesToEven, &Lossy);
10666 if (Lossy) {
10667 // If the literal cannot be represented in the source type, then a
10668 // check for == is always false and check for != is always true.
10669 Diag(Loc, diag::warn_float_compare_literal)
10670 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
10671 << LHS->getSourceRange() << RHS->getSourceRange();
10672 return;
10673 }
10674 }
10675 }
10676
10677 // Match a more general floating-point equality comparison (-Wfloat-equal).
10678 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
10679 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
10680
10681 // Special case: check for x == x (which is OK).
10682 // Do not emit warnings for such cases.
10683 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10684 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10685 if (DRL->getDecl() == DRR->getDecl())
10686 return;
10687
10688 // Special case: check for comparisons against literals that can be exactly
10689 // represented by APFloat. In such cases, do not emit a warning. This
10690 // is a heuristic: often comparison against such literals are used to
10691 // detect if a value in a variable has not changed. This clearly can
10692 // lead to false negatives.
10693 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10694 if (FLL->isExact())
10695 return;
10696 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10697 if (FLR->isExact())
10698 return;
10699
10700 // Check for comparisons with builtin types.
10701 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
10702 CL && CL->getBuiltinCallee())
10703 return;
10704
10705 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
10706 CR && CR->getBuiltinCallee())
10707 return;
10708
10709 // Emit the diagnostic.
10710 Diag(Loc, diag::warn_floatingpoint_eq)
10711 << LHS->getSourceRange() << RHS->getSourceRange();
10712}
10713
10714//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10715//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10716
10717namespace {
10718
10719/// Structure recording the 'active' range of an integer-valued
10720/// expression.
10721struct IntRange {
10722 /// The number of bits active in the int. Note that this includes exactly one
10723 /// sign bit if !NonNegative.
10724 unsigned Width;
10725
10726 /// True if the int is known not to have negative values. If so, all leading
10727 /// bits before Width are known zero, otherwise they are known to be the
10728 /// same as the MSB within Width.
10729 bool NonNegative;
10730
10731 IntRange(unsigned Width, bool NonNegative)
10732 : Width(Width), NonNegative(NonNegative) {}
10733
10734 /// Number of bits excluding the sign bit.
10735 unsigned valueBits() const {
10736 return NonNegative ? Width : Width - 1;
10737 }
10738
10739 /// Returns the range of the bool type.
10740 static IntRange forBoolType() {
10741 return IntRange(1, true);
10742 }
10743
10744 /// Returns the range of an opaque value of the given integral type.
10745 static IntRange forValueOfType(ASTContext &C, QualType T) {
10746 return forValueOfCanonicalType(C,
10748 }
10749
10750 /// Returns the range of an opaque value of a canonical integral type.
10751 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10752 assert(T->isCanonicalUnqualified());
10753
10754 if (const auto *VT = dyn_cast<VectorType>(T))
10755 T = VT->getElementType().getTypePtr();
10756 if (const auto *CT = dyn_cast<ComplexType>(T))
10757 T = CT->getElementType().getTypePtr();
10758 if (const auto *AT = dyn_cast<AtomicType>(T))
10759 T = AT->getValueType().getTypePtr();
10760
10761 if (!C.getLangOpts().CPlusPlus) {
10762 // For enum types in C code, use the underlying datatype.
10763 if (const auto *ED = T->getAsEnumDecl())
10764 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
10765 } else if (auto *Enum = T->getAsEnumDecl()) {
10766 // For enum types in C++, use the known bit width of the enumerators.
10767 // In C++11, enums can have a fixed underlying type. Use this type to
10768 // compute the range.
10769 if (Enum->isFixed()) {
10770 return IntRange(C.getIntWidth(QualType(T, 0)),
10771 !Enum->getIntegerType()->isSignedIntegerType());
10772 }
10773
10774 unsigned NumPositive = Enum->getNumPositiveBits();
10775 unsigned NumNegative = Enum->getNumNegativeBits();
10776
10777 if (NumNegative == 0)
10778 return IntRange(NumPositive, true/*NonNegative*/);
10779 else
10780 return IntRange(std::max(NumPositive + 1, NumNegative),
10781 false/*NonNegative*/);
10782 }
10783
10784 if (const auto *EIT = dyn_cast<BitIntType>(T))
10785 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10786
10787 const BuiltinType *BT = cast<BuiltinType>(T);
10788 assert(BT->isInteger());
10789
10790 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10791 }
10792
10793 /// Returns the "target" range of a canonical integral type, i.e.
10794 /// the range of values expressible in the type.
10795 ///
10796 /// This matches forValueOfCanonicalType except that enums have the
10797 /// full range of their type, not the range of their enumerators.
10798 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10799 assert(T->isCanonicalUnqualified());
10800
10801 if (const VectorType *VT = dyn_cast<VectorType>(T))
10802 T = VT->getElementType().getTypePtr();
10803 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10804 T = CT->getElementType().getTypePtr();
10805 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10806 T = AT->getValueType().getTypePtr();
10807 if (const auto *ED = T->getAsEnumDecl())
10808 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
10809
10810 if (const auto *EIT = dyn_cast<BitIntType>(T))
10811 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10812
10813 const BuiltinType *BT = cast<BuiltinType>(T);
10814 assert(BT->isInteger());
10815
10816 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10817 }
10818
10819 /// Returns the supremum of two ranges: i.e. their conservative merge.
10820 static IntRange join(IntRange L, IntRange R) {
10821 bool Unsigned = L.NonNegative && R.NonNegative;
10822 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10823 L.NonNegative && R.NonNegative);
10824 }
10825
10826 /// Return the range of a bitwise-AND of the two ranges.
10827 static IntRange bit_and(IntRange L, IntRange R) {
10828 unsigned Bits = std::max(L.Width, R.Width);
10829 bool NonNegative = false;
10830 if (L.NonNegative) {
10831 Bits = std::min(Bits, L.Width);
10832 NonNegative = true;
10833 }
10834 if (R.NonNegative) {
10835 Bits = std::min(Bits, R.Width);
10836 NonNegative = true;
10837 }
10838 return IntRange(Bits, NonNegative);
10839 }
10840
10841 /// Return the range of a sum of the two ranges.
10842 static IntRange sum(IntRange L, IntRange R) {
10843 bool Unsigned = L.NonNegative && R.NonNegative;
10844 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10845 Unsigned);
10846 }
10847
10848 /// Return the range of a difference of the two ranges.
10849 static IntRange difference(IntRange L, IntRange R) {
10850 // We need a 1-bit-wider range if:
10851 // 1) LHS can be negative: least value can be reduced.
10852 // 2) RHS can be negative: greatest value can be increased.
10853 bool CanWiden = !L.NonNegative || !R.NonNegative;
10854 bool Unsigned = L.NonNegative && R.Width == 0;
10855 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10856 !Unsigned,
10857 Unsigned);
10858 }
10859
10860 /// Return the range of a product of the two ranges.
10861 static IntRange product(IntRange L, IntRange R) {
10862 // If both LHS and RHS can be negative, we can form
10863 // -2^L * -2^R = 2^(L + R)
10864 // which requires L + R + 1 value bits to represent.
10865 bool CanWiden = !L.NonNegative && !R.NonNegative;
10866 bool Unsigned = L.NonNegative && R.NonNegative;
10867 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10868 Unsigned);
10869 }
10870
10871 /// Return the range of a remainder operation between the two ranges.
10872 static IntRange rem(IntRange L, IntRange R) {
10873 // The result of a remainder can't be larger than the result of
10874 // either side. The sign of the result is the sign of the LHS.
10875 bool Unsigned = L.NonNegative;
10876 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10877 Unsigned);
10878 }
10879};
10880
10881} // namespace
10882
10883static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
10884 if (value.isSigned() && value.isNegative())
10885 return IntRange(value.getSignificantBits(), false);
10886
10887 if (value.getBitWidth() > MaxWidth)
10888 value = value.trunc(MaxWidth);
10889
10890 // isNonNegative() just checks the sign bit without considering
10891 // signedness.
10892 return IntRange(value.getActiveBits(), true);
10893}
10894
10895static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
10896 if (result.isInt())
10897 return GetValueRange(result.getInt(), MaxWidth);
10898
10899 if (result.isVector()) {
10900 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
10901 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10902 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
10903 R = IntRange::join(R, El);
10904 }
10905 return R;
10906 }
10907
10908 if (result.isComplexInt()) {
10909 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
10910 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
10911 return IntRange::join(R, I);
10912 }
10913
10914 // This can happen with lossless casts to intptr_t of "based" lvalues.
10915 // Assume it might use arbitrary bits.
10916 // FIXME: The only reason we need to pass the type in here is to get
10917 // the sign right on this one case. It would be nice if APValue
10918 // preserved this.
10919 assert(result.isLValue() || result.isAddrLabelDiff());
10920 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10921}
10922
10923static QualType GetExprType(const Expr *E) {
10924 QualType Ty = E->getType();
10925 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
10926 Ty = AtomicRHS->getValueType();
10927 return Ty;
10928}
10929
10930/// Attempts to estimate an approximate range for the given integer expression.
10931/// Returns a range if successful, otherwise it returns \c std::nullopt if a
10932/// reliable estimation cannot be determined.
10933///
10934/// \param MaxWidth The width to which the value will be truncated.
10935/// \param InConstantContext If \c true, interpret the expression within a
10936/// constant context.
10937/// \param Approximate If \c true, provide a likely range of values by assuming
10938/// that arithmetic on narrower types remains within those types.
10939/// If \c false, return a range that includes all possible values
10940/// resulting from the expression.
10941/// \returns A range of values that the expression might take, or
10942/// std::nullopt if a reliable estimation cannot be determined.
10943static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
10944 unsigned MaxWidth,
10945 bool InConstantContext,
10946 bool Approximate) {
10947 E = E->IgnoreParens();
10948
10949 // Try a full evaluation first.
10950 Expr::EvalResult result;
10951 if (E->EvaluateAsRValue(result, C, InConstantContext))
10952 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
10953
10954 // I think we only want to look through implicit casts here; if the
10955 // user has an explicit widening cast, we should treat the value as
10956 // being of the new, wider type.
10957 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10958 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10959 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
10960 Approximate);
10961
10962 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10963
10964 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10965 CE->getCastKind() == CK_BooleanToSignedIntegral;
10966
10967 // Assume that non-integer casts can span the full range of the type.
10968 if (!isIntegerCast)
10969 return OutputTypeRange;
10970
10971 std::optional<IntRange> SubRange = TryGetExprRange(
10972 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
10973 InConstantContext, Approximate);
10974 if (!SubRange)
10975 return std::nullopt;
10976
10977 // Bail out if the subexpr's range is as wide as the cast type.
10978 if (SubRange->Width >= OutputTypeRange.Width)
10979 return OutputTypeRange;
10980
10981 // Otherwise, we take the smaller width, and we're non-negative if
10982 // either the output type or the subexpr is.
10983 return IntRange(SubRange->Width,
10984 SubRange->NonNegative || OutputTypeRange.NonNegative);
10985 }
10986
10987 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10988 // If we can fold the condition, just take that operand.
10989 bool CondResult;
10990 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10991 return TryGetExprRange(
10992 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
10993 InConstantContext, Approximate);
10994
10995 // Otherwise, conservatively merge.
10996 // TryGetExprRange requires an integer expression, but a throw expression
10997 // results in a void type.
10998 Expr *TrueExpr = CO->getTrueExpr();
10999 if (TrueExpr->getType()->isVoidType())
11000 return std::nullopt;
11001
11002 std::optional<IntRange> L =
11003 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
11004 if (!L)
11005 return std::nullopt;
11006
11007 Expr *FalseExpr = CO->getFalseExpr();
11008 if (FalseExpr->getType()->isVoidType())
11009 return std::nullopt;
11010
11011 std::optional<IntRange> R =
11012 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
11013 if (!R)
11014 return std::nullopt;
11015
11016 return IntRange::join(*L, *R);
11017 }
11018
11019 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11020 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11021
11022 switch (BO->getOpcode()) {
11023 case BO_Cmp:
11024 llvm_unreachable("builtin <=> should have class type");
11025
11026 // Boolean-valued operations are single-bit and positive.
11027 case BO_LAnd:
11028 case BO_LOr:
11029 case BO_LT:
11030 case BO_GT:
11031 case BO_LE:
11032 case BO_GE:
11033 case BO_EQ:
11034 case BO_NE:
11035 return IntRange::forBoolType();
11036
11037 // The type of the assignments is the type of the LHS, so the RHS
11038 // is not necessarily the same type.
11039 case BO_MulAssign:
11040 case BO_DivAssign:
11041 case BO_RemAssign:
11042 case BO_AddAssign:
11043 case BO_SubAssign:
11044 case BO_XorAssign:
11045 case BO_OrAssign:
11046 // TODO: bitfields?
11047 return IntRange::forValueOfType(C, GetExprType(E));
11048
11049 // Simple assignments just pass through the RHS, which will have
11050 // been coerced to the LHS type.
11051 case BO_Assign:
11052 // TODO: bitfields?
11053 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11054 Approximate);
11055
11056 // Operations with opaque sources are black-listed.
11057 case BO_PtrMemD:
11058 case BO_PtrMemI:
11059 return IntRange::forValueOfType(C, GetExprType(E));
11060
11061 // Bitwise-and uses the *infinum* of the two source ranges.
11062 case BO_And:
11063 case BO_AndAssign:
11064 Combine = IntRange::bit_and;
11065 break;
11066
11067 // Left shift gets black-listed based on a judgement call.
11068 case BO_Shl:
11069 // ...except that we want to treat '1 << (blah)' as logically
11070 // positive. It's an important idiom.
11071 if (IntegerLiteral *I
11072 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11073 if (I->getValue() == 1) {
11074 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11075 return IntRange(R.Width, /*NonNegative*/ true);
11076 }
11077 }
11078 [[fallthrough]];
11079
11080 case BO_ShlAssign:
11081 return IntRange::forValueOfType(C, GetExprType(E));
11082
11083 // Right shift by a constant can narrow its left argument.
11084 case BO_Shr:
11085 case BO_ShrAssign: {
11086 std::optional<IntRange> L = TryGetExprRange(
11087 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
11088 if (!L)
11089 return std::nullopt;
11090
11091 // If the shift amount is a positive constant, drop the width by
11092 // that much.
11093 if (std::optional<llvm::APSInt> shift =
11094 BO->getRHS()->getIntegerConstantExpr(C)) {
11095 if (shift->isNonNegative()) {
11096 if (shift->uge(L->Width))
11097 L->Width = (L->NonNegative ? 0 : 1);
11098 else
11099 L->Width -= shift->getZExtValue();
11100 }
11101 }
11102
11103 return L;
11104 }
11105
11106 // Comma acts as its right operand.
11107 case BO_Comma:
11108 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11109 Approximate);
11110
11111 case BO_Add:
11112 if (!Approximate)
11113 Combine = IntRange::sum;
11114 break;
11115
11116 case BO_Sub:
11117 if (BO->getLHS()->getType()->isPointerType())
11118 return IntRange::forValueOfType(C, GetExprType(E));
11119 if (!Approximate)
11120 Combine = IntRange::difference;
11121 break;
11122
11123 case BO_Mul:
11124 if (!Approximate)
11125 Combine = IntRange::product;
11126 break;
11127
11128 // The width of a division result is mostly determined by the size
11129 // of the LHS.
11130 case BO_Div: {
11131 // Don't 'pre-truncate' the operands.
11132 unsigned opWidth = C.getIntWidth(GetExprType(E));
11133 std::optional<IntRange> L = TryGetExprRange(
11134 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11135 if (!L)
11136 return std::nullopt;
11137
11138 // If the divisor is constant, use that.
11139 if (std::optional<llvm::APSInt> divisor =
11140 BO->getRHS()->getIntegerConstantExpr(C)) {
11141 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11142 if (log2 >= L->Width)
11143 L->Width = (L->NonNegative ? 0 : 1);
11144 else
11145 L->Width = std::min(L->Width - log2, MaxWidth);
11146 return L;
11147 }
11148
11149 // Otherwise, just use the LHS's width.
11150 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11151 // could be -1.
11152 std::optional<IntRange> R = TryGetExprRange(
11153 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11154 if (!R)
11155 return std::nullopt;
11156
11157 return IntRange(L->Width, L->NonNegative && R->NonNegative);
11158 }
11159
11160 case BO_Rem:
11161 Combine = IntRange::rem;
11162 break;
11163
11164 // The default behavior is okay for these.
11165 case BO_Xor:
11166 case BO_Or:
11167 break;
11168 }
11169
11170 // Combine the two ranges, but limit the result to the type in which we
11171 // performed the computation.
11172 QualType T = GetExprType(E);
11173 unsigned opWidth = C.getIntWidth(T);
11174 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
11175 InConstantContext, Approximate);
11176 if (!L)
11177 return std::nullopt;
11178
11179 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
11180 InConstantContext, Approximate);
11181 if (!R)
11182 return std::nullopt;
11183
11184 IntRange C = Combine(*L, *R);
11185 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11186 C.Width = std::min(C.Width, MaxWidth);
11187 return C;
11188 }
11189
11190 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11191 switch (UO->getOpcode()) {
11192 // Boolean-valued operations are white-listed.
11193 case UO_LNot:
11194 return IntRange::forBoolType();
11195
11196 // Operations with opaque sources are black-listed.
11197 case UO_Deref:
11198 case UO_AddrOf: // should be impossible
11199 return IntRange::forValueOfType(C, GetExprType(E));
11200
11201 case UO_Minus: {
11202 if (E->getType()->isUnsignedIntegerType()) {
11203 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11204 Approximate);
11205 }
11206
11207 std::optional<IntRange> SubRange = TryGetExprRange(
11208 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11209
11210 if (!SubRange)
11211 return std::nullopt;
11212
11213 // If the range was previously non-negative, we need an extra bit for the
11214 // sign bit. Otherwise, we need an extra bit because the negation of the
11215 // most-negative value is one bit wider than that value.
11216 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
11217 }
11218
11219 case UO_Not: {
11220 if (E->getType()->isUnsignedIntegerType()) {
11221 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11222 Approximate);
11223 }
11224
11225 std::optional<IntRange> SubRange = TryGetExprRange(
11226 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11227
11228 if (!SubRange)
11229 return std::nullopt;
11230
11231 // The width increments by 1 if the sub-expression cannot be negative
11232 // since it now can be.
11233 return IntRange(
11234 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
11235 false);
11236 }
11237
11238 default:
11239 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11240 Approximate);
11241 }
11242 }
11243
11244 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11245 return TryGetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11246 Approximate);
11247
11248 if (const auto *BitField = E->getSourceBitField())
11249 return IntRange(BitField->getBitWidthValue(),
11250 BitField->getType()->isUnsignedIntegerOrEnumerationType());
11251
11252 if (GetExprType(E)->isVoidType())
11253 return std::nullopt;
11254
11255 return IntRange::forValueOfType(C, GetExprType(E));
11256}
11257
11258static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11259 bool InConstantContext,
11260 bool Approximate) {
11261 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11262 Approximate);
11263}
11264
11265/// Checks whether the given value, which currently has the given
11266/// source semantics, has the same value when coerced through the
11267/// target semantics.
11268static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11269 const llvm::fltSemantics &Src,
11270 const llvm::fltSemantics &Tgt) {
11271 llvm::APFloat truncated = value;
11272
11273 bool ignored;
11274 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11275 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11276
11277 return truncated.bitwiseIsEqual(value);
11278}
11279
11280/// Checks whether the given value, which currently has the given
11281/// source semantics, has the same value when coerced through the
11282/// target semantics.
11283///
11284/// The value might be a vector of floats (or a complex number).
11285static bool IsSameFloatAfterCast(const APValue &value,
11286 const llvm::fltSemantics &Src,
11287 const llvm::fltSemantics &Tgt) {
11288 if (value.isFloat())
11289 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11290
11291 if (value.isVector()) {
11292 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11293 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11294 return false;
11295 return true;
11296 }
11297
11298 assert(value.isComplexFloat());
11299 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11300 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11301}
11302
11303static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11304 bool IsListInit = false);
11305
11306static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
11307 // Suppress cases where we are comparing against an enum constant.
11308 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11309 if (isa<EnumConstantDecl>(DR->getDecl()))
11310 return true;
11311
11312 // Suppress cases where the value is expanded from a macro, unless that macro
11313 // is how a language represents a boolean literal. This is the case in both C
11314 // and Objective-C.
11315 SourceLocation BeginLoc = E->getBeginLoc();
11316 if (BeginLoc.isMacroID()) {
11317 StringRef MacroName = Lexer::getImmediateMacroName(
11318 BeginLoc, S.getSourceManager(), S.getLangOpts());
11319 return MacroName != "YES" && MacroName != "NO" &&
11320 MacroName != "true" && MacroName != "false";
11321 }
11322
11323 return false;
11324}
11325
11326static bool isKnownToHaveUnsignedValue(const Expr *E) {
11327 return E->getType()->isIntegerType() &&
11328 (!E->getType()->isSignedIntegerType() ||
11330}
11331
11332namespace {
11333/// The promoted range of values of a type. In general this has the
11334/// following structure:
11335///
11336/// |-----------| . . . |-----------|
11337/// ^ ^ ^ ^
11338/// Min HoleMin HoleMax Max
11339///
11340/// ... where there is only a hole if a signed type is promoted to unsigned
11341/// (in which case Min and Max are the smallest and largest representable
11342/// values).
11343struct PromotedRange {
11344 // Min, or HoleMax if there is a hole.
11345 llvm::APSInt PromotedMin;
11346 // Max, or HoleMin if there is a hole.
11347 llvm::APSInt PromotedMax;
11348
11349 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11350 if (R.Width == 0)
11351 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11352 else if (R.Width >= BitWidth && !Unsigned) {
11353 // Promotion made the type *narrower*. This happens when promoting
11354 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11355 // Treat all values of 'signed int' as being in range for now.
11356 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11357 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11358 } else {
11359 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11360 .extOrTrunc(BitWidth);
11361 PromotedMin.setIsUnsigned(Unsigned);
11362
11363 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11364 .extOrTrunc(BitWidth);
11365 PromotedMax.setIsUnsigned(Unsigned);
11366 }
11367 }
11368
11369 // Determine whether this range is contiguous (has no hole).
11370 bool isContiguous() const { return PromotedMin <= PromotedMax; }
11371
11372 // Where a constant value is within the range.
11373 enum ComparisonResult {
11374 LT = 0x1,
11375 LE = 0x2,
11376 GT = 0x4,
11377 GE = 0x8,
11378 EQ = 0x10,
11379 NE = 0x20,
11380 InRangeFlag = 0x40,
11381
11382 Less = LE | LT | NE,
11383 Min = LE | InRangeFlag,
11384 InRange = InRangeFlag,
11385 Max = GE | InRangeFlag,
11386 Greater = GE | GT | NE,
11387
11388 OnlyValue = LE | GE | EQ | InRangeFlag,
11389 InHole = NE
11390 };
11391
11392 ComparisonResult compare(const llvm::APSInt &Value) const {
11393 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11394 Value.isUnsigned() == PromotedMin.isUnsigned());
11395 if (!isContiguous()) {
11396 assert(Value.isUnsigned() && "discontiguous range for signed compare");
11397 if (Value.isMinValue()) return Min;
11398 if (Value.isMaxValue()) return Max;
11399 if (Value >= PromotedMin) return InRange;
11400 if (Value <= PromotedMax) return InRange;
11401 return InHole;
11402 }
11403
11404 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11405 case -1: return Less;
11406 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11407 case 1:
11408 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11409 case -1: return InRange;
11410 case 0: return Max;
11411 case 1: return Greater;
11412 }
11413 }
11414
11415 llvm_unreachable("impossible compare result");
11416 }
11417
11418 static std::optional<StringRef>
11419 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11420 if (Op == BO_Cmp) {
11421 ComparisonResult LTFlag = LT, GTFlag = GT;
11422 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11423
11424 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11425 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11426 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11427 return std::nullopt;
11428 }
11429
11430 ComparisonResult TrueFlag, FalseFlag;
11431 if (Op == BO_EQ) {
11432 TrueFlag = EQ;
11433 FalseFlag = NE;
11434 } else if (Op == BO_NE) {
11435 TrueFlag = NE;
11436 FalseFlag = EQ;
11437 } else {
11438 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11439 TrueFlag = LT;
11440 FalseFlag = GE;
11441 } else {
11442 TrueFlag = GT;
11443 FalseFlag = LE;
11444 }
11445 if (Op == BO_GE || Op == BO_LE)
11446 std::swap(TrueFlag, FalseFlag);
11447 }
11448 if (R & TrueFlag)
11449 return StringRef("true");
11450 if (R & FalseFlag)
11451 return StringRef("false");
11452 return std::nullopt;
11453 }
11454};
11455}
11456
11457static bool HasEnumType(const Expr *E) {
11458 // Strip off implicit integral promotions.
11459 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11460 if (ICE->getCastKind() != CK_IntegralCast &&
11461 ICE->getCastKind() != CK_NoOp)
11462 break;
11463 E = ICE->getSubExpr();
11464 }
11465
11466 return E->getType()->isEnumeralType();
11467}
11468
11469static int classifyConstantValue(Expr *Constant) {
11470 // The values of this enumeration are used in the diagnostics
11471 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11472 enum ConstantValueKind {
11473 Miscellaneous = 0,
11474 LiteralTrue,
11475 LiteralFalse
11476 };
11477 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11478 return BL->getValue() ? ConstantValueKind::LiteralTrue
11479 : ConstantValueKind::LiteralFalse;
11480 return ConstantValueKind::Miscellaneous;
11481}
11482
11484 Expr *Constant, Expr *Other,
11485 const llvm::APSInt &Value,
11486 bool RhsConstant) {
11488 return false;
11489
11490 Expr *OriginalOther = Other;
11491
11492 Constant = Constant->IgnoreParenImpCasts();
11493 Other = Other->IgnoreParenImpCasts();
11494
11495 // Suppress warnings on tautological comparisons between values of the same
11496 // enumeration type. There are only two ways we could warn on this:
11497 // - If the constant is outside the range of representable values of
11498 // the enumeration. In such a case, we should warn about the cast
11499 // to enumeration type, not about the comparison.
11500 // - If the constant is the maximum / minimum in-range value. For an
11501 // enumeratin type, such comparisons can be meaningful and useful.
11502 if (Constant->getType()->isEnumeralType() &&
11503 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11504 return false;
11505
11506 std::optional<IntRange> OtherValueRange = TryGetExprRange(
11507 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
11508 if (!OtherValueRange)
11509 return false;
11510
11511 QualType OtherT = Other->getType();
11512 if (const auto *AT = OtherT->getAs<AtomicType>())
11513 OtherT = AT->getValueType();
11514 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11515
11516 // Special case for ObjC BOOL on targets where its a typedef for a signed char
11517 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11518 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11519 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
11520 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11521
11522 // Whether we're treating Other as being a bool because of the form of
11523 // expression despite it having another type (typically 'int' in C).
11524 bool OtherIsBooleanDespiteType =
11525 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11526 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11527 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
11528
11529 // Check if all values in the range of possible values of this expression
11530 // lead to the same comparison outcome.
11531 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
11532 Value.isUnsigned());
11533 auto Cmp = OtherPromotedValueRange.compare(Value);
11534 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11535 if (!Result)
11536 return false;
11537
11538 // Also consider the range determined by the type alone. This allows us to
11539 // classify the warning under the proper diagnostic group.
11540 bool TautologicalTypeCompare = false;
11541 {
11542 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11543 Value.isUnsigned());
11544 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11545 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11546 RhsConstant)) {
11547 TautologicalTypeCompare = true;
11548 Cmp = TypeCmp;
11549 Result = TypeResult;
11550 }
11551 }
11552
11553 // Don't warn if the non-constant operand actually always evaluates to the
11554 // same value.
11555 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
11556 return false;
11557
11558 // Suppress the diagnostic for an in-range comparison if the constant comes
11559 // from a macro or enumerator. We don't want to diagnose
11560 //
11561 // some_long_value <= INT_MAX
11562 //
11563 // when sizeof(int) == sizeof(long).
11564 bool InRange = Cmp & PromotedRange::InRangeFlag;
11565 if (InRange && IsEnumConstOrFromMacro(S, Constant))
11566 return false;
11567
11568 // A comparison of an unsigned bit-field against 0 is really a type problem,
11569 // even though at the type level the bit-field might promote to 'signed int'.
11570 if (Other->refersToBitField() && InRange && Value == 0 &&
11571 Other->getType()->isUnsignedIntegerOrEnumerationType())
11572 TautologicalTypeCompare = true;
11573
11574 // If this is a comparison to an enum constant, include that
11575 // constant in the diagnostic.
11576 const EnumConstantDecl *ED = nullptr;
11577 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
11578 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11579
11580 // Should be enough for uint128 (39 decimal digits)
11581 SmallString<64> PrettySourceValue;
11582 llvm::raw_svector_ostream OS(PrettySourceValue);
11583 if (ED) {
11584 OS << '\'' << *ED << "' (" << Value << ")";
11585 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11586 Constant->IgnoreParenImpCasts())) {
11587 OS << (BL->getValue() ? "YES" : "NO");
11588 } else {
11589 OS << Value;
11590 }
11591
11592 if (!TautologicalTypeCompare) {
11593 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11594 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
11595 << E->getOpcodeStr() << OS.str() << *Result
11596 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11597 return true;
11598 }
11599
11600 if (IsObjCSignedCharBool) {
11602 S.PDiag(diag::warn_tautological_compare_objc_bool)
11603 << OS.str() << *Result);
11604 return true;
11605 }
11606
11607 // FIXME: We use a somewhat different formatting for the in-range cases and
11608 // cases involving boolean values for historical reasons. We should pick a
11609 // consistent way of presenting these diagnostics.
11610 if (!InRange || Other->isKnownToHaveBooleanValue()) {
11611
11613 E->getOperatorLoc(), E,
11614 S.PDiag(!InRange ? diag::warn_out_of_range_compare
11615 : diag::warn_tautological_bool_compare)
11616 << OS.str() << classifyConstantValue(Constant) << OtherT
11617 << OtherIsBooleanDespiteType << *Result
11618 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11619 } else {
11620 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11621 unsigned Diag =
11622 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11623 ? (HasEnumType(OriginalOther)
11624 ? diag::warn_unsigned_enum_always_true_comparison
11625 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11626 : diag::warn_unsigned_always_true_comparison)
11627 : diag::warn_tautological_constant_compare;
11628
11629 S.Diag(E->getOperatorLoc(), Diag)
11630 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11631 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11632 }
11633
11634 return true;
11635}
11636
11637/// Analyze the operands of the given comparison. Implements the
11638/// fallback case from AnalyzeComparison.
11643
11644/// Implements -Wsign-compare.
11645///
11646/// \param E the binary operator to check for warnings
11648 // The type the comparison is being performed in.
11649 QualType T = E->getLHS()->getType();
11650
11651 // Only analyze comparison operators where both sides have been converted to
11652 // the same type.
11654 return AnalyzeImpConvsInComparison(S, E);
11655
11656 // Don't analyze value-dependent comparisons directly.
11657 if (E->isValueDependent())
11658 return AnalyzeImpConvsInComparison(S, E);
11659
11660 Expr *LHS = E->getLHS();
11661 Expr *RHS = E->getRHS();
11662
11663 if (T->isIntegralType(S.Context)) {
11664 std::optional<llvm::APSInt> RHSValue =
11666 std::optional<llvm::APSInt> LHSValue =
11668
11669 // We don't care about expressions whose result is a constant.
11670 if (RHSValue && LHSValue)
11671 return AnalyzeImpConvsInComparison(S, E);
11672
11673 // We only care about expressions where just one side is literal
11674 if ((bool)RHSValue ^ (bool)LHSValue) {
11675 // Is the constant on the RHS or LHS?
11676 const bool RhsConstant = (bool)RHSValue;
11677 Expr *Const = RhsConstant ? RHS : LHS;
11678 Expr *Other = RhsConstant ? LHS : RHS;
11679 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11680
11681 // Check whether an integer constant comparison results in a value
11682 // of 'true' or 'false'.
11683 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11684 return AnalyzeImpConvsInComparison(S, E);
11685 }
11686 }
11687
11688 if (!T->hasUnsignedIntegerRepresentation()) {
11689 // We don't do anything special if this isn't an unsigned integral
11690 // comparison: we're only interested in integral comparisons, and
11691 // signed comparisons only happen in cases we don't care to warn about.
11692 return AnalyzeImpConvsInComparison(S, E);
11693 }
11694
11695 LHS = LHS->IgnoreParenImpCasts();
11696 RHS = RHS->IgnoreParenImpCasts();
11697
11698 if (!S.getLangOpts().CPlusPlus) {
11699 // Avoid warning about comparison of integers with different signs when
11700 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11701 // the type of `E`.
11702 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11703 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11704 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11705 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11706 }
11707
11708 // Check to see if one of the (unmodified) operands is of different
11709 // signedness.
11710 Expr *signedOperand, *unsignedOperand;
11712 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11713 "unsigned comparison between two signed integer expressions?");
11714 signedOperand = LHS;
11715 unsignedOperand = RHS;
11716 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11717 signedOperand = RHS;
11718 unsignedOperand = LHS;
11719 } else {
11720 return AnalyzeImpConvsInComparison(S, E);
11721 }
11722
11723 // Otherwise, calculate the effective range of the signed operand.
11724 std::optional<IntRange> signedRange =
11726 /*Approximate=*/true);
11727 if (!signedRange)
11728 return;
11729
11730 // Go ahead and analyze implicit conversions in the operands. Note
11731 // that we skip the implicit conversions on both sides.
11734
11735 // If the signed range is non-negative, -Wsign-compare won't fire.
11736 if (signedRange->NonNegative)
11737 return;
11738
11739 // For (in)equality comparisons, if the unsigned operand is a
11740 // constant which cannot collide with a overflowed signed operand,
11741 // then reinterpreting the signed operand as unsigned will not
11742 // change the result of the comparison.
11743 if (E->isEqualityOp()) {
11744 unsigned comparisonWidth = S.Context.getIntWidth(T);
11745 std::optional<IntRange> unsignedRange = TryGetExprRange(
11746 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
11747 /*Approximate=*/true);
11748 if (!unsignedRange)
11749 return;
11750
11751 // We should never be unable to prove that the unsigned operand is
11752 // non-negative.
11753 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
11754
11755 if (unsignedRange->Width < comparisonWidth)
11756 return;
11757 }
11758
11760 S.PDiag(diag::warn_mixed_sign_comparison)
11761 << LHS->getType() << RHS->getType()
11762 << LHS->getSourceRange() << RHS->getSourceRange());
11763}
11764
11765/// Analyzes an attempt to assign the given value to a bitfield.
11766///
11767/// Returns true if there was something fishy about the attempt.
11769 SourceLocation InitLoc) {
11770 assert(Bitfield->isBitField());
11771 if (Bitfield->isInvalidDecl())
11772 return false;
11773
11774 // White-list bool bitfields.
11775 QualType BitfieldType = Bitfield->getType();
11776 if (BitfieldType->isBooleanType())
11777 return false;
11778
11779 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
11780 // If the underlying enum type was not explicitly specified as an unsigned
11781 // type and the enum contain only positive values, MSVC++ will cause an
11782 // inconsistency by storing this as a signed type.
11783 if (S.getLangOpts().CPlusPlus11 &&
11784 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11785 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11786 BitfieldEnumDecl->getNumNegativeBits() == 0) {
11787 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11788 << BitfieldEnumDecl;
11789 }
11790 }
11791
11792 // Ignore value- or type-dependent expressions.
11793 if (Bitfield->getBitWidth()->isValueDependent() ||
11794 Bitfield->getBitWidth()->isTypeDependent() ||
11795 Init->isValueDependent() ||
11796 Init->isTypeDependent())
11797 return false;
11798
11799 Expr *OriginalInit = Init->IgnoreParenImpCasts();
11800 unsigned FieldWidth = Bitfield->getBitWidthValue();
11801
11802 Expr::EvalResult Result;
11803 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11805 // The RHS is not constant. If the RHS has an enum type, make sure the
11806 // bitfield is wide enough to hold all the values of the enum without
11807 // truncation.
11808 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
11809 const PreferredTypeAttr *PTAttr = nullptr;
11810 if (!ED) {
11811 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
11812 if (PTAttr)
11813 ED = PTAttr->getType()->getAsEnumDecl();
11814 }
11815 if (ED) {
11816 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
11817
11818 // Enum types are implicitly signed on Windows, so check if there are any
11819 // negative enumerators to see if the enum was intended to be signed or
11820 // not.
11821 bool SignedEnum = ED->getNumNegativeBits() > 0;
11822
11823 // Check for surprising sign changes when assigning enum values to a
11824 // bitfield of different signedness. If the bitfield is signed and we
11825 // have exactly the right number of bits to store this unsigned enum,
11826 // suggest changing the enum to an unsigned type. This typically happens
11827 // on Windows where unfixed enums always use an underlying type of 'int'.
11828 unsigned DiagID = 0;
11829 if (SignedEnum && !SignedBitfield) {
11830 DiagID =
11831 PTAttr == nullptr
11832 ? diag::warn_unsigned_bitfield_assigned_signed_enum
11833 : diag::
11834 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
11835 } else if (SignedBitfield && !SignedEnum &&
11836 ED->getNumPositiveBits() == FieldWidth) {
11837 DiagID =
11838 PTAttr == nullptr
11839 ? diag::warn_signed_bitfield_enum_conversion
11840 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
11841 }
11842 if (DiagID) {
11843 S.Diag(InitLoc, DiagID) << Bitfield << ED;
11844 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11845 SourceRange TypeRange =
11846 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11847 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11848 << SignedEnum << TypeRange;
11849 if (PTAttr)
11850 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
11851 << ED;
11852 }
11853
11854 // Compute the required bitwidth. If the enum has negative values, we need
11855 // one more bit than the normal number of positive bits to represent the
11856 // sign bit.
11857 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11858 ED->getNumNegativeBits())
11859 : ED->getNumPositiveBits();
11860
11861 // Check the bitwidth.
11862 if (BitsNeeded > FieldWidth) {
11863 Expr *WidthExpr = Bitfield->getBitWidth();
11864 auto DiagID =
11865 PTAttr == nullptr
11866 ? diag::warn_bitfield_too_small_for_enum
11867 : diag::warn_preferred_type_bitfield_too_small_for_enum;
11868 S.Diag(InitLoc, DiagID) << Bitfield << ED;
11869 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11870 << BitsNeeded << ED << WidthExpr->getSourceRange();
11871 if (PTAttr)
11872 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
11873 << ED;
11874 }
11875 }
11876
11877 return false;
11878 }
11879
11880 llvm::APSInt Value = Result.Val.getInt();
11881
11882 unsigned OriginalWidth = Value.getBitWidth();
11883
11884 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
11885 // false positives where the user is demonstrating they intend to use the
11886 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
11887 // to a one-bit bit-field to see if the value came from a macro named 'true'.
11888 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
11889 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
11890 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
11891 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
11892 S.findMacroSpelling(MaybeMacroLoc, "true"))
11893 return false;
11894 }
11895
11896 if (!Value.isSigned() || Value.isNegative())
11897 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11898 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11899 OriginalWidth = Value.getSignificantBits();
11900
11901 if (OriginalWidth <= FieldWidth)
11902 return false;
11903
11904 // Compute the value which the bitfield will contain.
11905 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11906 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11907
11908 // Check whether the stored value is equal to the original value.
11909 TruncatedValue = TruncatedValue.extend(OriginalWidth);
11910 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11911 return false;
11912
11913 std::string PrettyValue = toString(Value, 10);
11914 std::string PrettyTrunc = toString(TruncatedValue, 10);
11915
11916 S.Diag(InitLoc, OneAssignedToOneBitBitfield
11917 ? diag::warn_impcast_single_bit_bitield_precision_constant
11918 : diag::warn_impcast_bitfield_precision_constant)
11919 << PrettyValue << PrettyTrunc << OriginalInit->getType()
11920 << Init->getSourceRange();
11921
11922 return true;
11923}
11924
11925/// Analyze the given simple or compound assignment for warning-worthy
11926/// operations.
11928 // Just recurse on the LHS.
11930
11931 // We want to recurse on the RHS as normal unless we're assigning to
11932 // a bitfield.
11933 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11934 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11935 E->getOperatorLoc())) {
11936 // Recurse, ignoring any implicit conversions on the RHS.
11938 E->getOperatorLoc());
11939 }
11940 }
11941
11943
11944 // Diagnose implicitly sequentially-consistent atomic assignment.
11945 if (E->getLHS()->getType()->isAtomicType())
11946 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11947}
11948
11949/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
11950static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
11951 QualType T, SourceLocation CContext, unsigned diag,
11952 bool PruneControlFlow = false) {
11953 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
11954 // address space annotations isn't really useful. The warnings aren't because
11955 // you're converting a `private int` to `unsigned int`, it is because you're
11956 // conerting `int` to `unsigned int`.
11957 if (SourceType.hasAddressSpace())
11958 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
11959 if (T.hasAddressSpace())
11961 if (PruneControlFlow) {
11963 S.PDiag(diag)
11964 << SourceType << T << E->getSourceRange()
11965 << SourceRange(CContext));
11966 return;
11967 }
11968 S.Diag(E->getExprLoc(), diag)
11969 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11970}
11971
11972/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
11973static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
11974 SourceLocation CContext, unsigned diag,
11975 bool PruneControlFlow = false) {
11976 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
11977}
11978
11979/// Diagnose an implicit cast from a floating point value to an integer value.
11980static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
11981 SourceLocation CContext) {
11982 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11983 bool PruneWarnings = S.inTemplateInstantiation();
11984
11985 const Expr *InnerE = E->IgnoreParenImpCasts();
11986 // We also want to warn on, e.g., "int i = -1.234"
11987 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
11988 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11989 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11990
11991 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11992
11993 llvm::APFloat Value(0.0);
11994 bool IsConstant =
11996 if (!IsConstant) {
11997 if (S.ObjC().isSignedCharBool(T)) {
11999 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12000 << E->getType());
12001 }
12002
12003 return DiagnoseImpCast(S, E, T, CContext,
12004 diag::warn_impcast_float_integer, PruneWarnings);
12005 }
12006
12007 bool isExact = false;
12008
12009 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12010 T->hasUnsignedIntegerRepresentation());
12011 llvm::APFloat::opStatus Result = Value.convertToInteger(
12012 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12013
12014 // FIXME: Force the precision of the source value down so we don't print
12015 // digits which are usually useless (we don't really care here if we
12016 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
12017 // would automatically print the shortest representation, but it's a bit
12018 // tricky to implement.
12019 SmallString<16> PrettySourceValue;
12020 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12021 precision = (precision * 59 + 195) / 196;
12022 Value.toString(PrettySourceValue, precision);
12023
12024 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
12026 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12027 << PrettySourceValue);
12028 }
12029
12030 if (Result == llvm::APFloat::opOK && isExact) {
12031 if (IsLiteral) return;
12032 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12033 PruneWarnings);
12034 }
12035
12036 // Conversion of a floating-point value to a non-bool integer where the
12037 // integral part cannot be represented by the integer type is undefined.
12038 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12039 return DiagnoseImpCast(
12040 S, E, T, CContext,
12041 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12042 : diag::warn_impcast_float_to_integer_out_of_range,
12043 PruneWarnings);
12044
12045 unsigned DiagID = 0;
12046 if (IsLiteral) {
12047 // Warn on floating point literal to integer.
12048 DiagID = diag::warn_impcast_literal_float_to_integer;
12049 } else if (IntegerValue == 0) {
12050 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
12051 return DiagnoseImpCast(S, E, T, CContext,
12052 diag::warn_impcast_float_integer, PruneWarnings);
12053 }
12054 // Warn on non-zero to zero conversion.
12055 DiagID = diag::warn_impcast_float_to_integer_zero;
12056 } else {
12057 if (IntegerValue.isUnsigned()) {
12058 if (!IntegerValue.isMaxValue()) {
12059 return DiagnoseImpCast(S, E, T, CContext,
12060 diag::warn_impcast_float_integer, PruneWarnings);
12061 }
12062 } else { // IntegerValue.isSigned()
12063 if (!IntegerValue.isMaxSignedValue() &&
12064 !IntegerValue.isMinSignedValue()) {
12065 return DiagnoseImpCast(S, E, T, CContext,
12066 diag::warn_impcast_float_integer, PruneWarnings);
12067 }
12068 }
12069 // Warn on evaluatable floating point expression to integer conversion.
12070 DiagID = diag::warn_impcast_float_to_integer;
12071 }
12072
12073 SmallString<16> PrettyTargetValue;
12074 if (IsBool)
12075 PrettyTargetValue = Value.isZero() ? "false" : "true";
12076 else
12077 IntegerValue.toString(PrettyTargetValue);
12078
12079 if (PruneWarnings) {
12081 S.PDiag(DiagID)
12082 << E->getType() << T.getUnqualifiedType()
12083 << PrettySourceValue << PrettyTargetValue
12084 << E->getSourceRange() << SourceRange(CContext));
12085 } else {
12086 S.Diag(E->getExprLoc(), DiagID)
12087 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12088 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12089 }
12090}
12091
12092/// Analyze the given compound assignment for the possible losing of
12093/// floating-point precision.
12095 assert(isa<CompoundAssignOperator>(E) &&
12096 "Must be compound assignment operation");
12097 // Recurse on the LHS and RHS in here
12100
12101 if (E->getLHS()->getType()->isAtomicType())
12102 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12103
12104 // Now check the outermost expression
12105 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12106 const auto *RBT = cast<CompoundAssignOperator>(E)
12107 ->getComputationResultType()
12108 ->getAs<BuiltinType>();
12109
12110 // The below checks assume source is floating point.
12111 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12112
12113 // If source is floating point but target is an integer.
12114 if (ResultBT->isInteger())
12115 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12116 E->getExprLoc(), diag::warn_impcast_float_integer);
12117
12118 if (!ResultBT->isFloatingPoint())
12119 return;
12120
12121 // If both source and target are floating points, warn about losing precision.
12123 QualType(ResultBT, 0), QualType(RBT, 0));
12124 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12125 // warn about dropping FP rank.
12126 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12127 diag::warn_impcast_float_result_precision);
12128}
12129
12130static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12131 IntRange Range) {
12132 if (!Range.Width) return "0";
12133
12134 llvm::APSInt ValueInRange = Value;
12135 ValueInRange.setIsSigned(!Range.NonNegative);
12136 ValueInRange = ValueInRange.trunc(Range.Width);
12137 return toString(ValueInRange, 10);
12138}
12139
12140static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
12141 bool ToBool) {
12142 if (!isa<ImplicitCastExpr>(Ex))
12143 return false;
12144
12145 const Expr *InnerE = Ex->IgnoreParenImpCasts();
12147 const Type *Source =
12149 if (Target->isDependentType())
12150 return false;
12151
12152 const auto *FloatCandidateBT =
12153 dyn_cast<BuiltinType>(ToBool ? Source : Target);
12154 const Type *BoolCandidateType = ToBool ? Target : Source;
12155
12156 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12157 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12158}
12159
12160static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
12161 SourceLocation CC) {
12162 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
12163 const Expr *CurrA = TheCall->getArg(I);
12164 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12165 continue;
12166
12167 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
12168 S, TheCall->getArg(I - 1), false));
12169 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
12170 S, TheCall->getArg(I + 1), false));
12171 if (IsSwapped) {
12172 // Warn on this floating-point to bool conversion.
12174 CurrA->getType(), CC,
12175 diag::warn_impcast_floating_point_to_bool);
12176 }
12177 }
12178}
12179
12181 SourceLocation CC) {
12182 // Don't warn on functions which have return type nullptr_t.
12183 if (isa<CallExpr>(E))
12184 return;
12185
12186 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12187 const Expr *NewE = E->IgnoreParenImpCasts();
12188 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
12189 bool HasNullPtrType = NewE->getType()->isNullPtrType();
12190 if (!IsGNUNullExpr && !HasNullPtrType)
12191 return;
12192
12193 // Return if target type is a safe conversion.
12194 if (T->isAnyPointerType() || T->isBlockPointerType() ||
12195 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12196 return;
12197
12198 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12199 E->getExprLoc()))
12200 return;
12201
12203
12204 // Venture through the macro stacks to get to the source of macro arguments.
12205 // The new location is a better location than the complete location that was
12206 // passed in.
12207 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12209
12210 // __null is usually wrapped in a macro. Go up a macro if that is the case.
12211 if (IsGNUNullExpr && Loc.isMacroID()) {
12212 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12213 Loc, S.SourceMgr, S.getLangOpts());
12214 if (MacroName == "NULL")
12216 }
12217
12218 // Only warn if the null and context location are in the same macro expansion.
12219 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12220 return;
12221
12222 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12223 << HasNullPtrType << T << SourceRange(CC)
12226}
12227
12228// Helper function to filter out cases for constant width constant conversion.
12229// Don't warn on char array initialization or for non-decimal values.
12231 SourceLocation CC) {
12232 // If initializing from a constant, and the constant starts with '0',
12233 // then it is a binary, octal, or hexadecimal. Allow these constants
12234 // to fill all the bits, even if there is a sign change.
12235 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12236 const char FirstLiteralCharacter =
12237 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12238 if (FirstLiteralCharacter == '0')
12239 return false;
12240 }
12241
12242 // If the CC location points to a '{', and the type is char, then assume
12243 // assume it is an array initialization.
12244 if (CC.isValid() && T->isCharType()) {
12245 const char FirstContextCharacter =
12247 if (FirstContextCharacter == '{')
12248 return false;
12249 }
12250
12251 return true;
12252}
12253
12255 const auto *IL = dyn_cast<IntegerLiteral>(E);
12256 if (!IL) {
12257 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12258 if (UO->getOpcode() == UO_Minus)
12259 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12260 }
12261 }
12262
12263 return IL;
12264}
12265
12267 E = E->IgnoreParenImpCasts();
12268 SourceLocation ExprLoc = E->getExprLoc();
12269
12270 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12271 BinaryOperator::Opcode Opc = BO->getOpcode();
12272 Expr::EvalResult Result;
12273 // Do not diagnose unsigned shifts.
12274 if (Opc == BO_Shl) {
12275 const auto *LHS = getIntegerLiteral(BO->getLHS());
12276 const auto *RHS = getIntegerLiteral(BO->getRHS());
12277 if (LHS && LHS->getValue() == 0)
12278 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12279 else if (!E->isValueDependent() && LHS && RHS &&
12280 RHS->getValue().isNonNegative() &&
12282 S.Diag(ExprLoc, diag::warn_left_shift_always)
12283 << (Result.Val.getInt() != 0);
12284 else if (E->getType()->isSignedIntegerType())
12285 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
12288 ") != 0");
12289 }
12290 }
12291
12292 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12293 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12294 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12295 if (!LHS || !RHS)
12296 return;
12297 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12298 (RHS->getValue() == 0 || RHS->getValue() == 1))
12299 // Do not diagnose common idioms.
12300 return;
12301 if (LHS->getValue() != 0 && RHS->getValue() != 0)
12302 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12303 }
12304}
12305
12307 const Type *Target, Expr *E,
12308 QualType T,
12309 SourceLocation CC) {
12310 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
12311 Source != Target);
12312
12313 // Lone surrogates have a distinct representation in UTF-32.
12314 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
12315 // so don't warn on such conversion.
12316 if (Source->isChar16Type() && Target->isChar32Type())
12317 return;
12318
12319 Expr::EvalResult Result;
12322 llvm::APSInt Value(32);
12323 Value = Result.Val.getInt();
12324 bool IsASCII = Value <= 0x7F;
12325 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
12326 bool ConversionPreservesSemantics =
12327 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
12328
12329 if (!ConversionPreservesSemantics) {
12330 auto IsSingleCodeUnitCP = [](const QualType &T,
12331 const llvm::APSInt &Value) {
12332 if (T->isChar8Type())
12333 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
12334 if (T->isChar16Type())
12335 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
12336 assert(T->isChar32Type());
12337 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
12338 };
12339
12340 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
12341 << E->getType() << T
12342 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
12343 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
12344 }
12345 } else {
12346 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
12348 DiagnoseImpCast(S, E, T, CC,
12349 LosesPrecision ? diag::warn_impcast_unicode_precision
12350 : diag::warn_impcast_unicode_char_type);
12351 }
12352}
12353
12359
12361 QualType To) {
12362 QualType MaybePointee = From->getPointeeType();
12363 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12364 From = MaybePointee;
12365 MaybePointee = To->getPointeeType();
12366 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12367 To = MaybePointee;
12368
12369 if (const auto *FromFn = From->getAs<FunctionType>()) {
12370 if (const auto *ToFn = To->getAs<FunctionType>()) {
12371 if (FromFn->getCFIUncheckedCalleeAttr() &&
12372 !ToFn->getCFIUncheckedCalleeAttr())
12373 return Discarding;
12374 if (!FromFn->getCFIUncheckedCalleeAttr() &&
12375 ToFn->getCFIUncheckedCalleeAttr())
12376 return Adding;
12377 }
12378 }
12379 return None;
12380}
12381
12383 From = Context.getCanonicalType(From);
12384 To = Context.getCanonicalType(To);
12385 return ::AdjustingCFIUncheckedCallee(From, To) == Discarding;
12386}
12387
12389 From = Context.getCanonicalType(From);
12390 To = Context.getCanonicalType(To);
12391 return ::AdjustingCFIUncheckedCallee(From, To) == Adding;
12392}
12393
12395 bool *ICContext, bool IsListInit) {
12396 if (E->isTypeDependent() || E->isValueDependent()) return;
12397
12398 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
12399 const Type *Target = Context.getCanonicalType(T).getTypePtr();
12400 if (Source == Target) return;
12401 if (Target->isDependentType()) return;
12402
12403 // If the conversion context location is invalid don't complain. We also
12404 // don't want to emit a warning if the issue occurs from the expansion of
12405 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12406 // delay this check as long as possible. Once we detect we are in that
12407 // scenario, we just return.
12408 if (CC.isInvalid())
12409 return;
12410
12411 if (Source->isAtomicType())
12412 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12413
12414 // Diagnose implicit casts to bool.
12415 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12416 if (isa<StringLiteral>(E))
12417 // Warn on string literal to bool. Checks for string literals in logical
12418 // and expressions, for instance, assert(0 && "error here"), are
12419 // prevented by a check in AnalyzeImplicitConversions().
12420 return DiagnoseImpCast(*this, E, T, CC,
12421 diag::warn_impcast_string_literal_to_bool);
12424 // This covers the literal expressions that evaluate to Objective-C
12425 // objects.
12426 return DiagnoseImpCast(*this, E, T, CC,
12427 diag::warn_impcast_objective_c_literal_to_bool);
12428 }
12429 if (Source->isPointerType() || Source->canDecayToPointerType()) {
12430 // Warn on pointer to bool conversion that is always true.
12432 SourceRange(CC));
12433 }
12434 }
12435
12436 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12437 // is a typedef for signed char (macOS), then that constant value has to be 1
12438 // or 0.
12439 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
12442 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12444 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12445 << toString(Result.Val.getInt(), 10));
12446 }
12447 return;
12448 }
12449 }
12450
12451 // Check implicit casts from Objective-C collection literals to specialized
12452 // collection types, e.g., NSArray<NSString *> *.
12453 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12454 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
12455 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12456 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
12457
12458 // Strip vector types.
12459 if (isa<VectorType>(Source)) {
12460 if (Target->isSveVLSBuiltinType() &&
12461 (ARM().areCompatibleSveTypes(QualType(Target, 0),
12462 QualType(Source, 0)) ||
12463 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
12464 QualType(Source, 0))))
12465 return;
12466
12467 if (Target->isRVVVLSBuiltinType() &&
12468 (Context.areCompatibleRVVTypes(QualType(Target, 0),
12469 QualType(Source, 0)) ||
12470 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
12471 QualType(Source, 0))))
12472 return;
12473
12474 if (!isa<VectorType>(Target)) {
12475 if (SourceMgr.isInSystemMacro(CC))
12476 return;
12477 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
12478 } else if (getLangOpts().HLSL &&
12479 Target->castAs<VectorType>()->getNumElements() <
12480 Source->castAs<VectorType>()->getNumElements()) {
12481 // Diagnose vector truncation but don't return. We may also want to
12482 // diagnose an element conversion.
12483 DiagnoseImpCast(*this, E, T, CC,
12484 diag::warn_hlsl_impcast_vector_truncation);
12485 }
12486
12487 // If the vector cast is cast between two vectors of the same size, it is
12488 // a bitcast, not a conversion, except under HLSL where it is a conversion.
12489 if (!getLangOpts().HLSL &&
12490 Context.getTypeSize(Source) == Context.getTypeSize(Target))
12491 return;
12492
12493 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12494 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12495 }
12496 if (auto VecTy = dyn_cast<VectorType>(Target))
12497 Target = VecTy->getElementType().getTypePtr();
12498
12499 // Strip complex types.
12500 if (isa<ComplexType>(Source)) {
12501 if (!isa<ComplexType>(Target)) {
12502 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12503 return;
12504
12505 return DiagnoseImpCast(*this, E, T, CC,
12507 ? diag::err_impcast_complex_scalar
12508 : diag::warn_impcast_complex_scalar);
12509 }
12510
12511 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12512 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12513 }
12514
12515 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12516 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12517
12518 // Strip SVE vector types
12519 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
12520 // Need the original target type for vector type checks
12521 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
12522 // Handle conversion from scalable to fixed when msve-vector-bits is
12523 // specified
12524 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
12525 QualType(Source, 0)) ||
12526 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
12527 QualType(Source, 0)))
12528 return;
12529
12530 // If the vector cast is cast between two vectors of the same size, it is
12531 // a bitcast, not a conversion.
12532 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
12533 return;
12534
12535 Source = SourceBT->getSveEltType(Context).getTypePtr();
12536 }
12537
12538 if (TargetBT && TargetBT->isSveVLSBuiltinType())
12539 Target = TargetBT->getSveEltType(Context).getTypePtr();
12540
12541 // If the source is floating point...
12542 if (SourceBT && SourceBT->isFloatingPoint()) {
12543 // ...and the target is floating point...
12544 if (TargetBT && TargetBT->isFloatingPoint()) {
12545 // ...then warn if we're dropping FP rank.
12546
12548 QualType(SourceBT, 0), QualType(TargetBT, 0));
12549 if (Order > 0) {
12550 // Don't warn about float constants that are precisely
12551 // representable in the target type.
12552 Expr::EvalResult result;
12553 if (E->EvaluateAsRValue(result, Context)) {
12554 // Value might be a float, a float vector, or a float complex.
12556 result.Val,
12557 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12558 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12559 return;
12560 }
12561
12562 if (SourceMgr.isInSystemMacro(CC))
12563 return;
12564
12565 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
12566 }
12567 // ... or possibly if we're increasing rank, too
12568 else if (Order < 0) {
12569 if (SourceMgr.isInSystemMacro(CC))
12570 return;
12571
12572 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
12573 }
12574 return;
12575 }
12576
12577 // If the target is integral, always warn.
12578 if (TargetBT && TargetBT->isInteger()) {
12579 if (SourceMgr.isInSystemMacro(CC))
12580 return;
12581
12582 DiagnoseFloatingImpCast(*this, E, T, CC);
12583 }
12584
12585 // Detect the case where a call result is converted from floating-point to
12586 // to bool, and the final argument to the call is converted from bool, to
12587 // discover this typo:
12588 //
12589 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
12590 //
12591 // FIXME: This is an incredibly special case; is there some more general
12592 // way to detect this class of misplaced-parentheses bug?
12593 if (Target->isBooleanType() && isa<CallExpr>(E)) {
12594 // Check last argument of function call to see if it is an
12595 // implicit cast from a type matching the type the result
12596 // is being cast to.
12597 CallExpr *CEx = cast<CallExpr>(E);
12598 if (unsigned NumArgs = CEx->getNumArgs()) {
12599 Expr *LastA = CEx->getArg(NumArgs - 1);
12600 Expr *InnerE = LastA->IgnoreParenImpCasts();
12601 if (isa<ImplicitCastExpr>(LastA) &&
12602 InnerE->getType()->isBooleanType()) {
12603 // Warn on this floating-point to bool conversion
12604 DiagnoseImpCast(*this, E, T, CC,
12605 diag::warn_impcast_floating_point_to_bool);
12606 }
12607 }
12608 }
12609 return;
12610 }
12611
12612 // Valid casts involving fixed point types should be accounted for here.
12613 if (Source->isFixedPointType()) {
12614 if (Target->isUnsaturatedFixedPointType()) {
12618 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12619 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
12620 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
12621 if (Value > MaxVal || Value < MinVal) {
12623 PDiag(diag::warn_impcast_fixed_point_range)
12624 << Value.toString() << T
12625 << E->getSourceRange()
12626 << clang::SourceRange(CC));
12627 return;
12628 }
12629 }
12630 } else if (Target->isIntegerType()) {
12634 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12635
12636 bool Overflowed;
12637 llvm::APSInt IntResult = FXResult.convertToInt(
12638 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
12639 &Overflowed);
12640
12641 if (Overflowed) {
12643 PDiag(diag::warn_impcast_fixed_point_range)
12644 << FXResult.toString() << T
12645 << E->getSourceRange()
12646 << clang::SourceRange(CC));
12647 return;
12648 }
12649 }
12650 }
12651 } else if (Target->isUnsaturatedFixedPointType()) {
12652 if (Source->isIntegerType()) {
12656 llvm::APSInt Value = Result.Val.getInt();
12657
12658 bool Overflowed;
12659 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12660 Value, Context.getFixedPointSemantics(T), &Overflowed);
12661
12662 if (Overflowed) {
12664 PDiag(diag::warn_impcast_fixed_point_range)
12665 << toString(Value, /*Radix=*/10) << T
12666 << E->getSourceRange()
12667 << clang::SourceRange(CC));
12668 return;
12669 }
12670 }
12671 }
12672 }
12673
12674 // If we are casting an integer type to a floating point type without
12675 // initialization-list syntax, we might lose accuracy if the floating
12676 // point type has a narrower significand than the integer type.
12677 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12678 TargetBT->isFloatingType() && !IsListInit) {
12679 // Determine the number of precision bits in the source integer type.
12680 std::optional<IntRange> SourceRange =
12682 /*Approximate=*/true);
12683 if (!SourceRange)
12684 return;
12685 unsigned int SourcePrecision = SourceRange->Width;
12686
12687 // Determine the number of precision bits in the
12688 // target floating point type.
12689 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12690 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12691
12692 if (SourcePrecision > 0 && TargetPrecision > 0 &&
12693 SourcePrecision > TargetPrecision) {
12694
12695 if (std::optional<llvm::APSInt> SourceInt =
12697 // If the source integer is a constant, convert it to the target
12698 // floating point type. Issue a warning if the value changes
12699 // during the whole conversion.
12700 llvm::APFloat TargetFloatValue(
12701 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12702 llvm::APFloat::opStatus ConversionStatus =
12703 TargetFloatValue.convertFromAPInt(
12704 *SourceInt, SourceBT->isSignedInteger(),
12705 llvm::APFloat::rmNearestTiesToEven);
12706
12707 if (ConversionStatus != llvm::APFloat::opOK) {
12708 SmallString<32> PrettySourceValue;
12709 SourceInt->toString(PrettySourceValue, 10);
12710 SmallString<32> PrettyTargetValue;
12711 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12712
12714 E->getExprLoc(), E,
12715 PDiag(diag::warn_impcast_integer_float_precision_constant)
12716 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12717 << E->getSourceRange() << clang::SourceRange(CC));
12718 }
12719 } else {
12720 // Otherwise, the implicit conversion may lose precision.
12721 DiagnoseImpCast(*this, E, T, CC,
12722 diag::warn_impcast_integer_float_precision);
12723 }
12724 }
12725 }
12726
12727 DiagnoseNullConversion(*this, E, T, CC);
12728
12730
12731 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
12732 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
12733 return;
12734 }
12735
12736 if (Target->isBooleanType())
12737 DiagnoseIntInBoolContext(*this, E);
12738
12740 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
12741 << QualType(Source, 0) << QualType(Target, 0);
12742 }
12743
12744 if (!Source->isIntegerType() || !Target->isIntegerType())
12745 return;
12746
12747 // TODO: remove this early return once the false positives for constant->bool
12748 // in templates, macros, etc, are reduced or removed.
12749 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12750 return;
12751
12752 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
12753 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12755 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12756 << E->getType());
12757 }
12758 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
12759 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
12760 if (!LikelySourceRange)
12761 return;
12762
12763 IntRange SourceTypeRange =
12764 IntRange::forTargetOfCanonicalType(Context, Source);
12765 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
12766
12767 if (LikelySourceRange->Width > TargetRange.Width) {
12768 // If the source is a constant, use a default-on diagnostic.
12769 // TODO: this should happen for bitfield stores, too.
12773 llvm::APSInt Value(32);
12774 Value = Result.Val.getInt();
12775
12776 if (SourceMgr.isInSystemMacro(CC))
12777 return;
12778
12779 std::string PrettySourceValue = toString(Value, 10);
12780 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12781
12783 PDiag(diag::warn_impcast_integer_precision_constant)
12784 << PrettySourceValue << PrettyTargetValue
12785 << E->getType() << T << E->getSourceRange()
12786 << SourceRange(CC));
12787 return;
12788 }
12789
12790 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12791 if (SourceMgr.isInSystemMacro(CC))
12792 return;
12793
12794 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
12795 if (UO->getOpcode() == UO_Minus)
12796 return DiagnoseImpCast(
12797 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
12798 }
12799
12800 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
12801 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
12802 /* pruneControlFlow */ true);
12803 return DiagnoseImpCast(*this, E, T, CC,
12804 diag::warn_impcast_integer_precision);
12805 }
12806
12807 if (TargetRange.Width > SourceTypeRange.Width) {
12808 if (auto *UO = dyn_cast<UnaryOperator>(E))
12809 if (UO->getOpcode() == UO_Minus)
12810 if (Source->isUnsignedIntegerType()) {
12811 if (Target->isUnsignedIntegerType())
12812 return DiagnoseImpCast(*this, E, T, CC,
12813 diag::warn_impcast_high_order_zero_bits);
12814 if (Target->isSignedIntegerType())
12815 return DiagnoseImpCast(*this, E, T, CC,
12816 diag::warn_impcast_nonnegative_result);
12817 }
12818 }
12819
12820 if (TargetRange.Width == LikelySourceRange->Width &&
12821 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
12822 Source->isSignedIntegerType()) {
12823 // Warn when doing a signed to signed conversion, warn if the positive
12824 // source value is exactly the width of the target type, which will
12825 // cause a negative value to be stored.
12826
12829 !SourceMgr.isInSystemMacro(CC)) {
12830 llvm::APSInt Value = Result.Val.getInt();
12831 if (isSameWidthConstantConversion(*this, E, T, CC)) {
12832 std::string PrettySourceValue = toString(Value, 10);
12833 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12834
12835 Diag(E->getExprLoc(),
12836 PDiag(diag::warn_impcast_integer_precision_constant)
12837 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12838 << E->getSourceRange() << SourceRange(CC));
12839 return;
12840 }
12841 }
12842
12843 // Fall through for non-constants to give a sign conversion warning.
12844 }
12845
12846 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
12847 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
12848 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
12849 LikelySourceRange->Width == TargetRange.Width))) {
12850 if (SourceMgr.isInSystemMacro(CC))
12851 return;
12852
12853 if (SourceBT && SourceBT->isInteger() && TargetBT &&
12854 TargetBT->isInteger() &&
12855 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
12856 return;
12857 }
12858
12859 unsigned DiagID = diag::warn_impcast_integer_sign;
12860
12861 // Traditionally, gcc has warned about this under -Wsign-compare.
12862 // We also want to warn about it in -Wconversion.
12863 // So if -Wconversion is off, use a completely identical diagnostic
12864 // in the sign-compare group.
12865 // The conditional-checking code will
12866 if (ICContext) {
12867 DiagID = diag::warn_impcast_integer_sign_conditional;
12868 *ICContext = true;
12869 }
12870
12871 DiagnoseImpCast(*this, E, T, CC, DiagID);
12872 }
12873
12874 // If we're implicitly converting from an integer into an enumeration, that
12875 // is valid in C but invalid in C++.
12876 QualType SourceType = E->getEnumCoercedType(Context);
12877 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
12878 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
12879 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
12880
12881 // Diagnose conversions between different enumeration types.
12882 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12883 // type, to give us better diagnostics.
12884 Source = Context.getCanonicalType(SourceType).getTypePtr();
12885
12886 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
12887 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
12888 if (SourceEnum->getDecl()->hasNameForLinkage() &&
12889 TargetEnum->getDecl()->hasNameForLinkage() &&
12890 SourceEnum != TargetEnum) {
12891 if (SourceMgr.isInSystemMacro(CC))
12892 return;
12893
12894 return DiagnoseImpCast(*this, E, SourceType, T, CC,
12895 diag::warn_impcast_different_enum_types);
12896 }
12897}
12898
12901
12903 SourceLocation CC, bool &ICContext) {
12904 E = E->IgnoreParenImpCasts();
12905 // Diagnose incomplete type for second or third operand in C.
12906 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
12907 S.RequireCompleteExprType(E, diag::err_incomplete_type);
12908
12909 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12910 return CheckConditionalOperator(S, CO, CC, T);
12911
12913 if (E->getType() != T)
12914 return S.CheckImplicitConversion(E, T, CC, &ICContext);
12915}
12916
12920
12921 Expr *TrueExpr = E->getTrueExpr();
12922 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12923 TrueExpr = BCO->getCommon();
12924
12925 bool Suspicious = false;
12926 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12927 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12928
12929 if (T->isBooleanType())
12931
12932 // If -Wconversion would have warned about either of the candidates
12933 // for a signedness conversion to the context type...
12934 if (!Suspicious) return;
12935
12936 // ...but it's currently ignored...
12937 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12938 return;
12939
12940 // ...then check whether it would have warned about either of the
12941 // candidates for a signedness conversion to the condition type.
12942 if (E->getType() == T) return;
12943
12944 Suspicious = false;
12945 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
12946 &Suspicious);
12947 if (!Suspicious)
12949 E->getType(), CC, &Suspicious);
12950}
12951
12952/// Check conversion of given expression to boolean.
12953/// Input argument E is a logical expression.
12955 // Run the bool-like conversion checks only for C since there bools are
12956 // still not used as the return type from "boolean" operators or as the input
12957 // type for conditional operators.
12958 if (S.getLangOpts().CPlusPlus)
12959 return;
12961 return;
12963}
12964
12965namespace {
12966struct AnalyzeImplicitConversionsWorkItem {
12967 Expr *E;
12968 SourceLocation CC;
12969 bool IsListInit;
12970};
12971}
12972
12974 Sema &S, Expr *E, QualType T, SourceLocation CC,
12975 bool ExtraCheckForImplicitConversion,
12977 E = E->IgnoreParenImpCasts();
12978 WorkList.push_back({E, CC, false});
12979
12980 if (ExtraCheckForImplicitConversion && E->getType() != T)
12981 S.CheckImplicitConversion(E, T, CC);
12982}
12983
12984/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12985/// that should be visited are added to WorkList.
12987 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12989 Expr *OrigE = Item.E;
12990 SourceLocation CC = Item.CC;
12991
12992 QualType T = OrigE->getType();
12993 Expr *E = OrigE->IgnoreParenImpCasts();
12994
12995 // Propagate whether we are in a C++ list initialization expression.
12996 // If so, we do not issue warnings for implicit int-float conversion
12997 // precision loss, because C++11 narrowing already handles it.
12998 //
12999 // HLSL's initialization lists are special, so they shouldn't observe the C++
13000 // behavior here.
13001 bool IsListInit =
13002 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
13003 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
13004
13005 if (E->isTypeDependent() || E->isValueDependent())
13006 return;
13007
13008 Expr *SourceExpr = E;
13009 // Examine, but don't traverse into the source expression of an
13010 // OpaqueValueExpr, since it may have multiple parents and we don't want to
13011 // emit duplicate diagnostics. Its fine to examine the form or attempt to
13012 // evaluate it in the context of checking the specific conversion to T though.
13013 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13014 if (auto *Src = OVE->getSourceExpr())
13015 SourceExpr = Src;
13016
13017 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13018 if (UO->getOpcode() == UO_Not &&
13019 UO->getSubExpr()->isKnownToHaveBooleanValue())
13020 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13021 << OrigE->getSourceRange() << T->isBooleanType()
13022 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13023
13024 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
13025 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13026 BO->getLHS()->isKnownToHaveBooleanValue() &&
13027 BO->getRHS()->isKnownToHaveBooleanValue() &&
13028 BO->getLHS()->HasSideEffects(S.Context) &&
13029 BO->getRHS()->HasSideEffects(S.Context)) {
13031 const LangOptions &LO = S.getLangOpts();
13032 SourceLocation BLoc = BO->getOperatorLoc();
13033 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
13034 StringRef SR = clang::Lexer::getSourceText(
13035 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
13036 // To reduce false positives, only issue the diagnostic if the operator
13037 // is explicitly spelled as a punctuator. This suppresses the diagnostic
13038 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
13039 // in C, along with other macro spellings the user might invent.
13040 if (SR.str() == "&" || SR.str() == "|") {
13041
13042 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13043 << (BO->getOpcode() == BO_And ? "&" : "|")
13044 << OrigE->getSourceRange()
13046 BO->getOperatorLoc(),
13047 (BO->getOpcode() == BO_And ? "&&" : "||"));
13048 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13049 }
13050 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
13051 /// Analyze the given comma operator. The basic idea behind the analysis
13052 /// is to analyze the left and right operands slightly differently. The
13053 /// left operand needs to check whether the operand itself has an implicit
13054 /// conversion, but not whether the left operand induces an implicit
13055 /// conversion for the entire comma expression itself. This is similar to
13056 /// how CheckConditionalOperand behaves; it's as-if the correct operand
13057 /// were directly used for the implicit conversion check.
13058 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
13059 /*ExtraCheckForImplicitConversion=*/false, WorkList);
13060 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
13061 /*ExtraCheckForImplicitConversion=*/true, WorkList);
13062 return;
13063 }
13064 }
13065
13066 // For conditional operators, we analyze the arguments as if they
13067 // were being fed directly into the output.
13068 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13069 CheckConditionalOperator(S, CO, CC, T);
13070 return;
13071 }
13072
13073 // Check implicit argument conversions for function calls.
13074 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
13076
13077 // Go ahead and check any implicit conversions we might have skipped.
13078 // The non-canonical typecheck is just an optimization;
13079 // CheckImplicitConversion will filter out dead implicit conversions.
13080 if (SourceExpr->getType() != T)
13081 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
13082
13083 // Now continue drilling into this expression.
13084
13085 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13086 // The bound subexpressions in a PseudoObjectExpr are not reachable
13087 // as transitive children.
13088 // FIXME: Use a more uniform representation for this.
13089 for (auto *SE : POE->semantics())
13090 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13091 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13092 }
13093
13094 // Skip past explicit casts.
13095 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13096 E = CE->getSubExpr();
13097 // In the special case of a C++ function-style cast with braces,
13098 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
13099 // initializer. This InitListExpr basically belongs to the cast itself, so
13100 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
13102 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
13103 if (InitListE->getNumInits() == 1) {
13104 E = InitListE->getInit(0);
13105 }
13106 }
13107 }
13108 E = E->IgnoreParenImpCasts();
13109 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13110 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13111 WorkList.push_back({E, CC, IsListInit});
13112 return;
13113 }
13114
13115 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
13116 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
13117 // The base expression is only used to initialize the parameter for
13118 // arguments to `inout` parameters, so we only traverse down the base
13119 // expression for `inout` cases.
13120 if (OutArgE->isInOut())
13121 WorkList.push_back(
13122 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
13123 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
13124 return;
13125 }
13126
13127 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13128 // Do a somewhat different check with comparison operators.
13129 if (BO->isComparisonOp())
13130 return AnalyzeComparison(S, BO);
13131
13132 // And with simple assignments.
13133 if (BO->getOpcode() == BO_Assign)
13134 return AnalyzeAssignment(S, BO);
13135 // And with compound assignments.
13136 if (BO->isAssignmentOp())
13137 return AnalyzeCompoundAssignment(S, BO);
13138 }
13139
13140 // These break the otherwise-useful invariant below. Fortunately,
13141 // we don't really need to recurse into them, because any internal
13142 // expressions should have been analyzed already when they were
13143 // built into statements.
13144 if (isa<StmtExpr>(E)) return;
13145
13146 // Don't descend into unevaluated contexts.
13147 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13148
13149 // Now just recurse over the expression's children.
13150 CC = E->getExprLoc();
13151 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13152 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13153 for (Stmt *SubStmt : E->children()) {
13154 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13155 if (!ChildExpr)
13156 continue;
13157
13158 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
13159 if (ChildExpr == CSE->getOperand())
13160 // Do not recurse over a CoroutineSuspendExpr's operand.
13161 // The operand is also a subexpression of getCommonExpr(), and
13162 // recursing into it directly would produce duplicate diagnostics.
13163 continue;
13164
13165 if (IsLogicalAndOperator &&
13167 // Ignore checking string literals that are in logical and operators.
13168 // This is a common pattern for asserts.
13169 continue;
13170 WorkList.push_back({ChildExpr, CC, IsListInit});
13171 }
13172
13173 if (BO && BO->isLogicalOp()) {
13174 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13175 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13176 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13177
13178 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13179 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13180 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13181 }
13182
13183 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13184 if (U->getOpcode() == UO_LNot) {
13185 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13186 } else if (U->getOpcode() != UO_AddrOf) {
13187 if (U->getSubExpr()->getType()->isAtomicType())
13188 S.Diag(U->getSubExpr()->getBeginLoc(),
13189 diag::warn_atomic_implicit_seq_cst);
13190 }
13191 }
13192}
13193
13194/// AnalyzeImplicitConversions - Find and report any interesting
13195/// implicit conversions in the given expression. There are a couple
13196/// of competing diagnostics here, -Wconversion and -Wsign-compare.
13198 bool IsListInit/*= false*/) {
13200 WorkList.push_back({OrigE, CC, IsListInit});
13201 while (!WorkList.empty())
13202 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13203}
13204
13205// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13206// Returns true when emitting a warning about taking the address of a reference.
13207static bool CheckForReference(Sema &SemaRef, const Expr *E,
13208 const PartialDiagnostic &PD) {
13209 E = E->IgnoreParenImpCasts();
13210
13211 const FunctionDecl *FD = nullptr;
13212
13213 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13214 if (!DRE->getDecl()->getType()->isReferenceType())
13215 return false;
13216 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13217 if (!M->getMemberDecl()->getType()->isReferenceType())
13218 return false;
13219 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13220 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13221 return false;
13222 FD = Call->getDirectCallee();
13223 } else {
13224 return false;
13225 }
13226
13227 SemaRef.Diag(E->getExprLoc(), PD);
13228
13229 // If possible, point to location of function.
13230 if (FD) {
13231 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13232 }
13233
13234 return true;
13235}
13236
13237// Returns true if the SourceLocation is expanded from any macro body.
13238// Returns false if the SourceLocation is invalid, is from not in a macro
13239// expansion, or is from expanded from a top-level macro argument.
13241 if (Loc.isInvalid())
13242 return false;
13243
13244 while (Loc.isMacroID()) {
13245 if (SM.isMacroBodyExpansion(Loc))
13246 return true;
13247 Loc = SM.getImmediateMacroCallerLoc(Loc);
13248 }
13249
13250 return false;
13251}
13252
13255 bool IsEqual, SourceRange Range) {
13256 if (!E)
13257 return;
13258
13259 // Don't warn inside macros.
13260 if (E->getExprLoc().isMacroID()) {
13262 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13263 IsInAnyMacroBody(SM, Range.getBegin()))
13264 return;
13265 }
13266 E = E->IgnoreImpCasts();
13267
13268 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13269
13270 if (isa<CXXThisExpr>(E)) {
13271 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13272 : diag::warn_this_bool_conversion;
13273 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13274 return;
13275 }
13276
13277 bool IsAddressOf = false;
13278
13279 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
13280 if (UO->getOpcode() != UO_AddrOf)
13281 return;
13282 IsAddressOf = true;
13283 E = UO->getSubExpr();
13284 }
13285
13286 if (IsAddressOf) {
13287 unsigned DiagID = IsCompare
13288 ? diag::warn_address_of_reference_null_compare
13289 : diag::warn_address_of_reference_bool_conversion;
13290 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13291 << IsEqual;
13292 if (CheckForReference(*this, E, PD)) {
13293 return;
13294 }
13295 }
13296
13297 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13298 bool IsParam = isa<NonNullAttr>(NonnullAttr);
13299 std::string Str;
13300 llvm::raw_string_ostream S(Str);
13301 E->printPretty(S, nullptr, getPrintingPolicy());
13302 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13303 : diag::warn_cast_nonnull_to_bool;
13304 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13305 << E->getSourceRange() << Range << IsEqual;
13306 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13307 };
13308
13309 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13310 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13311 if (auto *Callee = Call->getDirectCallee()) {
13312 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13313 ComplainAboutNonnullParamOrCall(A);
13314 return;
13315 }
13316 }
13317 }
13318
13319 // Complain if we are converting a lambda expression to a boolean value
13320 // outside of instantiation.
13321 if (!inTemplateInstantiation()) {
13322 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
13323 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
13324 MRecordDecl && MRecordDecl->isLambda()) {
13325 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
13326 << /*LambdaPointerConversionOperatorType=*/3
13327 << MRecordDecl->getSourceRange() << Range << IsEqual;
13328 return;
13329 }
13330 }
13331 }
13332
13333 // Expect to find a single Decl. Skip anything more complicated.
13334 ValueDecl *D = nullptr;
13335 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13336 D = R->getDecl();
13337 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13338 D = M->getMemberDecl();
13339 }
13340
13341 // Weak Decls can be null.
13342 if (!D || D->isWeak())
13343 return;
13344
13345 // Check for parameter decl with nonnull attribute
13346 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13347 if (getCurFunction() &&
13348 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13349 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13350 ComplainAboutNonnullParamOrCall(A);
13351 return;
13352 }
13353
13354 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13355 // Skip function template not specialized yet.
13357 return;
13358 auto ParamIter = llvm::find(FD->parameters(), PV);
13359 assert(ParamIter != FD->param_end());
13360 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13361
13362 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13363 if (!NonNull->args_size()) {
13364 ComplainAboutNonnullParamOrCall(NonNull);
13365 return;
13366 }
13367
13368 for (const ParamIdx &ArgNo : NonNull->args()) {
13369 if (ArgNo.getASTIndex() == ParamNo) {
13370 ComplainAboutNonnullParamOrCall(NonNull);
13371 return;
13372 }
13373 }
13374 }
13375 }
13376 }
13377 }
13378
13379 QualType T = D->getType();
13380 const bool IsArray = T->isArrayType();
13381 const bool IsFunction = T->isFunctionType();
13382
13383 // Address of function is used to silence the function warning.
13384 if (IsAddressOf && IsFunction) {
13385 return;
13386 }
13387
13388 // Found nothing.
13389 if (!IsAddressOf && !IsFunction && !IsArray)
13390 return;
13391
13392 // Pretty print the expression for the diagnostic.
13393 std::string Str;
13394 llvm::raw_string_ostream S(Str);
13395 E->printPretty(S, nullptr, getPrintingPolicy());
13396
13397 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13398 : diag::warn_impcast_pointer_to_bool;
13399 enum {
13400 AddressOf,
13401 FunctionPointer,
13402 ArrayPointer
13403 } DiagType;
13404 if (IsAddressOf)
13405 DiagType = AddressOf;
13406 else if (IsFunction)
13407 DiagType = FunctionPointer;
13408 else if (IsArray)
13409 DiagType = ArrayPointer;
13410 else
13411 llvm_unreachable("Could not determine diagnostic.");
13412 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13413 << Range << IsEqual;
13414
13415 if (!IsFunction)
13416 return;
13417
13418 // Suggest '&' to silence the function warning.
13419 Diag(E->getExprLoc(), diag::note_function_warning_silence)
13421
13422 // Check to see if '()' fixit should be emitted.
13423 QualType ReturnType;
13424 UnresolvedSet<4> NonTemplateOverloads;
13425 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13426 if (ReturnType.isNull())
13427 return;
13428
13429 if (IsCompare) {
13430 // There are two cases here. If there is null constant, the only suggest
13431 // for a pointer return type. If the null is 0, then suggest if the return
13432 // type is a pointer or an integer type.
13433 if (!ReturnType->isPointerType()) {
13434 if (NullKind == Expr::NPCK_ZeroExpression ||
13435 NullKind == Expr::NPCK_ZeroLiteral) {
13436 if (!ReturnType->isIntegerType())
13437 return;
13438 } else {
13439 return;
13440 }
13441 }
13442 } else { // !IsCompare
13443 // For function to bool, only suggest if the function pointer has bool
13444 // return type.
13445 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13446 return;
13447 }
13448 Diag(E->getExprLoc(), diag::note_function_to_function_call)
13450}
13451
13452void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13453 // Don't diagnose in unevaluated contexts.
13455 return;
13456
13457 // Don't diagnose for value- or type-dependent expressions.
13458 if (E->isTypeDependent() || E->isValueDependent())
13459 return;
13460
13461 // Check for array bounds violations in cases where the check isn't triggered
13462 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13463 // ArraySubscriptExpr is on the RHS of a variable initialization.
13464 CheckArrayAccess(E);
13465
13466 // This is not the right CC for (e.g.) a variable initialization.
13467 AnalyzeImplicitConversions(*this, E, CC);
13468}
13469
13470void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13471 ::CheckBoolLikeConversion(*this, E, CC);
13472}
13473
13474void Sema::CheckForIntOverflow (const Expr *E) {
13475 // Use a work list to deal with nested struct initializers.
13476 SmallVector<const Expr *, 2> Exprs(1, E);
13477
13478 do {
13479 const Expr *OriginalE = Exprs.pop_back_val();
13480 const Expr *E = OriginalE->IgnoreParenCasts();
13481
13484 continue;
13485 }
13486
13487 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
13488 Exprs.append(InitList->inits().begin(), InitList->inits().end());
13489 else if (isa<ObjCBoxedExpr>(OriginalE))
13491 else if (const auto *Call = dyn_cast<CallExpr>(E))
13492 Exprs.append(Call->arg_begin(), Call->arg_end());
13493 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
13494 Exprs.append(Message->arg_begin(), Message->arg_end());
13495 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
13496 Exprs.append(Construct->arg_begin(), Construct->arg_end());
13497 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
13498 Exprs.push_back(Temporary->getSubExpr());
13499 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
13500 Exprs.push_back(Array->getIdx());
13501 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
13502 Exprs.push_back(Compound->getInitializer());
13503 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
13504 New && New->isArray()) {
13505 if (auto ArraySize = New->getArraySize())
13506 Exprs.push_back(*ArraySize);
13507 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
13508 Exprs.push_back(MTE->getSubExpr());
13509 } while (!Exprs.empty());
13510}
13511
13512namespace {
13513
13514/// Visitor for expressions which looks for unsequenced operations on the
13515/// same object.
13516class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13517 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13518
13519 /// A tree of sequenced regions within an expression. Two regions are
13520 /// unsequenced if one is an ancestor or a descendent of the other. When we
13521 /// finish processing an expression with sequencing, such as a comma
13522 /// expression, we fold its tree nodes into its parent, since they are
13523 /// unsequenced with respect to nodes we will visit later.
13524 class SequenceTree {
13525 struct Value {
13526 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13527 unsigned Parent : 31;
13528 LLVM_PREFERRED_TYPE(bool)
13529 unsigned Merged : 1;
13530 };
13531 SmallVector<Value, 8> Values;
13532
13533 public:
13534 /// A region within an expression which may be sequenced with respect
13535 /// to some other region.
13536 class Seq {
13537 friend class SequenceTree;
13538
13539 unsigned Index;
13540
13541 explicit Seq(unsigned N) : Index(N) {}
13542
13543 public:
13544 Seq() : Index(0) {}
13545 };
13546
13547 SequenceTree() { Values.push_back(Value(0)); }
13548 Seq root() const { return Seq(0); }
13549
13550 /// Create a new sequence of operations, which is an unsequenced
13551 /// subset of \p Parent. This sequence of operations is sequenced with
13552 /// respect to other children of \p Parent.
13553 Seq allocate(Seq Parent) {
13554 Values.push_back(Value(Parent.Index));
13555 return Seq(Values.size() - 1);
13556 }
13557
13558 /// Merge a sequence of operations into its parent.
13559 void merge(Seq S) {
13560 Values[S.Index].Merged = true;
13561 }
13562
13563 /// Determine whether two operations are unsequenced. This operation
13564 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13565 /// should have been merged into its parent as appropriate.
13566 bool isUnsequenced(Seq Cur, Seq Old) {
13567 unsigned C = representative(Cur.Index);
13568 unsigned Target = representative(Old.Index);
13569 while (C >= Target) {
13570 if (C == Target)
13571 return true;
13572 C = Values[C].Parent;
13573 }
13574 return false;
13575 }
13576
13577 private:
13578 /// Pick a representative for a sequence.
13579 unsigned representative(unsigned K) {
13580 if (Values[K].Merged)
13581 // Perform path compression as we go.
13582 return Values[K].Parent = representative(Values[K].Parent);
13583 return K;
13584 }
13585 };
13586
13587 /// An object for which we can track unsequenced uses.
13588 using Object = const NamedDecl *;
13589
13590 /// Different flavors of object usage which we track. We only track the
13591 /// least-sequenced usage of each kind.
13592 enum UsageKind {
13593 /// A read of an object. Multiple unsequenced reads are OK.
13594 UK_Use,
13595
13596 /// A modification of an object which is sequenced before the value
13597 /// computation of the expression, such as ++n in C++.
13598 UK_ModAsValue,
13599
13600 /// A modification of an object which is not sequenced before the value
13601 /// computation of the expression, such as n++.
13602 UK_ModAsSideEffect,
13603
13604 UK_Count = UK_ModAsSideEffect + 1
13605 };
13606
13607 /// Bundle together a sequencing region and the expression corresponding
13608 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13609 struct Usage {
13610 const Expr *UsageExpr = nullptr;
13611 SequenceTree::Seq Seq;
13612
13613 Usage() = default;
13614 };
13615
13616 struct UsageInfo {
13617 Usage Uses[UK_Count];
13618
13619 /// Have we issued a diagnostic for this object already?
13620 bool Diagnosed = false;
13621
13622 UsageInfo();
13623 };
13624 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13625
13626 Sema &SemaRef;
13627
13628 /// Sequenced regions within the expression.
13629 SequenceTree Tree;
13630
13631 /// Declaration modifications and references which we have seen.
13632 UsageInfoMap UsageMap;
13633
13634 /// The region we are currently within.
13635 SequenceTree::Seq Region;
13636
13637 /// Filled in with declarations which were modified as a side-effect
13638 /// (that is, post-increment operations).
13639 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13640
13641 /// Expressions to check later. We defer checking these to reduce
13642 /// stack usage.
13643 SmallVectorImpl<const Expr *> &WorkList;
13644
13645 /// RAII object wrapping the visitation of a sequenced subexpression of an
13646 /// expression. At the end of this process, the side-effects of the evaluation
13647 /// become sequenced with respect to the value computation of the result, so
13648 /// we downgrade any UK_ModAsSideEffect within the evaluation to
13649 /// UK_ModAsValue.
13650 struct SequencedSubexpression {
13651 SequencedSubexpression(SequenceChecker &Self)
13652 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13653 Self.ModAsSideEffect = &ModAsSideEffect;
13654 }
13655
13656 ~SequencedSubexpression() {
13657 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13658 // Add a new usage with usage kind UK_ModAsValue, and then restore
13659 // the previous usage with UK_ModAsSideEffect (thus clearing it if
13660 // the previous one was empty).
13661 UsageInfo &UI = Self.UsageMap[M.first];
13662 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13663 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13664 SideEffectUsage = M.second;
13665 }
13666 Self.ModAsSideEffect = OldModAsSideEffect;
13667 }
13668
13669 SequenceChecker &Self;
13670 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13671 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13672 };
13673
13674 /// RAII object wrapping the visitation of a subexpression which we might
13675 /// choose to evaluate as a constant. If any subexpression is evaluated and
13676 /// found to be non-constant, this allows us to suppress the evaluation of
13677 /// the outer expression.
13678 class EvaluationTracker {
13679 public:
13680 EvaluationTracker(SequenceChecker &Self)
13681 : Self(Self), Prev(Self.EvalTracker) {
13682 Self.EvalTracker = this;
13683 }
13684
13685 ~EvaluationTracker() {
13686 Self.EvalTracker = Prev;
13687 if (Prev)
13688 Prev->EvalOK &= EvalOK;
13689 }
13690
13691 bool evaluate(const Expr *E, bool &Result) {
13692 if (!EvalOK || E->isValueDependent())
13693 return false;
13694 EvalOK = E->EvaluateAsBooleanCondition(
13695 Result, Self.SemaRef.Context,
13696 Self.SemaRef.isConstantEvaluatedContext());
13697 return EvalOK;
13698 }
13699
13700 private:
13701 SequenceChecker &Self;
13702 EvaluationTracker *Prev;
13703 bool EvalOK = true;
13704 } *EvalTracker = nullptr;
13705
13706 /// Find the object which is produced by the specified expression,
13707 /// if any.
13708 Object getObject(const Expr *E, bool Mod) const {
13709 E = E->IgnoreParenCasts();
13710 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13711 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13712 return getObject(UO->getSubExpr(), Mod);
13713 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13714 if (BO->getOpcode() == BO_Comma)
13715 return getObject(BO->getRHS(), Mod);
13716 if (Mod && BO->isAssignmentOp())
13717 return getObject(BO->getLHS(), Mod);
13718 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13719 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13720 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13721 return ME->getMemberDecl();
13722 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13723 // FIXME: If this is a reference, map through to its value.
13724 return DRE->getDecl();
13725 return nullptr;
13726 }
13727
13728 /// Note that an object \p O was modified or used by an expression
13729 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13730 /// the object \p O as obtained via the \p UsageMap.
13731 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13732 // Get the old usage for the given object and usage kind.
13733 Usage &U = UI.Uses[UK];
13734 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13735 // If we have a modification as side effect and are in a sequenced
13736 // subexpression, save the old Usage so that we can restore it later
13737 // in SequencedSubexpression::~SequencedSubexpression.
13738 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13739 ModAsSideEffect->push_back(std::make_pair(O, U));
13740 // Then record the new usage with the current sequencing region.
13741 U.UsageExpr = UsageExpr;
13742 U.Seq = Region;
13743 }
13744 }
13745
13746 /// Check whether a modification or use of an object \p O in an expression
13747 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13748 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13749 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13750 /// usage and false we are checking for a mod-use unsequenced usage.
13751 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13752 UsageKind OtherKind, bool IsModMod) {
13753 if (UI.Diagnosed)
13754 return;
13755
13756 const Usage &U = UI.Uses[OtherKind];
13757 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13758 return;
13759
13760 const Expr *Mod = U.UsageExpr;
13761 const Expr *ModOrUse = UsageExpr;
13762 if (OtherKind == UK_Use)
13763 std::swap(Mod, ModOrUse);
13764
13765 SemaRef.DiagRuntimeBehavior(
13766 Mod->getExprLoc(), {Mod, ModOrUse},
13767 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13768 : diag::warn_unsequenced_mod_use)
13769 << O << SourceRange(ModOrUse->getExprLoc()));
13770 UI.Diagnosed = true;
13771 }
13772
13773 // A note on note{Pre, Post}{Use, Mod}:
13774 //
13775 // (It helps to follow the algorithm with an expression such as
13776 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13777 // operations before C++17 and both are well-defined in C++17).
13778 //
13779 // When visiting a node which uses/modify an object we first call notePreUse
13780 // or notePreMod before visiting its sub-expression(s). At this point the
13781 // children of the current node have not yet been visited and so the eventual
13782 // uses/modifications resulting from the children of the current node have not
13783 // been recorded yet.
13784 //
13785 // We then visit the children of the current node. After that notePostUse or
13786 // notePostMod is called. These will 1) detect an unsequenced modification
13787 // as side effect (as in "k++ + k") and 2) add a new usage with the
13788 // appropriate usage kind.
13789 //
13790 // We also have to be careful that some operation sequences modification as
13791 // side effect as well (for example: || or ,). To account for this we wrap
13792 // the visitation of such a sub-expression (for example: the LHS of || or ,)
13793 // with SequencedSubexpression. SequencedSubexpression is an RAII object
13794 // which record usages which are modifications as side effect, and then
13795 // downgrade them (or more accurately restore the previous usage which was a
13796 // modification as side effect) when exiting the scope of the sequenced
13797 // subexpression.
13798
13799 void notePreUse(Object O, const Expr *UseExpr) {
13800 UsageInfo &UI = UsageMap[O];
13801 // Uses conflict with other modifications.
13802 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13803 }
13804
13805 void notePostUse(Object O, const Expr *UseExpr) {
13806 UsageInfo &UI = UsageMap[O];
13807 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13808 /*IsModMod=*/false);
13809 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13810 }
13811
13812 void notePreMod(Object O, const Expr *ModExpr) {
13813 UsageInfo &UI = UsageMap[O];
13814 // Modifications conflict with other modifications and with uses.
13815 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13816 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13817 }
13818
13819 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13820 UsageInfo &UI = UsageMap[O];
13821 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13822 /*IsModMod=*/true);
13823 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13824 }
13825
13826public:
13827 SequenceChecker(Sema &S, const Expr *E,
13828 SmallVectorImpl<const Expr *> &WorkList)
13829 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13830 Visit(E);
13831 // Silence a -Wunused-private-field since WorkList is now unused.
13832 // TODO: Evaluate if it can be used, and if not remove it.
13833 (void)this->WorkList;
13834 }
13835
13836 void VisitStmt(const Stmt *S) {
13837 // Skip all statements which aren't expressions for now.
13838 }
13839
13840 void VisitExpr(const Expr *E) {
13841 // By default, just recurse to evaluated subexpressions.
13842 Base::VisitStmt(E);
13843 }
13844
13845 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
13846 for (auto *Sub : CSE->children()) {
13847 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
13848 if (!ChildExpr)
13849 continue;
13850
13851 if (ChildExpr == CSE->getOperand())
13852 // Do not recurse over a CoroutineSuspendExpr's operand.
13853 // The operand is also a subexpression of getCommonExpr(), and
13854 // recursing into it directly could confuse object management
13855 // for the sake of sequence tracking.
13856 continue;
13857
13858 Visit(Sub);
13859 }
13860 }
13861
13862 void VisitCastExpr(const CastExpr *E) {
13863 Object O = Object();
13864 if (E->getCastKind() == CK_LValueToRValue)
13865 O = getObject(E->getSubExpr(), false);
13866
13867 if (O)
13868 notePreUse(O, E);
13869 VisitExpr(E);
13870 if (O)
13871 notePostUse(O, E);
13872 }
13873
13874 void VisitSequencedExpressions(const Expr *SequencedBefore,
13875 const Expr *SequencedAfter) {
13876 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13877 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13878 SequenceTree::Seq OldRegion = Region;
13879
13880 {
13881 SequencedSubexpression SeqBefore(*this);
13882 Region = BeforeRegion;
13883 Visit(SequencedBefore);
13884 }
13885
13886 Region = AfterRegion;
13887 Visit(SequencedAfter);
13888
13889 Region = OldRegion;
13890
13891 Tree.merge(BeforeRegion);
13892 Tree.merge(AfterRegion);
13893 }
13894
13895 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13896 // C++17 [expr.sub]p1:
13897 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13898 // expression E1 is sequenced before the expression E2.
13899 if (SemaRef.getLangOpts().CPlusPlus17)
13900 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13901 else {
13902 Visit(ASE->getLHS());
13903 Visit(ASE->getRHS());
13904 }
13905 }
13906
13907 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13908 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13909 void VisitBinPtrMem(const BinaryOperator *BO) {
13910 // C++17 [expr.mptr.oper]p4:
13911 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13912 // the expression E1 is sequenced before the expression E2.
13913 if (SemaRef.getLangOpts().CPlusPlus17)
13914 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13915 else {
13916 Visit(BO->getLHS());
13917 Visit(BO->getRHS());
13918 }
13919 }
13920
13921 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13922 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13923 void VisitBinShlShr(const BinaryOperator *BO) {
13924 // C++17 [expr.shift]p4:
13925 // The expression E1 is sequenced before the expression E2.
13926 if (SemaRef.getLangOpts().CPlusPlus17)
13927 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13928 else {
13929 Visit(BO->getLHS());
13930 Visit(BO->getRHS());
13931 }
13932 }
13933
13934 void VisitBinComma(const BinaryOperator *BO) {
13935 // C++11 [expr.comma]p1:
13936 // Every value computation and side effect associated with the left
13937 // expression is sequenced before every value computation and side
13938 // effect associated with the right expression.
13939 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13940 }
13941
13942 void VisitBinAssign(const BinaryOperator *BO) {
13943 SequenceTree::Seq RHSRegion;
13944 SequenceTree::Seq LHSRegion;
13945 if (SemaRef.getLangOpts().CPlusPlus17) {
13946 RHSRegion = Tree.allocate(Region);
13947 LHSRegion = Tree.allocate(Region);
13948 } else {
13949 RHSRegion = Region;
13950 LHSRegion = Region;
13951 }
13952 SequenceTree::Seq OldRegion = Region;
13953
13954 // C++11 [expr.ass]p1:
13955 // [...] the assignment is sequenced after the value computation
13956 // of the right and left operands, [...]
13957 //
13958 // so check it before inspecting the operands and update the
13959 // map afterwards.
13960 Object O = getObject(BO->getLHS(), /*Mod=*/true);
13961 if (O)
13962 notePreMod(O, BO);
13963
13964 if (SemaRef.getLangOpts().CPlusPlus17) {
13965 // C++17 [expr.ass]p1:
13966 // [...] The right operand is sequenced before the left operand. [...]
13967 {
13968 SequencedSubexpression SeqBefore(*this);
13969 Region = RHSRegion;
13970 Visit(BO->getRHS());
13971 }
13972
13973 Region = LHSRegion;
13974 Visit(BO->getLHS());
13975
13976 if (O && isa<CompoundAssignOperator>(BO))
13977 notePostUse(O, BO);
13978
13979 } else {
13980 // C++11 does not specify any sequencing between the LHS and RHS.
13981 Region = LHSRegion;
13982 Visit(BO->getLHS());
13983
13984 if (O && isa<CompoundAssignOperator>(BO))
13985 notePostUse(O, BO);
13986
13987 Region = RHSRegion;
13988 Visit(BO->getRHS());
13989 }
13990
13991 // C++11 [expr.ass]p1:
13992 // the assignment is sequenced [...] before the value computation of the
13993 // assignment expression.
13994 // C11 6.5.16/3 has no such rule.
13995 Region = OldRegion;
13996 if (O)
13997 notePostMod(O, BO,
13998 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13999 : UK_ModAsSideEffect);
14000 if (SemaRef.getLangOpts().CPlusPlus17) {
14001 Tree.merge(RHSRegion);
14002 Tree.merge(LHSRegion);
14003 }
14004 }
14005
14006 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14007 VisitBinAssign(CAO);
14008 }
14009
14010 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14011 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14012 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14013 Object O = getObject(UO->getSubExpr(), true);
14014 if (!O)
14015 return VisitExpr(UO);
14016
14017 notePreMod(O, UO);
14018 Visit(UO->getSubExpr());
14019 // C++11 [expr.pre.incr]p1:
14020 // the expression ++x is equivalent to x+=1
14021 notePostMod(O, UO,
14022 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14023 : UK_ModAsSideEffect);
14024 }
14025
14026 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14027 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14028 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14029 Object O = getObject(UO->getSubExpr(), true);
14030 if (!O)
14031 return VisitExpr(UO);
14032
14033 notePreMod(O, UO);
14034 Visit(UO->getSubExpr());
14035 notePostMod(O, UO, UK_ModAsSideEffect);
14036 }
14037
14038 void VisitBinLOr(const BinaryOperator *BO) {
14039 // C++11 [expr.log.or]p2:
14040 // If the second expression is evaluated, every value computation and
14041 // side effect associated with the first expression is sequenced before
14042 // every value computation and side effect associated with the
14043 // second expression.
14044 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14045 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14046 SequenceTree::Seq OldRegion = Region;
14047
14048 EvaluationTracker Eval(*this);
14049 {
14050 SequencedSubexpression Sequenced(*this);
14051 Region = LHSRegion;
14052 Visit(BO->getLHS());
14053 }
14054
14055 // C++11 [expr.log.or]p1:
14056 // [...] the second operand is not evaluated if the first operand
14057 // evaluates to true.
14058 bool EvalResult = false;
14059 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14060 bool ShouldVisitRHS = !EvalOK || !EvalResult;
14061 if (ShouldVisitRHS) {
14062 Region = RHSRegion;
14063 Visit(BO->getRHS());
14064 }
14065
14066 Region = OldRegion;
14067 Tree.merge(LHSRegion);
14068 Tree.merge(RHSRegion);
14069 }
14070
14071 void VisitBinLAnd(const BinaryOperator *BO) {
14072 // C++11 [expr.log.and]p2:
14073 // If the second expression is evaluated, every value computation and
14074 // side effect associated with the first expression is sequenced before
14075 // every value computation and side effect associated with the
14076 // second expression.
14077 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14078 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14079 SequenceTree::Seq OldRegion = Region;
14080
14081 EvaluationTracker Eval(*this);
14082 {
14083 SequencedSubexpression Sequenced(*this);
14084 Region = LHSRegion;
14085 Visit(BO->getLHS());
14086 }
14087
14088 // C++11 [expr.log.and]p1:
14089 // [...] the second operand is not evaluated if the first operand is false.
14090 bool EvalResult = false;
14091 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14092 bool ShouldVisitRHS = !EvalOK || EvalResult;
14093 if (ShouldVisitRHS) {
14094 Region = RHSRegion;
14095 Visit(BO->getRHS());
14096 }
14097
14098 Region = OldRegion;
14099 Tree.merge(LHSRegion);
14100 Tree.merge(RHSRegion);
14101 }
14102
14103 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14104 // C++11 [expr.cond]p1:
14105 // [...] Every value computation and side effect associated with the first
14106 // expression is sequenced before every value computation and side effect
14107 // associated with the second or third expression.
14108 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14109
14110 // No sequencing is specified between the true and false expression.
14111 // However since exactly one of both is going to be evaluated we can
14112 // consider them to be sequenced. This is needed to avoid warning on
14113 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14114 // both the true and false expressions because we can't evaluate x.
14115 // This will still allow us to detect an expression like (pre C++17)
14116 // "(x ? y += 1 : y += 2) = y".
14117 //
14118 // We don't wrap the visitation of the true and false expression with
14119 // SequencedSubexpression because we don't want to downgrade modifications
14120 // as side effect in the true and false expressions after the visition
14121 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14122 // not warn between the two "y++", but we should warn between the "y++"
14123 // and the "y".
14124 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14125 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14126 SequenceTree::Seq OldRegion = Region;
14127
14128 EvaluationTracker Eval(*this);
14129 {
14130 SequencedSubexpression Sequenced(*this);
14131 Region = ConditionRegion;
14132 Visit(CO->getCond());
14133 }
14134
14135 // C++11 [expr.cond]p1:
14136 // [...] The first expression is contextually converted to bool (Clause 4).
14137 // It is evaluated and if it is true, the result of the conditional
14138 // expression is the value of the second expression, otherwise that of the
14139 // third expression. Only one of the second and third expressions is
14140 // evaluated. [...]
14141 bool EvalResult = false;
14142 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14143 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
14144 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
14145 if (ShouldVisitTrueExpr) {
14146 Region = TrueRegion;
14147 Visit(CO->getTrueExpr());
14148 }
14149 if (ShouldVisitFalseExpr) {
14150 Region = FalseRegion;
14151 Visit(CO->getFalseExpr());
14152 }
14153
14154 Region = OldRegion;
14155 Tree.merge(ConditionRegion);
14156 Tree.merge(TrueRegion);
14157 Tree.merge(FalseRegion);
14158 }
14159
14160 void VisitCallExpr(const CallExpr *CE) {
14161 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14162
14163 if (CE->isUnevaluatedBuiltinCall(Context))
14164 return;
14165
14166 // C++11 [intro.execution]p15:
14167 // When calling a function [...], every value computation and side effect
14168 // associated with any argument expression, or with the postfix expression
14169 // designating the called function, is sequenced before execution of every
14170 // expression or statement in the body of the function [and thus before
14171 // the value computation of its result].
14172 SequencedSubexpression Sequenced(*this);
14173 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14174 // C++17 [expr.call]p5
14175 // The postfix-expression is sequenced before each expression in the
14176 // expression-list and any default argument. [...]
14177 SequenceTree::Seq CalleeRegion;
14178 SequenceTree::Seq OtherRegion;
14179 if (SemaRef.getLangOpts().CPlusPlus17) {
14180 CalleeRegion = Tree.allocate(Region);
14181 OtherRegion = Tree.allocate(Region);
14182 } else {
14183 CalleeRegion = Region;
14184 OtherRegion = Region;
14185 }
14186 SequenceTree::Seq OldRegion = Region;
14187
14188 // Visit the callee expression first.
14189 Region = CalleeRegion;
14190 if (SemaRef.getLangOpts().CPlusPlus17) {
14191 SequencedSubexpression Sequenced(*this);
14192 Visit(CE->getCallee());
14193 } else {
14194 Visit(CE->getCallee());
14195 }
14196
14197 // Then visit the argument expressions.
14198 Region = OtherRegion;
14199 for (const Expr *Argument : CE->arguments())
14200 Visit(Argument);
14201
14202 Region = OldRegion;
14203 if (SemaRef.getLangOpts().CPlusPlus17) {
14204 Tree.merge(CalleeRegion);
14205 Tree.merge(OtherRegion);
14206 }
14207 });
14208 }
14209
14210 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14211 // C++17 [over.match.oper]p2:
14212 // [...] the operator notation is first transformed to the equivalent
14213 // function-call notation as summarized in Table 12 (where @ denotes one
14214 // of the operators covered in the specified subclause). However, the
14215 // operands are sequenced in the order prescribed for the built-in
14216 // operator (Clause 8).
14217 //
14218 // From the above only overloaded binary operators and overloaded call
14219 // operators have sequencing rules in C++17 that we need to handle
14220 // separately.
14221 if (!SemaRef.getLangOpts().CPlusPlus17 ||
14222 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14223 return VisitCallExpr(CXXOCE);
14224
14225 enum {
14226 NoSequencing,
14227 LHSBeforeRHS,
14228 RHSBeforeLHS,
14229 LHSBeforeRest
14230 } SequencingKind;
14231 switch (CXXOCE->getOperator()) {
14232 case OO_Equal:
14233 case OO_PlusEqual:
14234 case OO_MinusEqual:
14235 case OO_StarEqual:
14236 case OO_SlashEqual:
14237 case OO_PercentEqual:
14238 case OO_CaretEqual:
14239 case OO_AmpEqual:
14240 case OO_PipeEqual:
14241 case OO_LessLessEqual:
14242 case OO_GreaterGreaterEqual:
14243 SequencingKind = RHSBeforeLHS;
14244 break;
14245
14246 case OO_LessLess:
14247 case OO_GreaterGreater:
14248 case OO_AmpAmp:
14249 case OO_PipePipe:
14250 case OO_Comma:
14251 case OO_ArrowStar:
14252 case OO_Subscript:
14253 SequencingKind = LHSBeforeRHS;
14254 break;
14255
14256 case OO_Call:
14257 SequencingKind = LHSBeforeRest;
14258 break;
14259
14260 default:
14261 SequencingKind = NoSequencing;
14262 break;
14263 }
14264
14265 if (SequencingKind == NoSequencing)
14266 return VisitCallExpr(CXXOCE);
14267
14268 // This is a call, so all subexpressions are sequenced before the result.
14269 SequencedSubexpression Sequenced(*this);
14270
14271 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14272 assert(SemaRef.getLangOpts().CPlusPlus17 &&
14273 "Should only get there with C++17 and above!");
14274 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14275 "Should only get there with an overloaded binary operator"
14276 " or an overloaded call operator!");
14277
14278 if (SequencingKind == LHSBeforeRest) {
14279 assert(CXXOCE->getOperator() == OO_Call &&
14280 "We should only have an overloaded call operator here!");
14281
14282 // This is very similar to VisitCallExpr, except that we only have the
14283 // C++17 case. The postfix-expression is the first argument of the
14284 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14285 // are in the following arguments.
14286 //
14287 // Note that we intentionally do not visit the callee expression since
14288 // it is just a decayed reference to a function.
14289 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14290 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14291 SequenceTree::Seq OldRegion = Region;
14292
14293 assert(CXXOCE->getNumArgs() >= 1 &&
14294 "An overloaded call operator must have at least one argument"
14295 " for the postfix-expression!");
14296 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14297 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14298 CXXOCE->getNumArgs() - 1);
14299
14300 // Visit the postfix-expression first.
14301 {
14302 Region = PostfixExprRegion;
14303 SequencedSubexpression Sequenced(*this);
14304 Visit(PostfixExpr);
14305 }
14306
14307 // Then visit the argument expressions.
14308 Region = ArgsRegion;
14309 for (const Expr *Arg : Args)
14310 Visit(Arg);
14311
14312 Region = OldRegion;
14313 Tree.merge(PostfixExprRegion);
14314 Tree.merge(ArgsRegion);
14315 } else {
14316 assert(CXXOCE->getNumArgs() == 2 &&
14317 "Should only have two arguments here!");
14318 assert((SequencingKind == LHSBeforeRHS ||
14319 SequencingKind == RHSBeforeLHS) &&
14320 "Unexpected sequencing kind!");
14321
14322 // We do not visit the callee expression since it is just a decayed
14323 // reference to a function.
14324 const Expr *E1 = CXXOCE->getArg(0);
14325 const Expr *E2 = CXXOCE->getArg(1);
14326 if (SequencingKind == RHSBeforeLHS)
14327 std::swap(E1, E2);
14328
14329 return VisitSequencedExpressions(E1, E2);
14330 }
14331 });
14332 }
14333
14334 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14335 // This is a call, so all subexpressions are sequenced before the result.
14336 SequencedSubexpression Sequenced(*this);
14337
14338 if (!CCE->isListInitialization())
14339 return VisitExpr(CCE);
14340
14341 // In C++11, list initializations are sequenced.
14342 SequenceExpressionsInOrder(
14343 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
14344 }
14345
14346 void VisitInitListExpr(const InitListExpr *ILE) {
14347 if (!SemaRef.getLangOpts().CPlusPlus11)
14348 return VisitExpr(ILE);
14349
14350 // In C++11, list initializations are sequenced.
14351 SequenceExpressionsInOrder(ILE->inits());
14352 }
14353
14354 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
14355 // C++20 parenthesized list initializations are sequenced. See C++20
14356 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
14357 SequenceExpressionsInOrder(PLIE->getInitExprs());
14358 }
14359
14360private:
14361 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
14363 SequenceTree::Seq Parent = Region;
14364 for (const Expr *E : ExpressionList) {
14365 if (!E)
14366 continue;
14367 Region = Tree.allocate(Parent);
14368 Elts.push_back(Region);
14369 Visit(E);
14370 }
14371
14372 // Forget that the initializers are sequenced.
14373 Region = Parent;
14374 for (unsigned I = 0; I < Elts.size(); ++I)
14375 Tree.merge(Elts[I]);
14376 }
14377};
14378
14379SequenceChecker::UsageInfo::UsageInfo() = default;
14380
14381} // namespace
14382
14383void Sema::CheckUnsequencedOperations(const Expr *E) {
14384 SmallVector<const Expr *, 8> WorkList;
14385 WorkList.push_back(E);
14386 while (!WorkList.empty()) {
14387 const Expr *Item = WorkList.pop_back_val();
14388 SequenceChecker(*this, Item, WorkList);
14389 }
14390}
14391
14392void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14393 bool IsConstexpr) {
14394 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
14395 IsConstexpr || isa<ConstantExpr>(E));
14396 CheckImplicitConversions(E, CheckLoc);
14397 if (!E->isInstantiationDependent())
14398 CheckUnsequencedOperations(E);
14399 if (!IsConstexpr && !E->isValueDependent())
14400 CheckForIntOverflow(E);
14401}
14402
14403void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14404 FieldDecl *BitField,
14405 Expr *Init) {
14406 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14407}
14408
14410 SourceLocation Loc) {
14411 if (!PType->isVariablyModifiedType())
14412 return;
14413 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14414 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14415 return;
14416 }
14417 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14418 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14419 return;
14420 }
14421 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14422 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14423 return;
14424 }
14425
14426 const ArrayType *AT = S.Context.getAsArrayType(PType);
14427 if (!AT)
14428 return;
14429
14432 return;
14433 }
14434
14435 S.Diag(Loc, diag::err_array_star_in_function_definition);
14436}
14437
14439 bool CheckParameterNames) {
14440 bool HasInvalidParm = false;
14441 for (ParmVarDecl *Param : Parameters) {
14442 assert(Param && "null in a parameter list");
14443 // C99 6.7.5.3p4: the parameters in a parameter type list in a
14444 // function declarator that is part of a function definition of
14445 // that function shall not have incomplete type.
14446 //
14447 // C++23 [dcl.fct.def.general]/p2
14448 // The type of a parameter [...] for a function definition
14449 // shall not be a (possibly cv-qualified) class type that is incomplete
14450 // or abstract within the function body unless the function is deleted.
14451 if (!Param->isInvalidDecl() &&
14452 (RequireCompleteType(Param->getLocation(), Param->getType(),
14453 diag::err_typecheck_decl_incomplete_type) ||
14454 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
14455 diag::err_abstract_type_in_decl,
14457 Param->setInvalidDecl();
14458 HasInvalidParm = true;
14459 }
14460
14461 // C99 6.9.1p5: If the declarator includes a parameter type list, the
14462 // declaration of each parameter shall include an identifier.
14463 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14464 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14465 // Diagnose this as an extension in C17 and earlier.
14466 if (!getLangOpts().C23)
14467 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
14468 }
14469
14470 // C99 6.7.5.3p12:
14471 // If the function declarator is not part of a definition of that
14472 // function, parameters may have incomplete type and may use the [*]
14473 // notation in their sequences of declarator specifiers to specify
14474 // variable length array types.
14475 QualType PType = Param->getOriginalType();
14476 // FIXME: This diagnostic should point the '[*]' if source-location
14477 // information is added for it.
14478 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14479
14480 // If the parameter is a c++ class type and it has to be destructed in the
14481 // callee function, declare the destructor so that it can be called by the
14482 // callee function. Do not perform any direct access check on the dtor here.
14483 if (!Param->isInvalidDecl()) {
14484 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14485 if (!ClassDecl->isInvalidDecl() &&
14486 !ClassDecl->hasIrrelevantDestructor() &&
14487 !ClassDecl->isDependentContext() &&
14488 ClassDecl->isParamDestroyedInCallee()) {
14490 MarkFunctionReferenced(Param->getLocation(), Destructor);
14491 DiagnoseUseOfDecl(Destructor, Param->getLocation());
14492 }
14493 }
14494 }
14495
14496 // Parameters with the pass_object_size attribute only need to be marked
14497 // constant at function definitions. Because we lack information about
14498 // whether we're on a declaration or definition when we're instantiating the
14499 // attribute, we need to check for constness here.
14500 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14501 if (!Param->getType().isConstQualified())
14502 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14503 << Attr->getSpelling() << 1;
14504
14505 // Check for parameter names shadowing fields from the class.
14506 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14507 // The owning context for the parameter should be the function, but we
14508 // want to see if this function's declaration context is a record.
14509 DeclContext *DC = Param->getDeclContext();
14510 if (DC && DC->isFunctionOrMethod()) {
14511 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14512 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14513 RD, /*DeclIsField*/ false);
14514 }
14515 }
14516
14517 if (!Param->isInvalidDecl() &&
14518 Param->getOriginalType()->isWebAssemblyTableType()) {
14519 Param->setInvalidDecl();
14520 HasInvalidParm = true;
14521 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
14522 }
14523 }
14524
14525 return HasInvalidParm;
14526}
14527
14528std::optional<std::pair<
14530 *E,
14532 &Ctx);
14533
14534/// Compute the alignment and offset of the base class object given the
14535/// derived-to-base cast expression and the alignment and offset of the derived
14536/// class object.
14537static std::pair<CharUnits, CharUnits>
14539 CharUnits BaseAlignment, CharUnits Offset,
14540 ASTContext &Ctx) {
14541 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14542 ++PathI) {
14543 const CXXBaseSpecifier *Base = *PathI;
14544 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14545 if (Base->isVirtual()) {
14546 // The complete object may have a lower alignment than the non-virtual
14547 // alignment of the base, in which case the base may be misaligned. Choose
14548 // the smaller of the non-virtual alignment and BaseAlignment, which is a
14549 // conservative lower bound of the complete object alignment.
14550 CharUnits NonVirtualAlignment =
14552 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14553 Offset = CharUnits::Zero();
14554 } else {
14555 const ASTRecordLayout &RL =
14556 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14557 Offset += RL.getBaseClassOffset(BaseDecl);
14558 }
14559 DerivedType = Base->getType();
14560 }
14561
14562 return std::make_pair(BaseAlignment, Offset);
14563}
14564
14565/// Compute the alignment and offset of a binary additive operator.
14566static std::optional<std::pair<CharUnits, CharUnits>>
14568 bool IsSub, ASTContext &Ctx) {
14569 QualType PointeeType = PtrE->getType()->getPointeeType();
14570
14571 if (!PointeeType->isConstantSizeType())
14572 return std::nullopt;
14573
14574 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14575
14576 if (!P)
14577 return std::nullopt;
14578
14579 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14580 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14581 CharUnits Offset = EltSize * IdxRes->getExtValue();
14582 if (IsSub)
14583 Offset = -Offset;
14584 return std::make_pair(P->first, P->second + Offset);
14585 }
14586
14587 // If the integer expression isn't a constant expression, compute the lower
14588 // bound of the alignment using the alignment and offset of the pointer
14589 // expression and the element size.
14590 return std::make_pair(
14591 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14592 CharUnits::Zero());
14593}
14594
14595/// This helper function takes an lvalue expression and returns the alignment of
14596/// a VarDecl and a constant offset from the VarDecl.
14597std::optional<std::pair<
14598 CharUnits,
14600 ASTContext &Ctx) {
14601 E = E->IgnoreParens();
14602 switch (E->getStmtClass()) {
14603 default:
14604 break;
14605 case Stmt::CStyleCastExprClass:
14606 case Stmt::CXXStaticCastExprClass:
14607 case Stmt::ImplicitCastExprClass: {
14608 auto *CE = cast<CastExpr>(E);
14609 const Expr *From = CE->getSubExpr();
14610 switch (CE->getCastKind()) {
14611 default:
14612 break;
14613 case CK_NoOp:
14614 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14615 case CK_UncheckedDerivedToBase:
14616 case CK_DerivedToBase: {
14617 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14618 if (!P)
14619 break;
14620 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14621 P->second, Ctx);
14622 }
14623 }
14624 break;
14625 }
14626 case Stmt::ArraySubscriptExprClass: {
14627 auto *ASE = cast<ArraySubscriptExpr>(E);
14629 false, Ctx);
14630 }
14631 case Stmt::DeclRefExprClass: {
14632 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14633 // FIXME: If VD is captured by copy or is an escaping __block variable,
14634 // use the alignment of VD's type.
14635 if (!VD->getType()->isReferenceType()) {
14636 // Dependent alignment cannot be resolved -> bail out.
14637 if (VD->hasDependentAlignment())
14638 break;
14639 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14640 }
14641 if (VD->hasInit())
14642 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14643 }
14644 break;
14645 }
14646 case Stmt::MemberExprClass: {
14647 auto *ME = cast<MemberExpr>(E);
14648 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14649 if (!FD || FD->getType()->isReferenceType() ||
14650 FD->getParent()->isInvalidDecl())
14651 break;
14652 std::optional<std::pair<CharUnits, CharUnits>> P;
14653 if (ME->isArrow())
14654 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14655 else
14656 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14657 if (!P)
14658 break;
14659 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14660 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14661 return std::make_pair(P->first,
14662 P->second + CharUnits::fromQuantity(Offset));
14663 }
14664 case Stmt::UnaryOperatorClass: {
14665 auto *UO = cast<UnaryOperator>(E);
14666 switch (UO->getOpcode()) {
14667 default:
14668 break;
14669 case UO_Deref:
14671 }
14672 break;
14673 }
14674 case Stmt::BinaryOperatorClass: {
14675 auto *BO = cast<BinaryOperator>(E);
14676 auto Opcode = BO->getOpcode();
14677 switch (Opcode) {
14678 default:
14679 break;
14680 case BO_Comma:
14682 }
14683 break;
14684 }
14685 }
14686 return std::nullopt;
14687}
14688
14689/// This helper function takes a pointer expression and returns the alignment of
14690/// a VarDecl and a constant offset from the VarDecl.
14691std::optional<std::pair<
14693 *E,
14695 &Ctx) {
14696 E = E->IgnoreParens();
14697 switch (E->getStmtClass()) {
14698 default:
14699 break;
14700 case Stmt::CStyleCastExprClass:
14701 case Stmt::CXXStaticCastExprClass:
14702 case Stmt::ImplicitCastExprClass: {
14703 auto *CE = cast<CastExpr>(E);
14704 const Expr *From = CE->getSubExpr();
14705 switch (CE->getCastKind()) {
14706 default:
14707 break;
14708 case CK_NoOp:
14709 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14710 case CK_ArrayToPointerDecay:
14711 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14712 case CK_UncheckedDerivedToBase:
14713 case CK_DerivedToBase: {
14714 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14715 if (!P)
14716 break;
14718 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14719 }
14720 }
14721 break;
14722 }
14723 case Stmt::CXXThisExprClass: {
14724 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14726 return std::make_pair(Alignment, CharUnits::Zero());
14727 }
14728 case Stmt::UnaryOperatorClass: {
14729 auto *UO = cast<UnaryOperator>(E);
14730 if (UO->getOpcode() == UO_AddrOf)
14732 break;
14733 }
14734 case Stmt::BinaryOperatorClass: {
14735 auto *BO = cast<BinaryOperator>(E);
14736 auto Opcode = BO->getOpcode();
14737 switch (Opcode) {
14738 default:
14739 break;
14740 case BO_Add:
14741 case BO_Sub: {
14742 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14743 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14744 std::swap(LHS, RHS);
14745 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14746 Ctx);
14747 }
14748 case BO_Comma:
14749 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14750 }
14751 break;
14752 }
14753 }
14754 return std::nullopt;
14755}
14756
14758 // See if we can compute the alignment of a VarDecl and an offset from it.
14759 std::optional<std::pair<CharUnits, CharUnits>> P =
14761
14762 if (P)
14763 return P->first.alignmentAtOffset(P->second);
14764
14765 // If that failed, return the type's alignment.
14767}
14768
14770 // This is actually a lot of work to potentially be doing on every
14771 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14772 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14773 return;
14774
14775 // Ignore dependent types.
14776 if (T->isDependentType() || Op->getType()->isDependentType())
14777 return;
14778
14779 // Require that the destination be a pointer type.
14780 const PointerType *DestPtr = T->getAs<PointerType>();
14781 if (!DestPtr) return;
14782
14783 // If the destination has alignment 1, we're done.
14784 QualType DestPointee = DestPtr->getPointeeType();
14785 if (DestPointee->isIncompleteType()) return;
14786 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14787 if (DestAlign.isOne()) return;
14788
14789 // Require that the source be a pointer type.
14790 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14791 if (!SrcPtr) return;
14792 QualType SrcPointee = SrcPtr->getPointeeType();
14793
14794 // Explicitly allow casts from cv void*. We already implicitly
14795 // allowed casts to cv void*, since they have alignment 1.
14796 // Also allow casts involving incomplete types, which implicitly
14797 // includes 'void'.
14798 if (SrcPointee->isIncompleteType()) return;
14799
14800 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14801
14802 if (SrcAlign >= DestAlign) return;
14803
14804 Diag(TRange.getBegin(), diag::warn_cast_align)
14805 << Op->getType() << T
14806 << static_cast<unsigned>(SrcAlign.getQuantity())
14807 << static_cast<unsigned>(DestAlign.getQuantity())
14808 << TRange << Op->getSourceRange();
14809}
14810
14811void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14812 const ArraySubscriptExpr *ASE,
14813 bool AllowOnePastEnd, bool IndexNegated) {
14814 // Already diagnosed by the constant evaluator.
14816 return;
14817
14818 IndexExpr = IndexExpr->IgnoreParenImpCasts();
14819 if (IndexExpr->isValueDependent())
14820 return;
14821
14822 const Type *EffectiveType =
14824 BaseExpr = BaseExpr->IgnoreParenCasts();
14825 const ConstantArrayType *ArrayTy =
14826 Context.getAsConstantArrayType(BaseExpr->getType());
14827
14829 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
14830
14831 const Type *BaseType =
14832 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14833 bool IsUnboundedArray =
14834 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
14835 Context, StrictFlexArraysLevel,
14836 /*IgnoreTemplateOrMacroSubstitution=*/true);
14837 if (EffectiveType->isDependentType() ||
14838 (!IsUnboundedArray && BaseType->isDependentType()))
14839 return;
14840
14842 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14843 return;
14844
14845 llvm::APSInt index = Result.Val.getInt();
14846 if (IndexNegated) {
14847 index.setIsUnsigned(false);
14848 index = -index;
14849 }
14850
14851 if (IsUnboundedArray) {
14852 if (EffectiveType->isFunctionType())
14853 return;
14854 if (index.isUnsigned() || !index.isNegative()) {
14855 const auto &ASTC = getASTContext();
14856 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
14857 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
14858 if (index.getBitWidth() < AddrBits)
14859 index = index.zext(AddrBits);
14860 std::optional<CharUnits> ElemCharUnits =
14861 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14862 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14863 // pointer) bounds-checking isn't meaningful.
14864 if (!ElemCharUnits || ElemCharUnits->isZero())
14865 return;
14866 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14867 // If index has more active bits than address space, we already know
14868 // we have a bounds violation to warn about. Otherwise, compute
14869 // address of (index + 1)th element, and warn about bounds violation
14870 // only if that address exceeds address space.
14871 if (index.getActiveBits() <= AddrBits) {
14872 bool Overflow;
14873 llvm::APInt Product(index);
14874 Product += 1;
14875 Product = Product.umul_ov(ElemBytes, Overflow);
14876 if (!Overflow && Product.getActiveBits() <= AddrBits)
14877 return;
14878 }
14879
14880 // Need to compute max possible elements in address space, since that
14881 // is included in diag message.
14882 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
14883 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
14884 MaxElems += 1;
14885 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
14886 MaxElems = MaxElems.udiv(ElemBytes);
14887
14888 unsigned DiagID =
14889 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
14890 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
14891
14892 // Diag message shows element size in bits and in "bytes" (platform-
14893 // dependent CharUnits)
14894 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14895 PDiag(DiagID) << index << AddrBits
14896 << (unsigned)ASTC.toBits(*ElemCharUnits)
14897 << ElemBytes << MaxElems
14898 << MaxElems.getZExtValue()
14899 << IndexExpr->getSourceRange());
14900
14901 const NamedDecl *ND = nullptr;
14902 // Try harder to find a NamedDecl to point at in the note.
14903 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14904 BaseExpr = ASE->getBase()->IgnoreParenCasts();
14905 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14906 ND = DRE->getDecl();
14907 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14908 ND = ME->getMemberDecl();
14909
14910 if (ND)
14911 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14912 PDiag(diag::note_array_declared_here) << ND);
14913 }
14914 return;
14915 }
14916
14917 if (index.isUnsigned() || !index.isNegative()) {
14918 // It is possible that the type of the base expression after
14919 // IgnoreParenCasts is incomplete, even though the type of the base
14920 // expression before IgnoreParenCasts is complete (see PR39746 for an
14921 // example). In this case we have no information about whether the array
14922 // access exceeds the array bounds. However we can still diagnose an array
14923 // access which precedes the array bounds.
14924 if (BaseType->isIncompleteType())
14925 return;
14926
14927 llvm::APInt size = ArrayTy->getSize();
14928
14929 if (BaseType != EffectiveType) {
14930 // Make sure we're comparing apples to apples when comparing index to
14931 // size.
14932 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14933 uint64_t array_typesize = Context.getTypeSize(BaseType);
14934
14935 // Handle ptrarith_typesize being zero, such as when casting to void*.
14936 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
14937 if (!ptrarith_typesize)
14938 ptrarith_typesize = Context.getCharWidth();
14939
14940 if (ptrarith_typesize != array_typesize) {
14941 // There's a cast to a different size type involved.
14942 uint64_t ratio = array_typesize / ptrarith_typesize;
14943
14944 // TODO: Be smarter about handling cases where array_typesize is not a
14945 // multiple of ptrarith_typesize.
14946 if (ptrarith_typesize * ratio == array_typesize)
14947 size *= llvm::APInt(size.getBitWidth(), ratio);
14948 }
14949 }
14950
14951 if (size.getBitWidth() > index.getBitWidth())
14952 index = index.zext(size.getBitWidth());
14953 else if (size.getBitWidth() < index.getBitWidth())
14954 size = size.zext(index.getBitWidth());
14955
14956 // For array subscripting the index must be less than size, but for pointer
14957 // arithmetic also allow the index (offset) to be equal to size since
14958 // computing the next address after the end of the array is legal and
14959 // commonly done e.g. in C++ iterators and range-based for loops.
14960 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14961 return;
14962
14963 // Suppress the warning if the subscript expression (as identified by the
14964 // ']' location) and the index expression are both from macro expansions
14965 // within a system header.
14966 if (ASE) {
14967 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14968 ASE->getRBracketLoc());
14969 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14970 SourceLocation IndexLoc =
14971 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14972 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14973 return;
14974 }
14975 }
14976
14977 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
14978 : diag::warn_ptr_arith_exceeds_bounds;
14979 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
14980 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
14981
14982 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14983 PDiag(DiagID)
14984 << index << ArrayTy->desugar() << CastMsg
14985 << CastMsgTy << IndexExpr->getSourceRange());
14986 } else {
14987 unsigned DiagID = diag::warn_array_index_precedes_bounds;
14988 if (!ASE) {
14989 DiagID = diag::warn_ptr_arith_precedes_bounds;
14990 if (index.isNegative()) index = -index;
14991 }
14992
14993 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14994 PDiag(DiagID) << index << IndexExpr->getSourceRange());
14995 }
14996
14997 const NamedDecl *ND = nullptr;
14998 // Try harder to find a NamedDecl to point at in the note.
14999 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15000 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15001 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15002 ND = DRE->getDecl();
15003 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15004 ND = ME->getMemberDecl();
15005
15006 if (ND)
15007 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15008 PDiag(diag::note_array_declared_here) << ND);
15009}
15010
15011void Sema::CheckArrayAccess(const Expr *expr) {
15012 int AllowOnePastEnd = 0;
15013 while (expr) {
15014 expr = expr->IgnoreParenImpCasts();
15015 switch (expr->getStmtClass()) {
15016 case Stmt::ArraySubscriptExprClass: {
15017 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15018 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15019 AllowOnePastEnd > 0);
15020 expr = ASE->getBase();
15021 break;
15022 }
15023 case Stmt::MemberExprClass: {
15024 expr = cast<MemberExpr>(expr)->getBase();
15025 break;
15026 }
15027 case Stmt::ArraySectionExprClass: {
15028 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
15029 // FIXME: We should probably be checking all of the elements to the
15030 // 'length' here as well.
15031 if (ASE->getLowerBound())
15032 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15033 /*ASE=*/nullptr, AllowOnePastEnd > 0);
15034 return;
15035 }
15036 case Stmt::UnaryOperatorClass: {
15037 // Only unwrap the * and & unary operators
15038 const UnaryOperator *UO = cast<UnaryOperator>(expr);
15039 expr = UO->getSubExpr();
15040 switch (UO->getOpcode()) {
15041 case UO_AddrOf:
15042 AllowOnePastEnd++;
15043 break;
15044 case UO_Deref:
15045 AllowOnePastEnd--;
15046 break;
15047 default:
15048 return;
15049 }
15050 break;
15051 }
15052 case Stmt::ConditionalOperatorClass: {
15053 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15054 if (const Expr *lhs = cond->getLHS())
15055 CheckArrayAccess(lhs);
15056 if (const Expr *rhs = cond->getRHS())
15057 CheckArrayAccess(rhs);
15058 return;
15059 }
15060 case Stmt::CXXOperatorCallExprClass: {
15061 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15062 for (const auto *Arg : OCE->arguments())
15063 CheckArrayAccess(Arg);
15064 return;
15065 }
15066 default:
15067 return;
15068 }
15069 }
15070}
15071
15073 Expr *RHS, bool isProperty) {
15074 // Check if RHS is an Objective-C object literal, which also can get
15075 // immediately zapped in a weak reference. Note that we explicitly
15076 // allow ObjCStringLiterals, since those are designed to never really die.
15077 RHS = RHS->IgnoreParenImpCasts();
15078
15079 // This enum needs to match with the 'select' in
15080 // warn_objc_arc_literal_assign (off-by-1).
15082 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
15083 return false;
15084
15085 S.Diag(Loc, diag::warn_arc_literal_assign)
15086 << (unsigned) Kind
15087 << (isProperty ? 0 : 1)
15088 << RHS->getSourceRange();
15089
15090 return true;
15091}
15092
15095 Expr *RHS, bool isProperty) {
15096 // Strip off any implicit cast added to get to the one ARC-specific.
15097 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15098 if (cast->getCastKind() == CK_ARCConsumeObject) {
15099 S.Diag(Loc, diag::warn_arc_retained_assign)
15101 << (isProperty ? 0 : 1)
15102 << RHS->getSourceRange();
15103 return true;
15104 }
15105 RHS = cast->getSubExpr();
15106 }
15107
15108 if (LT == Qualifiers::OCL_Weak &&
15109 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15110 return true;
15111
15112 return false;
15113}
15114
15116 QualType LHS, Expr *RHS) {
15118
15120 return false;
15121
15122 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15123 return true;
15124
15125 return false;
15126}
15127
15129 Expr *LHS, Expr *RHS) {
15130 QualType LHSType;
15131 // PropertyRef on LHS type need be directly obtained from
15132 // its declaration as it has a PseudoType.
15134 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15135 if (PRE && !PRE->isImplicitProperty()) {
15136 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15137 if (PD)
15138 LHSType = PD->getType();
15139 }
15140
15141 if (LHSType.isNull())
15142 LHSType = LHS->getType();
15143
15145
15146 if (LT == Qualifiers::OCL_Weak) {
15147 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15149 }
15150
15151 if (checkUnsafeAssigns(Loc, LHSType, RHS))
15152 return;
15153
15154 // FIXME. Check for other life times.
15155 if (LT != Qualifiers::OCL_None)
15156 return;
15157
15158 if (PRE) {
15159 if (PRE->isImplicitProperty())
15160 return;
15161 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15162 if (!PD)
15163 return;
15164
15165 unsigned Attributes = PD->getPropertyAttributes();
15166 if (Attributes & ObjCPropertyAttribute::kind_assign) {
15167 // when 'assign' attribute was not explicitly specified
15168 // by user, ignore it and rely on property type itself
15169 // for lifetime info.
15170 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15171 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15172 LHSType->isObjCRetainableType())
15173 return;
15174
15175 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15176 if (cast->getCastKind() == CK_ARCConsumeObject) {
15177 Diag(Loc, diag::warn_arc_retained_property_assign)
15178 << RHS->getSourceRange();
15179 return;
15180 }
15181 RHS = cast->getSubExpr();
15182 }
15183 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15184 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15185 return;
15186 }
15187 }
15188}
15189
15190//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15191
15192static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15193 SourceLocation StmtLoc,
15194 const NullStmt *Body) {
15195 // Do not warn if the body is a macro that expands to nothing, e.g:
15196 //
15197 // #define CALL(x)
15198 // if (condition)
15199 // CALL(0);
15200 if (Body->hasLeadingEmptyMacro())
15201 return false;
15202
15203 // Get line numbers of statement and body.
15204 bool StmtLineInvalid;
15205 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15206 &StmtLineInvalid);
15207 if (StmtLineInvalid)
15208 return false;
15209
15210 bool BodyLineInvalid;
15211 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15212 &BodyLineInvalid);
15213 if (BodyLineInvalid)
15214 return false;
15215
15216 // Warn if null statement and body are on the same line.
15217 if (StmtLine != BodyLine)
15218 return false;
15219
15220 return true;
15221}
15222
15224 const Stmt *Body,
15225 unsigned DiagID) {
15226 // Since this is a syntactic check, don't emit diagnostic for template
15227 // instantiations, this just adds noise.
15229 return;
15230
15231 // The body should be a null statement.
15232 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15233 if (!NBody)
15234 return;
15235
15236 // Do the usual checks.
15237 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15238 return;
15239
15240 Diag(NBody->getSemiLoc(), DiagID);
15241 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15242}
15243
15245 const Stmt *PossibleBody) {
15246 assert(!CurrentInstantiationScope); // Ensured by caller
15247
15248 SourceLocation StmtLoc;
15249 const Stmt *Body;
15250 unsigned DiagID;
15251 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15252 StmtLoc = FS->getRParenLoc();
15253 Body = FS->getBody();
15254 DiagID = diag::warn_empty_for_body;
15255 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15256 StmtLoc = WS->getRParenLoc();
15257 Body = WS->getBody();
15258 DiagID = diag::warn_empty_while_body;
15259 } else
15260 return; // Neither `for' nor `while'.
15261
15262 // The body should be a null statement.
15263 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15264 if (!NBody)
15265 return;
15266
15267 // Skip expensive checks if diagnostic is disabled.
15268 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15269 return;
15270
15271 // Do the usual checks.
15272 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15273 return;
15274
15275 // `for(...);' and `while(...);' are popular idioms, so in order to keep
15276 // noise level low, emit diagnostics only if for/while is followed by a
15277 // CompoundStmt, e.g.:
15278 // for (int i = 0; i < n; i++);
15279 // {
15280 // a(i);
15281 // }
15282 // or if for/while is followed by a statement with more indentation
15283 // than for/while itself:
15284 // for (int i = 0; i < n; i++);
15285 // a(i);
15286 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15287 if (!ProbableTypo) {
15288 bool BodyColInvalid;
15289 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15290 PossibleBody->getBeginLoc(), &BodyColInvalid);
15291 if (BodyColInvalid)
15292 return;
15293
15294 bool StmtColInvalid;
15295 unsigned StmtCol =
15296 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15297 if (StmtColInvalid)
15298 return;
15299
15300 if (BodyCol > StmtCol)
15301 ProbableTypo = true;
15302 }
15303
15304 if (ProbableTypo) {
15305 Diag(NBody->getSemiLoc(), DiagID);
15306 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15307 }
15308}
15309
15310//===--- CHECK: Warn on self move with std::move. -------------------------===//
15311
15312void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15313 SourceLocation OpLoc) {
15314 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15315 return;
15316
15318 return;
15319
15320 // Strip parens and casts away.
15321 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15322 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15323
15324 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
15325 // which we can treat as an inlined std::move
15326 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
15327 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
15328 RHSExpr = CE->getArg(0);
15329 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
15330 CXXSCE && CXXSCE->isXValue())
15331 RHSExpr = CXXSCE->getSubExpr();
15332 else
15333 return;
15334
15335 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15336 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15337
15338 // Two DeclRefExpr's, check that the decls are the same.
15339 if (LHSDeclRef && RHSDeclRef) {
15340 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15341 return;
15342 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15343 RHSDeclRef->getDecl()->getCanonicalDecl())
15344 return;
15345
15346 auto D = Diag(OpLoc, diag::warn_self_move)
15347 << LHSExpr->getType() << LHSExpr->getSourceRange()
15348 << RHSExpr->getSourceRange();
15349 if (const FieldDecl *F =
15351 D << 1 << F
15352 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15353 else
15354 D << 0;
15355 return;
15356 }
15357
15358 // Member variables require a different approach to check for self moves.
15359 // MemberExpr's are the same if every nested MemberExpr refers to the same
15360 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15361 // the base Expr's are CXXThisExpr's.
15362 const Expr *LHSBase = LHSExpr;
15363 const Expr *RHSBase = RHSExpr;
15364 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15365 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15366 if (!LHSME || !RHSME)
15367 return;
15368
15369 while (LHSME && RHSME) {
15370 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15371 RHSME->getMemberDecl()->getCanonicalDecl())
15372 return;
15373
15374 LHSBase = LHSME->getBase();
15375 RHSBase = RHSME->getBase();
15376 LHSME = dyn_cast<MemberExpr>(LHSBase);
15377 RHSME = dyn_cast<MemberExpr>(RHSBase);
15378 }
15379
15380 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15381 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15382 if (LHSDeclRef && RHSDeclRef) {
15383 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15384 return;
15385 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15386 RHSDeclRef->getDecl()->getCanonicalDecl())
15387 return;
15388
15389 Diag(OpLoc, diag::warn_self_move)
15390 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15391 << RHSExpr->getSourceRange();
15392 return;
15393 }
15394
15395 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15396 Diag(OpLoc, diag::warn_self_move)
15397 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15398 << RHSExpr->getSourceRange();
15399}
15400
15401//===--- Layout compatibility ----------------------------------------------//
15402
15403static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
15404
15405/// Check if two enumeration types are layout-compatible.
15406static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
15407 const EnumDecl *ED2) {
15408 // C++11 [dcl.enum] p8:
15409 // Two enumeration types are layout-compatible if they have the same
15410 // underlying type.
15411 return ED1->isComplete() && ED2->isComplete() &&
15412 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15413}
15414
15415/// Check if two fields are layout-compatible.
15416/// Can be used on union members, which are exempt from alignment requirement
15417/// of common initial sequence.
15418static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
15419 const FieldDecl *Field2,
15420 bool AreUnionMembers = false) {
15421#ifndef NDEBUG
15422 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
15423 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
15424 assert(((Field1Parent->isStructureOrClassType() &&
15425 Field2Parent->isStructureOrClassType()) ||
15426 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
15427 "Can't evaluate layout compatibility between a struct field and a "
15428 "union field.");
15429 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
15430 (AreUnionMembers && Field1Parent->isUnionType())) &&
15431 "AreUnionMembers should be 'true' for union fields (only).");
15432#endif
15433
15434 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15435 return false;
15436
15437 if (Field1->isBitField() != Field2->isBitField())
15438 return false;
15439
15440 if (Field1->isBitField()) {
15441 // Make sure that the bit-fields are the same length.
15442 unsigned Bits1 = Field1->getBitWidthValue();
15443 unsigned Bits2 = Field2->getBitWidthValue();
15444
15445 if (Bits1 != Bits2)
15446 return false;
15447 }
15448
15449 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
15450 Field2->hasAttr<clang::NoUniqueAddressAttr>())
15451 return false;
15452
15453 if (!AreUnionMembers &&
15454 Field1->getMaxAlignment() != Field2->getMaxAlignment())
15455 return false;
15456
15457 return true;
15458}
15459
15460/// Check if two standard-layout structs are layout-compatible.
15461/// (C++11 [class.mem] p17)
15462static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
15463 const RecordDecl *RD2) {
15464 // Get to the class where the fields are declared
15465 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
15466 RD1 = D1CXX->getStandardLayoutBaseWithFields();
15467
15468 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
15469 RD2 = D2CXX->getStandardLayoutBaseWithFields();
15470
15471 // Check the fields.
15472 return llvm::equal(RD1->fields(), RD2->fields(),
15473 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
15474 return isLayoutCompatible(C, F1, F2);
15475 });
15476}
15477
15478/// Check if two standard-layout unions are layout-compatible.
15479/// (C++11 [class.mem] p18)
15480static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
15481 const RecordDecl *RD2) {
15482 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
15483 RD2->fields());
15484
15485 for (auto *Field1 : RD1->fields()) {
15486 auto I = UnmatchedFields.begin();
15487 auto E = UnmatchedFields.end();
15488
15489 for ( ; I != E; ++I) {
15490 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
15491 bool Result = UnmatchedFields.erase(*I);
15492 (void) Result;
15493 assert(Result);
15494 break;
15495 }
15496 }
15497 if (I == E)
15498 return false;
15499 }
15500
15501 return UnmatchedFields.empty();
15502}
15503
15504static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
15505 const RecordDecl *RD2) {
15506 if (RD1->isUnion() != RD2->isUnion())
15507 return false;
15508
15509 if (RD1->isUnion())
15510 return isLayoutCompatibleUnion(C, RD1, RD2);
15511 else
15512 return isLayoutCompatibleStruct(C, RD1, RD2);
15513}
15514
15515/// Check if two types are layout-compatible in C++11 sense.
15516static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
15517 if (T1.isNull() || T2.isNull())
15518 return false;
15519
15520 // C++20 [basic.types] p11:
15521 // Two types cv1 T1 and cv2 T2 are layout-compatible types
15522 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
15523 // or layout-compatible standard-layout class types (11.4).
15526
15527 if (C.hasSameType(T1, T2))
15528 return true;
15529
15530 const Type::TypeClass TC1 = T1->getTypeClass();
15531 const Type::TypeClass TC2 = T2->getTypeClass();
15532
15533 if (TC1 != TC2)
15534 return false;
15535
15536 if (TC1 == Type::Enum)
15537 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
15538 if (TC1 == Type::Record) {
15539 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15540 return false;
15541
15543 T2->castAsRecordDecl());
15544 }
15545
15546 return false;
15547}
15548
15550 return isLayoutCompatible(getASTContext(), T1, T2);
15551}
15552
15553//===-------------- Pointer interconvertibility ----------------------------//
15554
15556 const TypeSourceInfo *Derived) {
15557 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
15558 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
15559
15560 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
15561 getASTContext().hasSameType(BaseT, DerivedT))
15562 return true;
15563
15564 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
15565 return false;
15566
15567 // Per [basic.compound]/4.3, containing object has to be standard-layout.
15568 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
15569 return true;
15570
15571 return false;
15572}
15573
15574//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15575
15576/// Given a type tag expression find the type tag itself.
15577///
15578/// \param TypeExpr Type tag expression, as it appears in user's code.
15579///
15580/// \param VD Declaration of an identifier that appears in a type tag.
15581///
15582/// \param MagicValue Type tag magic value.
15583///
15584/// \param isConstantEvaluated whether the evalaution should be performed in
15585
15586/// constant context.
15587static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15588 const ValueDecl **VD, uint64_t *MagicValue,
15589 bool isConstantEvaluated) {
15590 while(true) {
15591 if (!TypeExpr)
15592 return false;
15593
15594 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15595
15596 switch (TypeExpr->getStmtClass()) {
15597 case Stmt::UnaryOperatorClass: {
15598 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15599 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15600 TypeExpr = UO->getSubExpr();
15601 continue;
15602 }
15603 return false;
15604 }
15605
15606 case Stmt::DeclRefExprClass: {
15607 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15608 *VD = DRE->getDecl();
15609 return true;
15610 }
15611
15612 case Stmt::IntegerLiteralClass: {
15613 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15614 llvm::APInt MagicValueAPInt = IL->getValue();
15615 if (MagicValueAPInt.getActiveBits() <= 64) {
15616 *MagicValue = MagicValueAPInt.getZExtValue();
15617 return true;
15618 } else
15619 return false;
15620 }
15621
15622 case Stmt::BinaryConditionalOperatorClass:
15623 case Stmt::ConditionalOperatorClass: {
15624 const AbstractConditionalOperator *ACO =
15626 bool Result;
15627 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15628 isConstantEvaluated)) {
15629 if (Result)
15630 TypeExpr = ACO->getTrueExpr();
15631 else
15632 TypeExpr = ACO->getFalseExpr();
15633 continue;
15634 }
15635 return false;
15636 }
15637
15638 case Stmt::BinaryOperatorClass: {
15639 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15640 if (BO->getOpcode() == BO_Comma) {
15641 TypeExpr = BO->getRHS();
15642 continue;
15643 }
15644 return false;
15645 }
15646
15647 default:
15648 return false;
15649 }
15650 }
15651}
15652
15653/// Retrieve the C type corresponding to type tag TypeExpr.
15654///
15655/// \param TypeExpr Expression that specifies a type tag.
15656///
15657/// \param MagicValues Registered magic values.
15658///
15659/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15660/// kind.
15661///
15662/// \param TypeInfo Information about the corresponding C type.
15663///
15664/// \param isConstantEvaluated whether the evalaution should be performed in
15665/// constant context.
15666///
15667/// \returns true if the corresponding C type was found.
15669 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15670 const ASTContext &Ctx,
15671 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15672 *MagicValues,
15673 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15674 bool isConstantEvaluated) {
15675 FoundWrongKind = false;
15676
15677 // Variable declaration that has type_tag_for_datatype attribute.
15678 const ValueDecl *VD = nullptr;
15679
15680 uint64_t MagicValue;
15681
15682 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15683 return false;
15684
15685 if (VD) {
15686 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15687 if (I->getArgumentKind() != ArgumentKind) {
15688 FoundWrongKind = true;
15689 return false;
15690 }
15691 TypeInfo.Type = I->getMatchingCType();
15692 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15693 TypeInfo.MustBeNull = I->getMustBeNull();
15694 return true;
15695 }
15696 return false;
15697 }
15698
15699 if (!MagicValues)
15700 return false;
15701
15702 llvm::DenseMap<Sema::TypeTagMagicValue,
15704 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15705 if (I == MagicValues->end())
15706 return false;
15707
15708 TypeInfo = I->second;
15709 return true;
15710}
15711
15713 uint64_t MagicValue, QualType Type,
15714 bool LayoutCompatible,
15715 bool MustBeNull) {
15716 if (!TypeTagForDatatypeMagicValues)
15717 TypeTagForDatatypeMagicValues.reset(
15718 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15719
15720 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15721 (*TypeTagForDatatypeMagicValues)[Magic] =
15722 TypeTagData(Type, LayoutCompatible, MustBeNull);
15723}
15724
15725static bool IsSameCharType(QualType T1, QualType T2) {
15726 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15727 if (!BT1)
15728 return false;
15729
15730 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15731 if (!BT2)
15732 return false;
15733
15734 BuiltinType::Kind T1Kind = BT1->getKind();
15735 BuiltinType::Kind T2Kind = BT2->getKind();
15736
15737 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
15738 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
15739 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15740 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15741}
15742
15743void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15744 const ArrayRef<const Expr *> ExprArgs,
15745 SourceLocation CallSiteLoc) {
15746 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15747 bool IsPointerAttr = Attr->getIsPointer();
15748
15749 // Retrieve the argument representing the 'type_tag'.
15750 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15751 if (TypeTagIdxAST >= ExprArgs.size()) {
15752 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15753 << 0 << Attr->getTypeTagIdx().getSourceIndex();
15754 return;
15755 }
15756 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15757 bool FoundWrongKind;
15758 TypeTagData TypeInfo;
15759 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15760 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15761 TypeInfo, isConstantEvaluatedContext())) {
15762 if (FoundWrongKind)
15763 Diag(TypeTagExpr->getExprLoc(),
15764 diag::warn_type_tag_for_datatype_wrong_kind)
15765 << TypeTagExpr->getSourceRange();
15766 return;
15767 }
15768
15769 // Retrieve the argument representing the 'arg_idx'.
15770 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15771 if (ArgumentIdxAST >= ExprArgs.size()) {
15772 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15773 << 1 << Attr->getArgumentIdx().getSourceIndex();
15774 return;
15775 }
15776 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15777 if (IsPointerAttr) {
15778 // Skip implicit cast of pointer to `void *' (as a function argument).
15779 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15780 if (ICE->getType()->isVoidPointerType() &&
15781 ICE->getCastKind() == CK_BitCast)
15782 ArgumentExpr = ICE->getSubExpr();
15783 }
15784 QualType ArgumentType = ArgumentExpr->getType();
15785
15786 // Passing a `void*' pointer shouldn't trigger a warning.
15787 if (IsPointerAttr && ArgumentType->isVoidPointerType())
15788 return;
15789
15790 if (TypeInfo.MustBeNull) {
15791 // Type tag with matching void type requires a null pointer.
15792 if (!ArgumentExpr->isNullPointerConstant(Context,
15794 Diag(ArgumentExpr->getExprLoc(),
15795 diag::warn_type_safety_null_pointer_required)
15796 << ArgumentKind->getName()
15797 << ArgumentExpr->getSourceRange()
15798 << TypeTagExpr->getSourceRange();
15799 }
15800 return;
15801 }
15802
15803 QualType RequiredType = TypeInfo.Type;
15804 if (IsPointerAttr)
15805 RequiredType = Context.getPointerType(RequiredType);
15806
15807 bool mismatch = false;
15808 if (!TypeInfo.LayoutCompatible) {
15809 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15810
15811 // C++11 [basic.fundamental] p1:
15812 // Plain char, signed char, and unsigned char are three distinct types.
15813 //
15814 // But we treat plain `char' as equivalent to `signed char' or `unsigned
15815 // char' depending on the current char signedness mode.
15816 if (mismatch)
15817 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15818 RequiredType->getPointeeType())) ||
15819 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15820 mismatch = false;
15821 } else
15822 if (IsPointerAttr)
15823 mismatch = !isLayoutCompatible(Context,
15824 ArgumentType->getPointeeType(),
15825 RequiredType->getPointeeType());
15826 else
15827 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15828
15829 if (mismatch)
15830 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15831 << ArgumentType << ArgumentKind
15832 << TypeInfo.LayoutCompatible << RequiredType
15833 << ArgumentExpr->getSourceRange()
15834 << TypeTagExpr->getSourceRange();
15835}
15836
15837void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15838 CharUnits Alignment) {
15839 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
15840 Alignment);
15841}
15842
15844 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
15845 const NamedDecl *ND = m.RD;
15846 if (ND->getName().empty()) {
15847 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15848 ND = TD;
15849 }
15850 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15851 << m.MD << ND << m.E->getSourceRange();
15852 }
15854}
15855
15857 E = E->IgnoreParens();
15858 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
15859 return;
15860 if (isa<UnaryOperator>(E) &&
15861 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15862 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15863 if (isa<MemberExpr>(Op)) {
15864 auto &MisalignedMembersForExpr =
15866 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
15867 if (MA != MisalignedMembersForExpr.end() &&
15868 (T->isDependentType() || T->isIntegerType() ||
15869 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15870 Context.getTypeAlignInChars(
15871 T->getPointeeType()) <= MA->Alignment))))
15872 MisalignedMembersForExpr.erase(MA);
15873 }
15874 }
15875}
15876
15878 Expr *E,
15879 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15880 Action) {
15881 const auto *ME = dyn_cast<MemberExpr>(E);
15882 if (!ME)
15883 return;
15884
15885 // No need to check expressions with an __unaligned-qualified type.
15886 if (E->getType().getQualifiers().hasUnaligned())
15887 return;
15888
15889 // For a chain of MemberExpr like "a.b.c.d" this list
15890 // will keep FieldDecl's like [d, c, b].
15891 SmallVector<FieldDecl *, 4> ReverseMemberChain;
15892 const MemberExpr *TopME = nullptr;
15893 bool AnyIsPacked = false;
15894 do {
15895 QualType BaseType = ME->getBase()->getType();
15896 if (BaseType->isDependentType())
15897 return;
15898 if (ME->isArrow())
15899 BaseType = BaseType->getPointeeType();
15900 auto *RD = BaseType->castAsRecordDecl();
15901 if (RD->isInvalidDecl())
15902 return;
15903
15904 ValueDecl *MD = ME->getMemberDecl();
15905 auto *FD = dyn_cast<FieldDecl>(MD);
15906 // We do not care about non-data members.
15907 if (!FD || FD->isInvalidDecl())
15908 return;
15909
15910 AnyIsPacked =
15911 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15912 ReverseMemberChain.push_back(FD);
15913
15914 TopME = ME;
15915 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15916 } while (ME);
15917 assert(TopME && "We did not compute a topmost MemberExpr!");
15918
15919 // Not the scope of this diagnostic.
15920 if (!AnyIsPacked)
15921 return;
15922
15923 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15924 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15925 // TODO: The innermost base of the member expression may be too complicated.
15926 // For now, just disregard these cases. This is left for future
15927 // improvement.
15928 if (!DRE && !isa<CXXThisExpr>(TopBase))
15929 return;
15930
15931 // Alignment expected by the whole expression.
15932 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15933
15934 // No need to do anything else with this case.
15935 if (ExpectedAlignment.isOne())
15936 return;
15937
15938 // Synthesize offset of the whole access.
15939 CharUnits Offset;
15940 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
15941 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
15942
15943 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15944 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15945 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
15946
15947 // The base expression of the innermost MemberExpr may give
15948 // stronger guarantees than the class containing the member.
15949 if (DRE && !TopME->isArrow()) {
15950 const ValueDecl *VD = DRE->getDecl();
15951 if (!VD->getType()->isReferenceType())
15952 CompleteObjectAlignment =
15953 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15954 }
15955
15956 // Check if the synthesized offset fulfills the alignment.
15957 if (!Offset.isMultipleOf(ExpectedAlignment) ||
15958 // It may fulfill the offset it but the effective alignment may still be
15959 // lower than the expected expression alignment.
15960 CompleteObjectAlignment < ExpectedAlignment) {
15961 // If this happens, we want to determine a sensible culprit of this.
15962 // Intuitively, watching the chain of member expressions from right to
15963 // left, we start with the required alignment (as required by the field
15964 // type) but some packed attribute in that chain has reduced the alignment.
15965 // It may happen that another packed structure increases it again. But if
15966 // we are here such increase has not been enough. So pointing the first
15967 // FieldDecl that either is packed or else its RecordDecl is,
15968 // seems reasonable.
15969 FieldDecl *FD = nullptr;
15970 CharUnits Alignment;
15971 for (FieldDecl *FDI : ReverseMemberChain) {
15972 if (FDI->hasAttr<PackedAttr>() ||
15973 FDI->getParent()->hasAttr<PackedAttr>()) {
15974 FD = FDI;
15975 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
15976 Context.getTypeAlignInChars(
15977 Context.getCanonicalTagType(FD->getParent())));
15978 break;
15979 }
15980 }
15981 assert(FD && "We did not find a packed FieldDecl!");
15982 Action(E, FD->getParent(), FD, Alignment);
15983 }
15984}
15985
15986void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15987 using namespace std::placeholders;
15988
15990 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15991 _2, _3, _4));
15992}
15993
15994// Performs a similar job to Sema::UsualUnaryConversions, but without any
15995// implicit promotion of integral/enumeration types.
15997 // First, convert to an r-value.
15999 if (Res.isInvalid())
16000 return ExprError();
16001
16002 // Promote floating-point types.
16003 return S.UsualUnaryFPConversions(Res.get());
16004}
16005
16007 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16008 if (checkArgCount(TheCall, 1))
16009 return true;
16010
16011 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
16012 if (A.isInvalid())
16013 return true;
16014
16015 TheCall->setArg(0, A.get());
16016 QualType TyA = A.get()->getType();
16017
16018 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
16019 ArgTyRestr, 1))
16020 return true;
16021
16022 TheCall->setType(TyA);
16023 return false;
16024}
16025
16026bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
16027 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16028 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
16029 TheCall->setType(*Res);
16030 return false;
16031 }
16032 return true;
16033}
16034
16036 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
16037 if (!Res)
16038 return true;
16039
16040 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
16041 TheCall->setType(VecTy0->getElementType());
16042 else
16043 TheCall->setType(*Res);
16044
16045 return false;
16046}
16047
16049 SourceLocation Loc) {
16051 R = RHS->getEnumCoercedType(S.Context);
16052 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
16054 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
16055 << LHS->getSourceRange() << RHS->getSourceRange()
16056 << /*Arithmetic Between*/ 0 << L << R;
16057 }
16058 return false;
16059}
16060
16061/// Check if all arguments have the same type. If the types don't match, emit an
16062/// error message and return true. Otherwise return false.
16063///
16064/// For scalars we directly compare their unqualified types. But even if we
16065/// compare unqualified vector types, a difference in qualifiers in the element
16066/// types can make the vector types be considered not equal. For example,
16067/// vector of 4 'const float' values vs vector of 4 'float' values.
16068/// So we compare unqualified types of their elements and number of elements.
16070 ArrayRef<Expr *> Args) {
16071 assert(!Args.empty() && "Should have at least one argument.");
16072
16073 Expr *Arg0 = Args.front();
16074 QualType Ty0 = Arg0->getType();
16075
16076 auto EmitError = [&](Expr *ArgI) {
16077 SemaRef.Diag(Arg0->getBeginLoc(),
16078 diag::err_typecheck_call_different_arg_types)
16079 << Arg0->getType() << ArgI->getType();
16080 };
16081
16082 // Compare scalar types.
16083 if (!Ty0->isVectorType()) {
16084 for (Expr *ArgI : Args.drop_front())
16085 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
16086 EmitError(ArgI);
16087 return true;
16088 }
16089
16090 return false;
16091 }
16092
16093 // Compare vector types.
16094 const auto *Vec0 = Ty0->castAs<VectorType>();
16095 for (Expr *ArgI : Args.drop_front()) {
16096 const auto *VecI = ArgI->getType()->getAs<VectorType>();
16097 if (!VecI ||
16098 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
16099 VecI->getElementType()) ||
16100 Vec0->getNumElements() != VecI->getNumElements()) {
16101 EmitError(ArgI);
16102 return true;
16103 }
16104 }
16105
16106 return false;
16107}
16108
16109std::optional<QualType>
16111 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16112 if (checkArgCount(TheCall, 2))
16113 return std::nullopt;
16114
16116 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
16117 return std::nullopt;
16118
16119 Expr *Args[2];
16120 for (int I = 0; I < 2; ++I) {
16121 ExprResult Converted =
16122 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16123 if (Converted.isInvalid())
16124 return std::nullopt;
16125 Args[I] = Converted.get();
16126 }
16127
16128 SourceLocation LocA = Args[0]->getBeginLoc();
16129 QualType TyA = Args[0]->getType();
16130
16131 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
16132 return std::nullopt;
16133
16134 if (checkBuiltinVectorMathArgTypes(*this, Args))
16135 return std::nullopt;
16136
16137 TheCall->setArg(0, Args[0]);
16138 TheCall->setArg(1, Args[1]);
16139 return TyA;
16140}
16141
16143 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16144 if (checkArgCount(TheCall, 3))
16145 return true;
16146
16147 SourceLocation Loc = TheCall->getExprLoc();
16148 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
16149 TheCall->getArg(1), Loc) ||
16150 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
16151 TheCall->getArg(2), Loc))
16152 return true;
16153
16154 Expr *Args[3];
16155 for (int I = 0; I < 3; ++I) {
16156 ExprResult Converted =
16157 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16158 if (Converted.isInvalid())
16159 return true;
16160 Args[I] = Converted.get();
16161 }
16162
16163 int ArgOrdinal = 1;
16164 for (Expr *Arg : Args) {
16165 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
16166 ArgTyRestr, ArgOrdinal++))
16167 return true;
16168 }
16169
16170 if (checkBuiltinVectorMathArgTypes(*this, Args))
16171 return true;
16172
16173 for (int I = 0; I < 3; ++I)
16174 TheCall->setArg(I, Args[I]);
16175
16176 TheCall->setType(Args[0]->getType());
16177 return false;
16178}
16179
16180bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
16181 if (checkArgCount(TheCall, 1))
16182 return true;
16183
16184 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16185 if (A.isInvalid())
16186 return true;
16187
16188 TheCall->setArg(0, A.get());
16189 return false;
16190}
16191
16192bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
16193 if (checkArgCount(TheCall, 1))
16194 return true;
16195
16196 ExprResult Arg = TheCall->getArg(0);
16197 QualType TyArg = Arg.get()->getType();
16198
16199 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
16200 return Diag(TheCall->getArg(0)->getBeginLoc(),
16201 diag::err_builtin_invalid_arg_type)
16202 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
16203
16204 TheCall->setType(TyArg);
16205 return false;
16206}
16207
16208ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
16209 ExprResult CallResult) {
16210 if (checkArgCount(TheCall, 1))
16211 return ExprError();
16212
16213 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16214 if (MatrixArg.isInvalid())
16215 return MatrixArg;
16216 Expr *Matrix = MatrixArg.get();
16217
16218 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16219 if (!MType) {
16220 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16221 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
16222 << Matrix->getType();
16223 return ExprError();
16224 }
16225
16226 // Create returned matrix type by swapping rows and columns of the argument
16227 // matrix type.
16228 QualType ResultType = Context.getConstantMatrixType(
16229 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16230
16231 // Change the return type to the type of the returned matrix.
16232 TheCall->setType(ResultType);
16233
16234 // Update call argument to use the possibly converted matrix argument.
16235 TheCall->setArg(0, Matrix);
16236 return CallResult;
16237}
16238
16239// Get and verify the matrix dimensions.
16240static std::optional<unsigned>
16242 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
16243 if (!Value) {
16244 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16245 << Name;
16246 return {};
16247 }
16248 uint64_t Dim = Value->getZExtValue();
16249 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
16250 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16251 << Name << S.Context.getLangOpts().MaxMatrixDimension;
16252 return {};
16253 }
16254 return Dim;
16255}
16256
16257ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16258 ExprResult CallResult) {
16259 if (!getLangOpts().MatrixTypes) {
16260 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16261 return ExprError();
16262 }
16263
16264 if (checkArgCount(TheCall, 4))
16265 return ExprError();
16266
16267 unsigned PtrArgIdx = 0;
16268 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16269 Expr *RowsExpr = TheCall->getArg(1);
16270 Expr *ColumnsExpr = TheCall->getArg(2);
16271 Expr *StrideExpr = TheCall->getArg(3);
16272
16273 bool ArgError = false;
16274
16275 // Check pointer argument.
16276 {
16278 if (PtrConv.isInvalid())
16279 return PtrConv;
16280 PtrExpr = PtrConv.get();
16281 TheCall->setArg(0, PtrExpr);
16282 if (PtrExpr->isTypeDependent()) {
16283 TheCall->setType(Context.DependentTy);
16284 return TheCall;
16285 }
16286 }
16287
16288 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16289 QualType ElementTy;
16290 if (!PtrTy) {
16291 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16292 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
16293 << PtrExpr->getType();
16294 ArgError = true;
16295 } else {
16296 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16297
16299 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16300 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
16301 << /* no fp */ 0 << PtrExpr->getType();
16302 ArgError = true;
16303 }
16304 }
16305
16306 // Apply default Lvalue conversions and convert the expression to size_t.
16307 auto ApplyArgumentConversions = [this](Expr *E) {
16309 if (Conv.isInvalid())
16310 return Conv;
16311
16312 return tryConvertExprToType(Conv.get(), Context.getSizeType());
16313 };
16314
16315 // Apply conversion to row and column expressions.
16316 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16317 if (!RowsConv.isInvalid()) {
16318 RowsExpr = RowsConv.get();
16319 TheCall->setArg(1, RowsExpr);
16320 } else
16321 RowsExpr = nullptr;
16322
16323 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16324 if (!ColumnsConv.isInvalid()) {
16325 ColumnsExpr = ColumnsConv.get();
16326 TheCall->setArg(2, ColumnsExpr);
16327 } else
16328 ColumnsExpr = nullptr;
16329
16330 // If any part of the result matrix type is still pending, just use
16331 // Context.DependentTy, until all parts are resolved.
16332 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16333 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16334 TheCall->setType(Context.DependentTy);
16335 return CallResult;
16336 }
16337
16338 // Check row and column dimensions.
16339 std::optional<unsigned> MaybeRows;
16340 if (RowsExpr)
16341 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16342
16343 std::optional<unsigned> MaybeColumns;
16344 if (ColumnsExpr)
16345 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16346
16347 // Check stride argument.
16348 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16349 if (StrideConv.isInvalid())
16350 return ExprError();
16351 StrideExpr = StrideConv.get();
16352 TheCall->setArg(3, StrideExpr);
16353
16354 if (MaybeRows) {
16355 if (std::optional<llvm::APSInt> Value =
16356 StrideExpr->getIntegerConstantExpr(Context)) {
16357 uint64_t Stride = Value->getZExtValue();
16358 if (Stride < *MaybeRows) {
16359 Diag(StrideExpr->getBeginLoc(),
16360 diag::err_builtin_matrix_stride_too_small);
16361 ArgError = true;
16362 }
16363 }
16364 }
16365
16366 if (ArgError || !MaybeRows || !MaybeColumns)
16367 return ExprError();
16368
16369 TheCall->setType(
16370 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16371 return CallResult;
16372}
16373
16374ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16375 ExprResult CallResult) {
16376 if (checkArgCount(TheCall, 3))
16377 return ExprError();
16378
16379 unsigned PtrArgIdx = 1;
16380 Expr *MatrixExpr = TheCall->getArg(0);
16381 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16382 Expr *StrideExpr = TheCall->getArg(2);
16383
16384 bool ArgError = false;
16385
16386 {
16387 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16388 if (MatrixConv.isInvalid())
16389 return MatrixConv;
16390 MatrixExpr = MatrixConv.get();
16391 TheCall->setArg(0, MatrixExpr);
16392 }
16393 if (MatrixExpr->isTypeDependent()) {
16394 TheCall->setType(Context.DependentTy);
16395 return TheCall;
16396 }
16397
16398 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16399 if (!MatrixTy) {
16400 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16401 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
16402 ArgError = true;
16403 }
16404
16405 {
16407 if (PtrConv.isInvalid())
16408 return PtrConv;
16409 PtrExpr = PtrConv.get();
16410 TheCall->setArg(1, PtrExpr);
16411 if (PtrExpr->isTypeDependent()) {
16412 TheCall->setType(Context.DependentTy);
16413 return TheCall;
16414 }
16415 }
16416
16417 // Check pointer argument.
16418 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16419 if (!PtrTy) {
16420 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16421 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
16422 << PtrExpr->getType();
16423 ArgError = true;
16424 } else {
16425 QualType ElementTy = PtrTy->getPointeeType();
16426 if (ElementTy.isConstQualified()) {
16427 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16428 ArgError = true;
16429 }
16430 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16431 if (MatrixTy &&
16432 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16433 Diag(PtrExpr->getBeginLoc(),
16434 diag::err_builtin_matrix_pointer_arg_mismatch)
16435 << ElementTy << MatrixTy->getElementType();
16436 ArgError = true;
16437 }
16438 }
16439
16440 // Apply default Lvalue conversions and convert the stride expression to
16441 // size_t.
16442 {
16443 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16444 if (StrideConv.isInvalid())
16445 return StrideConv;
16446
16447 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16448 if (StrideConv.isInvalid())
16449 return StrideConv;
16450 StrideExpr = StrideConv.get();
16451 TheCall->setArg(2, StrideExpr);
16452 }
16453
16454 // Check stride argument.
16455 if (MatrixTy) {
16456 if (std::optional<llvm::APSInt> Value =
16457 StrideExpr->getIntegerConstantExpr(Context)) {
16458 uint64_t Stride = Value->getZExtValue();
16459 if (Stride < MatrixTy->getNumRows()) {
16460 Diag(StrideExpr->getBeginLoc(),
16461 diag::err_builtin_matrix_stride_too_small);
16462 ArgError = true;
16463 }
16464 }
16465 }
16466
16467 if (ArgError)
16468 return ExprError();
16469
16470 return CallResult;
16471}
16472
16474 const NamedDecl *Callee) {
16475 // This warning does not make sense in code that has no runtime behavior.
16477 return;
16478
16479 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
16480
16481 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
16482 return;
16483
16484 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16485 // all TCBs the callee is a part of.
16486 llvm::StringSet<> CalleeTCBs;
16487 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
16488 CalleeTCBs.insert(A->getTCBName());
16489 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
16490 CalleeTCBs.insert(A->getTCBName());
16491
16492 // Go through the TCBs the caller is a part of and emit warnings if Caller
16493 // is in a TCB that the Callee is not.
16494 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
16495 StringRef CallerTCB = A->getTCBName();
16496 if (CalleeTCBs.count(CallerTCB) == 0) {
16497 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
16498 << Callee << CallerTCB;
16499 }
16500 }
16501}
Defines the clang::ASTContext interface.
#define V(N, I)
Provides definitions for the various language-specific address spaces.
Defines the Diagnostic-related interfaces.
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)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
std::shared_ptr< TokenRole > Role
A token can have a special role that can carry extra information about the token's formatting.
unsigned IsFirst
Indicates that this is the first token of the file.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
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)
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 bool isInvalidOSLogArgTypeForCodeGen(FormatStringType FSType, QualType T)
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 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.
static ExprResult BuiltinMaskedScatter(Sema &S, CallExpr *TheCall)
#define BUILTIN_ROW(x)
static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_{clzg,ctzg} was called with a first argument, which is an unsigned integer,...
static 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 CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg, unsigned Pos, bool AllowConst, bool AllowAS)
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)
static ExprResult BuiltinMaskedGather(Sema &S, CallExpr *TheCall)
MathCheck
static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall)
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.
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.
__DEVICE__ int min(int __a, int __b)
__device__ __2f16 float __ockl_bool s
@ GE_None
No error.
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatch
The conversion specifier and the argument types are incompatible.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ MatchPromotion
The conversion specifier and the argument type are compatible because of default argument promotions.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
@ NoMatchTypeConfusion
The conversion specifier and the argument type are compatible, but still seems likely to be an error.
@ NoMatchPromotionTypeConfusion
The conversion specifier and the argument type are compatible but still seems likely to be an error.
unsigned getLength() const
const char * toString() const
const char * getStart() const
const char * getStart() const
HowSpecified getHowSpecified() const
unsigned getConstantAmount() const
unsigned getConstantLength() const
bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx, bool IsObjCLiteral)
Changes the specifier and length according to a QualType, retaining any flags or options.
void toString(raw_ostream &os) const
bool fixType(QualType QT, QualType RawQT, const LangOptions &LangOpt, ASTContext &Ctx)
void toString(raw_ostream &os) const
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
const LValueBase getLValueBase() const
Definition APValue.cpp:983
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:220
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
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
IdentifierTable & Idents
Definition ASTContext.h:772
Builtin::Context & BuiltinInfo
Definition ASTContext.h:774
const LangOptions & getLangOpts() const
Definition ASTContext.h:926
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.
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
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType CharTy
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
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:825
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.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
CanQualType UnsignedIntTy
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.
CanQualType UnsignedShortTy
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
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...
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:891
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.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
@ GE_None
No error.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getNonVirtualAlignment() const
getNonVirtualAlignment - Get the non-virtual alignment (in chars) of an object, which is the alignmen...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4287
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4465
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4471
SourceLocation getQuestionLoc() const
Definition Expr.h:4314
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4477
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Expr * getBase()
Get base of the array section.
Definition Expr.h:7183
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7187
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2721
SourceLocation getRBracketLoc() const
Definition Expr.h:2769
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2750
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3722
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3736
QualType getElementType() const
Definition TypeBase.h:3734
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6814
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:6963
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:6945
Attr - This represents one attribute.
Definition Attr.h:44
const char * getSpelling() const
Type source information for an attributed type.
Definition TypeLoc.h:1008
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:1022
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3972
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4105
Expr * getLHS() const
Definition Expr.h:4022
SourceLocation getOperatorLoc() const
Definition Expr.h:4014
SourceLocation getExprLoc() const
Definition Expr.h:4013
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2128
Expr * getRHS() const
Definition Expr.h:4024
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4058
Opcode getOpcode() const
Definition Expr.h:4017
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4069
BinaryOperatorKind Opcode
Definition Expr.h:3977
Pointer to a block type.
Definition TypeBase.h:3542
This class is used for builtin types like 'int'.
Definition TypeBase.h:3164
bool isInteger() const
Definition TypeBase.h:3225
bool isFloatingPoint() const
Definition TypeBase.h:3237
bool isSignedInteger() const
Definition TypeBase.h:3229
bool isUnsignedInteger() const
Definition TypeBase.h:3233
Kind getKind() const
Definition TypeBase.h:3212
std::string getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition Builtins.cpp:85
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
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:3903
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:5143
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5183
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:2877
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3081
SourceLocation getBeginLoc() const
Definition Expr.h:3211
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3094
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:3134
arg_iterator arg_end()
Definition Expr.h:3137
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3060
bool isCallToStdMove() const
Definition Expr.cpp:3619
Expr * getCallee()
Definition Expr.h:3024
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3068
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3170
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3071
arg_range arguments()
Definition Expr.h:3129
SourceLocation getEndLoc() const
Definition Expr.h:3230
SourceLocation getRParenLoc() const
Definition Expr.h:3208
Decl * getCalleeDecl()
Definition Expr.h:3054
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:3026
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition Expr.h:3113
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.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3610
path_iterator path_begin()
Definition Expr.h:3680
CastKind getCastKind() const
Definition Expr.h:3654
path_iterator path_end()
Definition Expr.h:3681
Expr * getSubExpr()
Definition Expr.h:3660
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
bool isOne() const
isOne - Test whether the quantity equals one.
Definition CharUnits.h:125
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
ConditionalOperator - The ?
Definition Expr.h:4325
Expr * getLHS() const
Definition Expr.h:4359
Expr * getRHS() const
Definition Expr.h:4360
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3760
QualType desugar() const
Definition TypeBase.h:3861
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3816
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:346
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:5552
Expr * getOperand() const
Definition ExprCXX.h:5326
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 isStdNamespace() const
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:1270
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:1363
ValueDecl * getDecl()
Definition Expr.h:1338
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1468
SourceLocation getBeginLoc() const
Definition Expr.h:1349
SourceLocation getLocation() const
Definition Expr.h:1346
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:449
T * getAttr() const
Definition DeclBase.h:573
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:560
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
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:809
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:951
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3423
Represents an enum.
Definition Decl.h:4007
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4230
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4171
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:3090
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
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
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...
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3085
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3073
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:3081
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:4203
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:831
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:835
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:451
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:3077
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:3665
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
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3065
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:802
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:811
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:814
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:804
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:4042
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:4267
Represents a member of a struct/union/class.
Definition Decl.h:3160
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3263
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4741
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3276
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
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:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
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:103
llvm::APFloat getValue() const
Definition Expr.h:1666
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2888
Represents a function declaration or definition.
Definition Decl.h:2000
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4542
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3751
param_iterator param_end()
Definition Decl.h:2787
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3854
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
param_iterator param_begin()
Definition Decl.h:2786
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3122
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4318
bool isStatic() const
Definition Decl.h:2929
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4133
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4119
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3815
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5254
unsigned getNumParams() const
Definition TypeBase.h:5532
QualType getParamType(unsigned i) const
Definition TypeBase.h:5534
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5658
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5543
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5653
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5539
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4450
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4759
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4755
QualType getReturnType() const
Definition TypeBase.h:4790
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:3787
Describes an C or C++ initializer list.
Definition Expr.h:5233
ArrayRef< Expr * > inits()
Definition Expr.h:5283
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...
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
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
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:4358
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3298
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3381
Expr * getBase() const
Definition Expr.h:3375
bool isArrow() const
Definition Expr.h:3482
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3653
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
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:592
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
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:290
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2182
Represents a parameter to a function.
Definition Decl.h:1790
Pointer-authentication qualifiers.
Definition TypeBase.h:152
@ MaxDiscriminator
The maximum supported pointer-authentication discriminator.
Definition TypeBase.h:232
bool isAddressDiscriminated() const
Definition TypeBase.h:265
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
QualType getPointeeType() const
Definition TypeBase.h:3338
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6690
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5071
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8362
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2866
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1453
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:8278
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8404
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8318
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:8330
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8372
void removeLocalVolatile()
Definition TypeBase.h:8394
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1179
void removeLocalConst()
Definition TypeBase.h:8386
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8351
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8399
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1670
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8324
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:4312
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4398
field_range fields() const
Definition Decl.h:4515
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4390
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
bool isSEHExceptScope() const
Determine whether this scope is a SEH '__except' block.
Definition Scope.h:616
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:287
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)
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)
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.
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
void adornBoolConversionDiagWithTernaryFixit(const Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder)
bool isSignedCharBool(QualType Ty)
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...
void checkDictionaryLiteral(QualType TargetType, ObjCDictionaryLiteral *DictionaryLiteral)
Check an Objective-C dictionary literal being converted to the given target type.
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)
bool CheckSPIRVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
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:854
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...
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:1420
bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum, unsigned ArgBits)
BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is a constant expression represen...
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...
bool BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum, unsigned Multiple)
BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr TheCall is a constant expr...
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:12996
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1120
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.
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:9306
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9314
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9351
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...
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull)
Register a magic integral constant to be used as a type tag.
bool isValidPointerAttrType(QualType T, bool RefOkay=false)
Determine if type T is a valid subject for a nonnull and similar attributes.
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
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....
void CheckFloatComparison(SourceLocation Loc, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
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:6905
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:2049
SemaHexagon & Hexagon()
Definition Sema.h:1460
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:833
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
SemaX86 & X86()
Definition Sema.h:1550
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
ASTContext & Context
Definition Sema.h:1283
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:922
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:1490
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:754
ASTContext & getASTContext() const
Definition Sema.h:925
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)
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:2589
bool BuiltinVectorToScalarMath(CallExpr *TheCall)
bool BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum, llvm::APSInt &Result)
BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr TheCall is a constant expression.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1191
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
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:2701
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low, int High, bool RangeIsError=true)
BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr TheCall is a constant express...
bool IsLayoutCompatible(QualType T1, QualType T2) const
const LangOptions & getLangOpts() const
Definition Sema.h:918
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
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:1435
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.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
SemaDirectX & DirectX()
Definition Sema.h:1450
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:1281
static const uint64_t MaximumAlignment
Definition Sema.h:1214
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:952
SemaHLSL & HLSL()
Definition Sema.h:1455
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1475
SemaRISCV & RISCV()
Definition Sema.h:1520
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:2767
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:6938
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)
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1314
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
Definition Sema.h:2669
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition Sema.h:15338
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:639
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:1418
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:1500
FormatArgumentPassingKind
Definition Sema.h:2599
@ FAPK_Elsewhere
Definition Sema.h:2603
@ FAPK_Fixed
Definition Sema.h:2600
@ FAPK_Variadic
Definition Sema.h:2601
@ FAPK_VAList
Definition Sema.h:2602
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:8145
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:13900
SourceManager & getSourceManager() const
Definition Sema.h:923
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.
ExprResult BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl=DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr=nullptr, SourceLocation opLoc=SourceLocation())
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:224
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.
bool isConstantEvaluatedContext() const
Definition Sema.h:2591
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.
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
SemaPPC & PPC()
Definition Sema.h:1510
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1246
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:1540
bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, unsigned ArgNum, unsigned ArgBits)
BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of TheCall is a constant expression re...
SourceManager & SourceMgr
Definition Sema.h:1286
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:783
DiagnosticsEngine & Diags
Definition Sema.h:1285
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
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...
SemaNVPTX & NVPTX()
Definition Sema.h:1485
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
bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum)
BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a constant expression representing ...
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,...
@ AbstractParamType
Definition Sema.h:6210
SemaSPIRV & SPIRV()
Definition Sema.h:1525
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.
SemaLoongArch & LoongArch()
Definition Sema.h:1465
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6398
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:1545
SemaARM & ARM()
Definition Sema.h:1425
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:4577
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.
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.
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.
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:362
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:299
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:338
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:350
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1973
bool isUTF8() const
Definition Expr.h:1918
bool isWide() const
Definition Expr.h:1917
bool isPascal() const
Definition Expr.h:1922
unsigned getLength() const
Definition Expr.h:1909
StringLiteralKind getKind() const
Definition Expr.h:1912
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:1920
unsigned getByteLength() const
Definition Expr.h:1908
StringRef getString() const
Definition Expr.h:1867
bool isUTF16() const
Definition Expr.h:1919
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.h:1974
bool isOrdinary() const
Definition Expr.h:1916
unsigned getCharByteWidth() const
Definition Expr.h:1910
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3832
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3812
bool isUnion() const
Definition Decl.h:3922
Exposes information about the current target.
Definition TargetInfo.h:226
virtual bool supportsCpuSupports() const
virtual bool validateCpuIs(StringRef Name) const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
IntType getSizeType() const
Definition TargetInfo.h:385
virtual bool validateCpuSupports(StringRef Name) const
virtual bool supportsCpuIs() const
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
@ Type
The template argument is a type.
The base class of all kinds of template declarations (e.g., class, function, etc.).
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:2706
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:6165
A container of type source information.
Definition TypeBase.h:8249
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8260
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isBlockPointerType() const
Definition TypeBase.h:8535
bool isVoidType() const
Definition TypeBase.h:8871
bool isBooleanType() const
Definition TypeBase.h:9001
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2225
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9051
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:787
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2205
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2273
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2115
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:9031
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:2066
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:2425
bool isArrayType() const
Definition TypeBase.h:8614
bool isCharType() const
Definition Type.cpp:2132
bool isFunctionPointerType() const
Definition TypeBase.h:8582
bool isPointerType() const
Definition TypeBase.h:8515
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8915
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9158
bool isReferenceType() const
Definition TypeBase.h:8539
bool isEnumeralType() const
Definition TypeBase.h:8646
bool isScalarType() const
Definition TypeBase.h:8973
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:8626
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2607
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isExtVectorType() const
Definition TypeBase.h:8658
bool isExtVectorBoolType() const
Definition TypeBase.h:8662
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2646
bool isBitIntType() const
Definition TypeBase.h:8780
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8840
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8638
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2243
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3119
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2557
bool isAtomicType() const
Definition TypeBase.h:8697
bool isFunctionProtoType() const
Definition TypeBase.h:2601
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition Type.cpp:3074
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:2800
bool isUnscopedEnumerationType() const
Definition Type.cpp:2125
bool isObjCObjectType() const
Definition TypeBase.h:8688
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9144
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9007
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2510
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:2435
bool isFunctionType() const
Definition TypeBase.h:8511
bool isObjCObjectPointerType() const
Definition TypeBase.h:8684
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2312
bool isStructureOrClassType() const
Definition Type.cpp:706
bool isVectorType() const
Definition TypeBase.h:8654
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2320
bool isFloatingType() const
Definition Type.cpp:2304
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:2253
bool isAnyPointerType() const
Definition TypeBase.h:8523
TypeClass getTypeClass() const
Definition TypeBase.h:2385
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2411
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9091
bool isNullPtrType() const
Definition TypeBase.h:8908
bool isRecordType() const
Definition TypeBase.h:8642
bool isObjCRetainableType() const
Definition Type.cpp:5283
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5014
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2569
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition Type.cpp:2634
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2625
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
Expr * getSubExpr() const
Definition Expr.h:2285
Opcode getOpcode() const
Definition Expr.h:2280
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2362
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
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3399
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5501
Represents a variable declaration or definition.
Definition Decl.h:926
Represents a GCC generic vector type.
Definition TypeBase.h:4175
unsigned getNumElements() const
Definition TypeBase.h:4190
QualType getElementType() const
Definition TypeBase.h:4189
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2697
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
std::optional< ConversionSpecifier > getStandardSpecifier() const
const OptionalAmount & getFieldWidth() const
bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const
const LengthModifier & getLengthModifier() const
bool hasValidLengthModifier(const TargetInfo &Target, const LangOptions &LO) const
std::optional< LengthModifier > getCorrectedLengthModifier() const
ArgType getArgType(ASTContext &Ctx) const
Class representing optional flags with location and representation information.
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
const OptionalFlag & isPrivate() const
const OptionalAmount & getPrecision() const
const OptionalFlag & hasSpacePrefix() const
const OptionalFlag & isSensitive() const
const OptionalFlag & isLeftJustified() const
const OptionalFlag & hasLeadingZeros() const
const OptionalFlag & hasAlternativeForm() const
const PrintfConversionSpecifier & getConversionSpecifier() const
const OptionalFlag & hasPlusPrefix() const
const OptionalFlag & hasThousandsGrouping() const
ArgType getArgType(ASTContext &Ctx, bool IsObjCLiteral) const
Returns the builtin type that a data argument paired with this format specifier should have.
const OptionalFlag & isPublic() const
const ScanfConversionSpecifier & getConversionSpecifier() const
ArgType getArgType(ASTContext &Ctx) const
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
#define bool
Definition gpuintrin.h:32
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition SPIR.cpp:35
Definition SPIR.cpp:47
Common components of both fprintf and fscanf format strings.
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)
Pieces specific to fprintf format strings.
Pieces specific to fscanf format strings.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< PointerType > pointerType
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
uint32_t Literal
Literals are represented as positive integers.
Definition CNFFormula.h:35
ComparisonResult
Indicates the result of a tentative comparison.
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition Types.cpp:216
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ 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 LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1267
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:2503
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.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:816
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
Expr * IgnoreElidableImplicitConstructorSingleStep(Expr *E)
Definition IgnoreExpr.h:125
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
VariadicCallType
Definition Sema.h:511
bool hasSpecificAttr(const Container &container)
@ Arithmetic
An arithmetic operation.
Definition Sema.h:661
@ Comparison
A comparison.
Definition Sema.h:665
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
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.
Definition Parser.h:65
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)
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:124
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Register
Definition Specifiers.h:257
Expr * Cond
};
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition JsonSupport.h:21
SemaARM::ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD)
Definition SemaARM.cpp:545
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
const FunctionProtoType * T
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:562
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:497
CastKind
CastKind - The kind of operation required for a conversion.
BuiltinCountedByRefKind
Definition Sema.h:519
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
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())
Expr * IgnoreImplicitAsWrittenSingleStep(Expr *E)
Definition IgnoreExpr.h:137
StringLiteralKind
Definition Expr.h:1763
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_Win64
Definition Specifiers.h:285
@ CC_X86_64SysV
Definition Specifiers.h:286
@ Generic
not a target-specific vector type
Definition TypeBase.h:4136
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5874
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5867
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1746
unsigned long uint64_t
long int64_t
#define false
Definition stdbool.h:26
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:5339
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.
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13170
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13196
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13186
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13142
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6799
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2611
#define log2(__x)
Definition tgmath.h:970